PackageManagerService.java revision c066205cea051c6d9f386188b9cb426c03dbee2d
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_DEVICE_ADMIN; 72import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 73import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 74import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 75import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 76import static android.content.pm.PackageManager.PERMISSION_DENIED; 77import static android.content.pm.PackageManager.PERMISSION_GRANTED; 78import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 79import static android.content.pm.PackageParser.isApkFile; 80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 81import static android.system.OsConstants.O_CREAT; 82import static android.system.OsConstants.O_RDWR; 83 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 88import static com.android.internal.util.ArrayUtils.appendInt; 89import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.annotation.UserIdInt; 106import android.app.ActivityManager; 107import android.app.AppOpsManager; 108import android.app.IActivityManager; 109import android.app.ResourcesManager; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.ContentResolver; 116import android.content.Context; 117import android.content.IIntentReceiver; 118import android.content.Intent; 119import android.content.IntentFilter; 120import android.content.IntentSender; 121import android.content.IntentSender.SendIntentException; 122import android.content.ServiceConnection; 123import android.content.pm.ActivityInfo; 124import android.content.pm.ApplicationInfo; 125import android.content.pm.AppsQueryHelper; 126import android.content.pm.ComponentInfo; 127import android.content.pm.EphemeralApplicationInfo; 128import android.content.pm.EphemeralRequest; 129import android.content.pm.EphemeralResolveInfo; 130import android.content.pm.EphemeralResponse; 131import android.content.pm.FeatureInfo; 132import android.content.pm.IOnPermissionsChangeListener; 133import android.content.pm.IPackageDataObserver; 134import android.content.pm.IPackageDeleteObserver; 135import android.content.pm.IPackageDeleteObserver2; 136import android.content.pm.IPackageInstallObserver2; 137import android.content.pm.IPackageInstaller; 138import android.content.pm.IPackageManager; 139import android.content.pm.IPackageMoveObserver; 140import android.content.pm.IPackageStatsObserver; 141import android.content.pm.InstrumentationInfo; 142import android.content.pm.IntentFilterVerificationInfo; 143import android.content.pm.KeySet; 144import android.content.pm.PackageCleanItem; 145import android.content.pm.PackageInfo; 146import android.content.pm.PackageInfoLite; 147import android.content.pm.PackageInstaller; 148import android.content.pm.PackageManager; 149import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 150import android.content.pm.PackageManagerInternal; 151import android.content.pm.PackageParser; 152import android.content.pm.PackageParser.ActivityIntentInfo; 153import android.content.pm.PackageParser.PackageLite; 154import android.content.pm.PackageParser.PackageParserException; 155import android.content.pm.PackageStats; 156import android.content.pm.PackageUserState; 157import android.content.pm.ParceledListSlice; 158import android.content.pm.PermissionGroupInfo; 159import android.content.pm.PermissionInfo; 160import android.content.pm.ProviderInfo; 161import android.content.pm.ResolveInfo; 162import android.content.pm.ServiceInfo; 163import android.content.pm.Signature; 164import android.content.pm.UserInfo; 165import android.content.pm.VerifierDeviceIdentity; 166import android.content.pm.VerifierInfo; 167import android.content.res.Resources; 168import android.graphics.Bitmap; 169import android.hardware.display.DisplayManager; 170import android.net.Uri; 171import android.os.Binder; 172import android.os.Build; 173import android.os.Bundle; 174import android.os.Debug; 175import android.os.Environment; 176import android.os.Environment.UserEnvironment; 177import android.os.FileUtils; 178import android.os.Handler; 179import android.os.IBinder; 180import android.os.Looper; 181import android.os.Message; 182import android.os.Parcel; 183import android.os.ParcelFileDescriptor; 184import android.os.PatternMatcher; 185import android.os.Process; 186import android.os.RemoteCallbackList; 187import android.os.RemoteException; 188import android.os.ResultReceiver; 189import android.os.SELinux; 190import android.os.ServiceManager; 191import android.os.ShellCallback; 192import android.os.SystemClock; 193import android.os.SystemProperties; 194import android.os.Trace; 195import android.os.UserHandle; 196import android.os.UserManager; 197import android.os.UserManagerInternal; 198import android.os.storage.IStorageManager; 199import android.os.storage.StorageManagerInternal; 200import android.os.storage.StorageEventListener; 201import android.os.storage.StorageManager; 202import android.os.storage.VolumeInfo; 203import android.os.storage.VolumeRecord; 204import android.provider.Settings.Global; 205import android.provider.Settings.Secure; 206import android.security.KeyStore; 207import android.security.SystemKeyStore; 208import android.system.ErrnoException; 209import android.system.Os; 210import android.text.TextUtils; 211import android.text.format.DateUtils; 212import android.util.ArrayMap; 213import android.util.ArraySet; 214import android.util.Base64; 215import android.util.DisplayMetrics; 216import android.util.EventLog; 217import android.util.ExceptionUtils; 218import android.util.Log; 219import android.util.LogPrinter; 220import android.util.MathUtils; 221import android.util.Pair; 222import android.util.PrintStreamPrinter; 223import android.util.Slog; 224import android.util.SparseArray; 225import android.util.SparseBooleanArray; 226import android.util.SparseIntArray; 227import android.util.Xml; 228import android.util.jar.StrictJarFile; 229import android.view.Display; 230 231import com.android.internal.R; 232import com.android.internal.annotations.GuardedBy; 233import com.android.internal.app.IMediaContainerService; 234import com.android.internal.app.ResolverActivity; 235import com.android.internal.content.NativeLibraryHelper; 236import com.android.internal.content.PackageHelper; 237import com.android.internal.logging.MetricsLogger; 238import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 239import com.android.internal.os.IParcelFileDescriptorFactory; 240import com.android.internal.os.RoSystemProperties; 241import com.android.internal.os.SomeArgs; 242import com.android.internal.os.Zygote; 243import com.android.internal.telephony.CarrierAppUtils; 244import com.android.internal.util.ArrayUtils; 245import com.android.internal.util.FastPrintWriter; 246import com.android.internal.util.FastXmlSerializer; 247import com.android.internal.util.IndentingPrintWriter; 248import com.android.internal.util.Preconditions; 249import com.android.internal.util.XmlUtils; 250import com.android.server.AttributeCache; 251import com.android.server.EventLogTags; 252import com.android.server.FgThread; 253import com.android.server.IntentResolver; 254import com.android.server.LocalServices; 255import com.android.server.ServiceThread; 256import com.android.server.SystemConfig; 257import com.android.server.Watchdog; 258import com.android.server.net.NetworkPolicyManagerInternal; 259import com.android.server.pm.Installer.InstallerException; 260import com.android.server.pm.PermissionsState.PermissionState; 261import com.android.server.pm.Settings.DatabaseVersion; 262import com.android.server.pm.Settings.VersionInfo; 263import com.android.server.pm.dex.DexManager; 264import com.android.server.storage.DeviceStorageMonitorInternal; 265 266import dalvik.system.CloseGuard; 267import dalvik.system.DexFile; 268import dalvik.system.VMRuntime; 269 270import libcore.io.IoUtils; 271import libcore.util.EmptyArray; 272 273import org.xmlpull.v1.XmlPullParser; 274import org.xmlpull.v1.XmlPullParserException; 275import org.xmlpull.v1.XmlSerializer; 276 277import java.io.BufferedOutputStream; 278import java.io.BufferedReader; 279import java.io.ByteArrayInputStream; 280import java.io.ByteArrayOutputStream; 281import java.io.File; 282import java.io.FileDescriptor; 283import java.io.FileInputStream; 284import java.io.FileNotFoundException; 285import java.io.FileOutputStream; 286import java.io.FileReader; 287import java.io.FilenameFilter; 288import java.io.IOException; 289import java.io.PrintWriter; 290import java.nio.charset.StandardCharsets; 291import java.security.DigestInputStream; 292import java.security.MessageDigest; 293import java.security.NoSuchAlgorithmException; 294import java.security.PublicKey; 295import java.security.SecureRandom; 296import java.security.cert.Certificate; 297import java.security.cert.CertificateEncodingException; 298import java.security.cert.CertificateException; 299import java.text.SimpleDateFormat; 300import java.util.ArrayList; 301import java.util.Arrays; 302import java.util.Collection; 303import java.util.Collections; 304import java.util.Comparator; 305import java.util.Date; 306import java.util.HashSet; 307import java.util.HashMap; 308import java.util.Iterator; 309import java.util.List; 310import java.util.Map; 311import java.util.Objects; 312import java.util.Set; 313import java.util.concurrent.CountDownLatch; 314import java.util.concurrent.TimeUnit; 315import java.util.concurrent.atomic.AtomicBoolean; 316import java.util.concurrent.atomic.AtomicInteger; 317 318/** 319 * Keep track of all those APKs everywhere. 320 * <p> 321 * Internally there are two important locks: 322 * <ul> 323 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 324 * and other related state. It is a fine-grained lock that should only be held 325 * momentarily, as it's one of the most contended locks in the system. 326 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 327 * operations typically involve heavy lifting of application data on disk. Since 328 * {@code installd} is single-threaded, and it's operations can often be slow, 329 * this lock should never be acquired while already holding {@link #mPackages}. 330 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 331 * holding {@link #mInstallLock}. 332 * </ul> 333 * Many internal methods rely on the caller to hold the appropriate locks, and 334 * this contract is expressed through method name suffixes: 335 * <ul> 336 * <li>fooLI(): the caller must hold {@link #mInstallLock} 337 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 338 * being modified must be frozen 339 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 340 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 341 * </ul> 342 * <p> 343 * Because this class is very central to the platform's security; please run all 344 * CTS and unit tests whenever making modifications: 345 * 346 * <pre> 347 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 348 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 349 * </pre> 350 */ 351public class PackageManagerService extends IPackageManager.Stub { 352 static final String TAG = "PackageManager"; 353 static final boolean DEBUG_SETTINGS = false; 354 static final boolean DEBUG_PREFERRED = false; 355 static final boolean DEBUG_UPGRADE = false; 356 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 357 private static final boolean DEBUG_BACKUP = false; 358 private static final boolean DEBUG_INSTALL = false; 359 private static final boolean DEBUG_REMOVE = false; 360 private static final boolean DEBUG_BROADCASTS = false; 361 private static final boolean DEBUG_SHOW_INFO = false; 362 private static final boolean DEBUG_PACKAGE_INFO = false; 363 private static final boolean DEBUG_INTENT_MATCHING = false; 364 private static final boolean DEBUG_PACKAGE_SCANNING = false; 365 private static final boolean DEBUG_VERIFY = false; 366 private static final boolean DEBUG_FILTERS = false; 367 368 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 369 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 370 // user, but by default initialize to this. 371 static final boolean DEBUG_DEXOPT = false; 372 373 private static final boolean DEBUG_ABI_SELECTION = false; 374 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 375 private static final boolean DEBUG_TRIAGED_MISSING = false; 376 private static final boolean DEBUG_APP_DATA = false; 377 378 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 379 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 380 381 private static final boolean DISABLE_EPHEMERAL_APPS = false; 382 private static final boolean HIDE_EPHEMERAL_APIS = true; 383 384 private static final int RADIO_UID = Process.PHONE_UID; 385 private static final int LOG_UID = Process.LOG_UID; 386 private static final int NFC_UID = Process.NFC_UID; 387 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 388 private static final int SHELL_UID = Process.SHELL_UID; 389 390 // Cap the size of permission trees that 3rd party apps can define 391 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 392 393 // Suffix used during package installation when copying/moving 394 // package apks to install directory. 395 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 396 397 static final int SCAN_NO_DEX = 1<<1; 398 static final int SCAN_FORCE_DEX = 1<<2; 399 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 400 static final int SCAN_NEW_INSTALL = 1<<4; 401 static final int SCAN_UPDATE_TIME = 1<<5; 402 static final int SCAN_BOOTING = 1<<6; 403 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 404 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 405 static final int SCAN_REPLACING = 1<<9; 406 static final int SCAN_REQUIRE_KNOWN = 1<<10; 407 static final int SCAN_MOVE = 1<<11; 408 static final int SCAN_INITIAL = 1<<12; 409 static final int SCAN_CHECK_ONLY = 1<<13; 410 static final int SCAN_DONT_KILL_APP = 1<<14; 411 static final int SCAN_IGNORE_FROZEN = 1<<15; 412 static final int REMOVE_CHATTY = 1<<16; 413 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 414 415 private static final int[] EMPTY_INT_ARRAY = new int[0]; 416 417 /** 418 * Timeout (in milliseconds) after which the watchdog should declare that 419 * our handler thread is wedged. The usual default for such things is one 420 * minute but we sometimes do very lengthy I/O operations on this thread, 421 * such as installing multi-gigabyte applications, so ours needs to be longer. 422 */ 423 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 424 425 /** 426 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 427 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 428 * settings entry if available, otherwise we use the hardcoded default. If it's been 429 * more than this long since the last fstrim, we force one during the boot sequence. 430 * 431 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 432 * one gets run at the next available charging+idle time. This final mandatory 433 * no-fstrim check kicks in only of the other scheduling criteria is never met. 434 */ 435 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 436 437 /** 438 * Whether verification is enabled by default. 439 */ 440 private static final boolean DEFAULT_VERIFY_ENABLE = true; 441 442 /** 443 * The default maximum time to wait for the verification agent to return in 444 * milliseconds. 445 */ 446 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 447 448 /** 449 * The default response for package verification timeout. 450 * 451 * This can be either PackageManager.VERIFICATION_ALLOW or 452 * PackageManager.VERIFICATION_REJECT. 453 */ 454 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 455 456 static final String PLATFORM_PACKAGE_NAME = "android"; 457 458 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 459 460 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 461 DEFAULT_CONTAINER_PACKAGE, 462 "com.android.defcontainer.DefaultContainerService"); 463 464 private static final String KILL_APP_REASON_GIDS_CHANGED = 465 "permission grant or revoke changed gids"; 466 467 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 468 "permissions revoked"; 469 470 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 471 472 private static final String PACKAGE_SCHEME = "package"; 473 474 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 475 /** 476 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 477 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 478 * VENDOR_OVERLAY_DIR. 479 */ 480 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 481 /** 482 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 483 * is in VENDOR_OVERLAY_THEME_PROPERTY. 484 */ 485 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 486 = "persist.vendor.overlay.theme"; 487 488 /** Permission grant: not grant the permission. */ 489 private static final int GRANT_DENIED = 1; 490 491 /** Permission grant: grant the permission as an install permission. */ 492 private static final int GRANT_INSTALL = 2; 493 494 /** Permission grant: grant the permission as a runtime one. */ 495 private static final int GRANT_RUNTIME = 3; 496 497 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 498 private static final int GRANT_UPGRADE = 4; 499 500 /** Canonical intent used to identify what counts as a "web browser" app */ 501 private static final Intent sBrowserIntent; 502 static { 503 sBrowserIntent = new Intent(); 504 sBrowserIntent.setAction(Intent.ACTION_VIEW); 505 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 506 sBrowserIntent.setData(Uri.parse("http:")); 507 } 508 509 /** 510 * The set of all protected actions [i.e. those actions for which a high priority 511 * intent filter is disallowed]. 512 */ 513 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 514 static { 515 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 516 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 517 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 518 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 519 } 520 521 // Compilation reasons. 522 public static final int REASON_FIRST_BOOT = 0; 523 public static final int REASON_BOOT = 1; 524 public static final int REASON_INSTALL = 2; 525 public static final int REASON_BACKGROUND_DEXOPT = 3; 526 public static final int REASON_AB_OTA = 4; 527 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 528 public static final int REASON_SHARED_APK = 6; 529 public static final int REASON_FORCED_DEXOPT = 7; 530 public static final int REASON_CORE_APP = 8; 531 532 public static final int REASON_LAST = REASON_CORE_APP; 533 534 /** Special library name that skips shared libraries check during compilation. */ 535 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 536 537 /** All dangerous permission names in the same order as the events in MetricsEvent */ 538 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 539 Manifest.permission.READ_CALENDAR, 540 Manifest.permission.WRITE_CALENDAR, 541 Manifest.permission.CAMERA, 542 Manifest.permission.READ_CONTACTS, 543 Manifest.permission.WRITE_CONTACTS, 544 Manifest.permission.GET_ACCOUNTS, 545 Manifest.permission.ACCESS_FINE_LOCATION, 546 Manifest.permission.ACCESS_COARSE_LOCATION, 547 Manifest.permission.RECORD_AUDIO, 548 Manifest.permission.READ_PHONE_STATE, 549 Manifest.permission.CALL_PHONE, 550 Manifest.permission.READ_CALL_LOG, 551 Manifest.permission.WRITE_CALL_LOG, 552 Manifest.permission.ADD_VOICEMAIL, 553 Manifest.permission.USE_SIP, 554 Manifest.permission.PROCESS_OUTGOING_CALLS, 555 Manifest.permission.READ_CELL_BROADCASTS, 556 Manifest.permission.BODY_SENSORS, 557 Manifest.permission.SEND_SMS, 558 Manifest.permission.RECEIVE_SMS, 559 Manifest.permission.READ_SMS, 560 Manifest.permission.RECEIVE_WAP_PUSH, 561 Manifest.permission.RECEIVE_MMS, 562 Manifest.permission.READ_EXTERNAL_STORAGE, 563 Manifest.permission.WRITE_EXTERNAL_STORAGE, 564 Manifest.permission.READ_PHONE_NUMBER); 565 566 final ServiceThread mHandlerThread; 567 568 final PackageHandler mHandler; 569 570 private final ProcessLoggingHandler mProcessLoggingHandler; 571 572 /** 573 * Messages for {@link #mHandler} that need to wait for system ready before 574 * being dispatched. 575 */ 576 private ArrayList<Message> mPostSystemReadyMessages; 577 578 final int mSdkVersion = Build.VERSION.SDK_INT; 579 580 final Context mContext; 581 final boolean mFactoryTest; 582 final boolean mOnlyCore; 583 final DisplayMetrics mMetrics; 584 final int mDefParseFlags; 585 final String[] mSeparateProcesses; 586 final boolean mIsUpgrade; 587 final boolean mIsPreNUpgrade; 588 final boolean mIsPreNMR1Upgrade; 589 590 @GuardedBy("mPackages") 591 private boolean mDexOptDialogShown; 592 593 /** The location for ASEC container files on internal storage. */ 594 final String mAsecInternalPath; 595 596 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 597 // LOCK HELD. Can be called with mInstallLock held. 598 @GuardedBy("mInstallLock") 599 final Installer mInstaller; 600 601 /** Directory where installed third-party apps stored */ 602 final File mAppInstallDir; 603 final File mEphemeralInstallDir; 604 605 /** 606 * Directory to which applications installed internally have their 607 * 32 bit native libraries copied. 608 */ 609 private File mAppLib32InstallDir; 610 611 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 612 // apps. 613 final File mDrmAppPrivateInstallDir; 614 615 // ---------------------------------------------------------------- 616 617 // Lock for state used when installing and doing other long running 618 // operations. Methods that must be called with this lock held have 619 // the suffix "LI". 620 final Object mInstallLock = new Object(); 621 622 // ---------------------------------------------------------------- 623 624 // Keys are String (package name), values are Package. This also serves 625 // as the lock for the global state. Methods that must be called with 626 // this lock held have the prefix "LP". 627 @GuardedBy("mPackages") 628 final ArrayMap<String, PackageParser.Package> mPackages = 629 new ArrayMap<String, PackageParser.Package>(); 630 631 final ArrayMap<String, Set<String>> mKnownCodebase = 632 new ArrayMap<String, Set<String>>(); 633 634 // Tracks available target package names -> overlay package paths. 635 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 636 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 637 638 /** 639 * Tracks new system packages [received in an OTA] that we expect to 640 * find updated user-installed versions. Keys are package name, values 641 * are package location. 642 */ 643 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 644 /** 645 * Tracks high priority intent filters for protected actions. During boot, certain 646 * filter actions are protected and should never be allowed to have a high priority 647 * intent filter for them. However, there is one, and only one exception -- the 648 * setup wizard. It must be able to define a high priority intent filter for these 649 * actions to ensure there are no escapes from the wizard. We need to delay processing 650 * of these during boot as we need to look at all of the system packages in order 651 * to know which component is the setup wizard. 652 */ 653 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 654 /** 655 * Whether or not processing protected filters should be deferred. 656 */ 657 private boolean mDeferProtectedFilters = true; 658 659 /** 660 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 661 */ 662 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 663 /** 664 * Whether or not system app permissions should be promoted from install to runtime. 665 */ 666 boolean mPromoteSystemApps; 667 668 @GuardedBy("mPackages") 669 final Settings mSettings; 670 671 /** 672 * Set of package names that are currently "frozen", which means active 673 * surgery is being done on the code/data for that package. The platform 674 * will refuse to launch frozen packages to avoid race conditions. 675 * 676 * @see PackageFreezer 677 */ 678 @GuardedBy("mPackages") 679 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 680 681 final ProtectedPackages mProtectedPackages; 682 683 boolean mFirstBoot; 684 685 // System configuration read by SystemConfig. 686 final int[] mGlobalGids; 687 final SparseArray<ArraySet<String>> mSystemPermissions; 688 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 689 690 // If mac_permissions.xml was found for seinfo labeling. 691 boolean mFoundPolicyFile; 692 693 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 694 695 public static final class SharedLibraryEntry { 696 public final String path; 697 public final String apk; 698 699 SharedLibraryEntry(String _path, String _apk) { 700 path = _path; 701 apk = _apk; 702 } 703 } 704 705 // Currently known shared libraries. 706 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 707 new ArrayMap<String, SharedLibraryEntry>(); 708 709 // All available activities, for your resolving pleasure. 710 final ActivityIntentResolver mActivities = 711 new ActivityIntentResolver(); 712 713 // All available receivers, for your resolving pleasure. 714 final ActivityIntentResolver mReceivers = 715 new ActivityIntentResolver(); 716 717 // All available services, for your resolving pleasure. 718 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 719 720 // All available providers, for your resolving pleasure. 721 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 722 723 // Mapping from provider base names (first directory in content URI codePath) 724 // to the provider information. 725 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 726 new ArrayMap<String, PackageParser.Provider>(); 727 728 // Mapping from instrumentation class names to info about them. 729 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 730 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 731 732 // Mapping from permission names to info about them. 733 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 734 new ArrayMap<String, PackageParser.PermissionGroup>(); 735 736 // Packages whose data we have transfered into another package, thus 737 // should no longer exist. 738 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 739 740 // Broadcast actions that are only available to the system. 741 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 742 743 /** List of packages waiting for verification. */ 744 final SparseArray<PackageVerificationState> mPendingVerification 745 = new SparseArray<PackageVerificationState>(); 746 747 /** Set of packages associated with each app op permission. */ 748 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 749 750 final PackageInstallerService mInstallerService; 751 752 private final PackageDexOptimizer mPackageDexOptimizer; 753 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 754 // is used by other apps). 755 private final DexManager mDexManager; 756 757 private AtomicInteger mNextMoveId = new AtomicInteger(); 758 private final MoveCallbacks mMoveCallbacks; 759 760 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 761 762 // Cache of users who need badging. 763 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 764 765 /** Token for keys in mPendingVerification. */ 766 private int mPendingVerificationToken = 0; 767 768 volatile boolean mSystemReady; 769 volatile boolean mSafeMode; 770 volatile boolean mHasSystemUidErrors; 771 772 ApplicationInfo mAndroidApplication; 773 final ActivityInfo mResolveActivity = new ActivityInfo(); 774 final ResolveInfo mResolveInfo = new ResolveInfo(); 775 ComponentName mResolveComponentName; 776 PackageParser.Package mPlatformPackage; 777 ComponentName mCustomResolverComponentName; 778 779 boolean mResolverReplaced = false; 780 781 private final @Nullable ComponentName mIntentFilterVerifierComponent; 782 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 783 784 private int mIntentFilterVerificationToken = 0; 785 786 /** The service connection to the ephemeral resolver */ 787 final EphemeralResolverConnection mEphemeralResolverConnection; 788 789 /** Component used to install ephemeral applications */ 790 ComponentName mEphemeralInstallerComponent; 791 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 792 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 793 794 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 795 = new SparseArray<IntentFilterVerificationState>(); 796 797 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 798 799 // List of packages names to keep cached, even if they are uninstalled for all users 800 private List<String> mKeepUninstalledPackages; 801 802 private UserManagerInternal mUserManagerInternal; 803 804 private static class IFVerificationParams { 805 PackageParser.Package pkg; 806 boolean replacing; 807 int userId; 808 int verifierUid; 809 810 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 811 int _userId, int _verifierUid) { 812 pkg = _pkg; 813 replacing = _replacing; 814 userId = _userId; 815 replacing = _replacing; 816 verifierUid = _verifierUid; 817 } 818 } 819 820 private interface IntentFilterVerifier<T extends IntentFilter> { 821 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 822 T filter, String packageName); 823 void startVerifications(int userId); 824 void receiveVerificationResponse(int verificationId); 825 } 826 827 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 828 private Context mContext; 829 private ComponentName mIntentFilterVerifierComponent; 830 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 831 832 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 833 mContext = context; 834 mIntentFilterVerifierComponent = verifierComponent; 835 } 836 837 private String getDefaultScheme() { 838 return IntentFilter.SCHEME_HTTPS; 839 } 840 841 @Override 842 public void startVerifications(int userId) { 843 // Launch verifications requests 844 int count = mCurrentIntentFilterVerifications.size(); 845 for (int n=0; n<count; n++) { 846 int verificationId = mCurrentIntentFilterVerifications.get(n); 847 final IntentFilterVerificationState ivs = 848 mIntentFilterVerificationStates.get(verificationId); 849 850 String packageName = ivs.getPackageName(); 851 852 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 853 final int filterCount = filters.size(); 854 ArraySet<String> domainsSet = new ArraySet<>(); 855 for (int m=0; m<filterCount; m++) { 856 PackageParser.ActivityIntentInfo filter = filters.get(m); 857 domainsSet.addAll(filter.getHostsList()); 858 } 859 synchronized (mPackages) { 860 if (mSettings.createIntentFilterVerificationIfNeededLPw( 861 packageName, domainsSet) != null) { 862 scheduleWriteSettingsLocked(); 863 } 864 } 865 sendVerificationRequest(userId, verificationId, ivs); 866 } 867 mCurrentIntentFilterVerifications.clear(); 868 } 869 870 private void sendVerificationRequest(int userId, int verificationId, 871 IntentFilterVerificationState ivs) { 872 873 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 874 verificationIntent.putExtra( 875 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 876 verificationId); 877 verificationIntent.putExtra( 878 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 879 getDefaultScheme()); 880 verificationIntent.putExtra( 881 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 882 ivs.getHostsString()); 883 verificationIntent.putExtra( 884 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 885 ivs.getPackageName()); 886 verificationIntent.setComponent(mIntentFilterVerifierComponent); 887 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 888 889 UserHandle user = new UserHandle(userId); 890 mContext.sendBroadcastAsUser(verificationIntent, user); 891 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 892 "Sending IntentFilter verification broadcast"); 893 } 894 895 public void receiveVerificationResponse(int verificationId) { 896 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 897 898 final boolean verified = ivs.isVerified(); 899 900 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 901 final int count = filters.size(); 902 if (DEBUG_DOMAIN_VERIFICATION) { 903 Slog.i(TAG, "Received verification response " + verificationId 904 + " for " + count + " filters, verified=" + verified); 905 } 906 for (int n=0; n<count; n++) { 907 PackageParser.ActivityIntentInfo filter = filters.get(n); 908 filter.setVerified(verified); 909 910 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 911 + " verified with result:" + verified + " and hosts:" 912 + ivs.getHostsString()); 913 } 914 915 mIntentFilterVerificationStates.remove(verificationId); 916 917 final String packageName = ivs.getPackageName(); 918 IntentFilterVerificationInfo ivi = null; 919 920 synchronized (mPackages) { 921 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 922 } 923 if (ivi == null) { 924 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 925 + verificationId + " packageName:" + packageName); 926 return; 927 } 928 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 929 "Updating IntentFilterVerificationInfo for package " + packageName 930 +" verificationId:" + verificationId); 931 932 synchronized (mPackages) { 933 if (verified) { 934 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 935 } else { 936 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 937 } 938 scheduleWriteSettingsLocked(); 939 940 final int userId = ivs.getUserId(); 941 if (userId != UserHandle.USER_ALL) { 942 final int userStatus = 943 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 944 945 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 946 boolean needUpdate = false; 947 948 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 949 // already been set by the User thru the Disambiguation dialog 950 switch (userStatus) { 951 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 952 if (verified) { 953 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 954 } else { 955 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 956 } 957 needUpdate = true; 958 break; 959 960 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 961 if (verified) { 962 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 963 needUpdate = true; 964 } 965 break; 966 967 default: 968 // Nothing to do 969 } 970 971 if (needUpdate) { 972 mSettings.updateIntentFilterVerificationStatusLPw( 973 packageName, updatedStatus, userId); 974 scheduleWritePackageRestrictionsLocked(userId); 975 } 976 } 977 } 978 } 979 980 @Override 981 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 982 ActivityIntentInfo filter, String packageName) { 983 if (!hasValidDomains(filter)) { 984 return false; 985 } 986 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 987 if (ivs == null) { 988 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 989 packageName); 990 } 991 if (DEBUG_DOMAIN_VERIFICATION) { 992 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 993 } 994 ivs.addFilter(filter); 995 return true; 996 } 997 998 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 999 int userId, int verificationId, String packageName) { 1000 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1001 verifierUid, userId, packageName); 1002 ivs.setPendingState(); 1003 synchronized (mPackages) { 1004 mIntentFilterVerificationStates.append(verificationId, ivs); 1005 mCurrentIntentFilterVerifications.add(verificationId); 1006 } 1007 return ivs; 1008 } 1009 } 1010 1011 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1012 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1013 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1014 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1015 } 1016 1017 // Set of pending broadcasts for aggregating enable/disable of components. 1018 static class PendingPackageBroadcasts { 1019 // for each user id, a map of <package name -> components within that package> 1020 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1021 1022 public PendingPackageBroadcasts() { 1023 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1024 } 1025 1026 public ArrayList<String> get(int userId, String packageName) { 1027 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1028 return packages.get(packageName); 1029 } 1030 1031 public void put(int userId, String packageName, ArrayList<String> components) { 1032 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1033 packages.put(packageName, components); 1034 } 1035 1036 public void remove(int userId, String packageName) { 1037 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1038 if (packages != null) { 1039 packages.remove(packageName); 1040 } 1041 } 1042 1043 public void remove(int userId) { 1044 mUidMap.remove(userId); 1045 } 1046 1047 public int userIdCount() { 1048 return mUidMap.size(); 1049 } 1050 1051 public int userIdAt(int n) { 1052 return mUidMap.keyAt(n); 1053 } 1054 1055 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1056 return mUidMap.get(userId); 1057 } 1058 1059 public int size() { 1060 // total number of pending broadcast entries across all userIds 1061 int num = 0; 1062 for (int i = 0; i< mUidMap.size(); i++) { 1063 num += mUidMap.valueAt(i).size(); 1064 } 1065 return num; 1066 } 1067 1068 public void clear() { 1069 mUidMap.clear(); 1070 } 1071 1072 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1073 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1074 if (map == null) { 1075 map = new ArrayMap<String, ArrayList<String>>(); 1076 mUidMap.put(userId, map); 1077 } 1078 return map; 1079 } 1080 } 1081 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1082 1083 // Service Connection to remote media container service to copy 1084 // package uri's from external media onto secure containers 1085 // or internal storage. 1086 private IMediaContainerService mContainerService = null; 1087 1088 static final int SEND_PENDING_BROADCAST = 1; 1089 static final int MCS_BOUND = 3; 1090 static final int END_COPY = 4; 1091 static final int INIT_COPY = 5; 1092 static final int MCS_UNBIND = 6; 1093 static final int START_CLEANING_PACKAGE = 7; 1094 static final int FIND_INSTALL_LOC = 8; 1095 static final int POST_INSTALL = 9; 1096 static final int MCS_RECONNECT = 10; 1097 static final int MCS_GIVE_UP = 11; 1098 static final int UPDATED_MEDIA_STATUS = 12; 1099 static final int WRITE_SETTINGS = 13; 1100 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1101 static final int PACKAGE_VERIFIED = 15; 1102 static final int CHECK_PENDING_VERIFICATION = 16; 1103 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1104 static final int INTENT_FILTER_VERIFIED = 18; 1105 static final int WRITE_PACKAGE_LIST = 19; 1106 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1107 1108 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1109 1110 // Delay time in millisecs 1111 static final int BROADCAST_DELAY = 10 * 1000; 1112 1113 static UserManagerService sUserManager; 1114 1115 // Stores a list of users whose package restrictions file needs to be updated 1116 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1117 1118 final private DefaultContainerConnection mDefContainerConn = 1119 new DefaultContainerConnection(); 1120 class DefaultContainerConnection implements ServiceConnection { 1121 public void onServiceConnected(ComponentName name, IBinder service) { 1122 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1123 final IMediaContainerService imcs = IMediaContainerService.Stub 1124 .asInterface(Binder.allowBlocking(service)); 1125 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1126 } 1127 1128 public void onServiceDisconnected(ComponentName name) { 1129 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1130 } 1131 } 1132 1133 // Recordkeeping of restore-after-install operations that are currently in flight 1134 // between the Package Manager and the Backup Manager 1135 static class PostInstallData { 1136 public InstallArgs args; 1137 public PackageInstalledInfo res; 1138 1139 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1140 args = _a; 1141 res = _r; 1142 } 1143 } 1144 1145 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1146 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1147 1148 // XML tags for backup/restore of various bits of state 1149 private static final String TAG_PREFERRED_BACKUP = "pa"; 1150 private static final String TAG_DEFAULT_APPS = "da"; 1151 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1152 1153 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1154 private static final String TAG_ALL_GRANTS = "rt-grants"; 1155 private static final String TAG_GRANT = "grant"; 1156 private static final String ATTR_PACKAGE_NAME = "pkg"; 1157 1158 private static final String TAG_PERMISSION = "perm"; 1159 private static final String ATTR_PERMISSION_NAME = "name"; 1160 private static final String ATTR_IS_GRANTED = "g"; 1161 private static final String ATTR_USER_SET = "set"; 1162 private static final String ATTR_USER_FIXED = "fixed"; 1163 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1164 1165 // System/policy permission grants are not backed up 1166 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1167 FLAG_PERMISSION_POLICY_FIXED 1168 | FLAG_PERMISSION_SYSTEM_FIXED 1169 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1170 1171 // And we back up these user-adjusted states 1172 private static final int USER_RUNTIME_GRANT_MASK = 1173 FLAG_PERMISSION_USER_SET 1174 | FLAG_PERMISSION_USER_FIXED 1175 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1176 1177 final @Nullable String mRequiredVerifierPackage; 1178 final @NonNull String mRequiredInstallerPackage; 1179 final @NonNull String mRequiredUninstallerPackage; 1180 final @Nullable String mSetupWizardPackage; 1181 final @Nullable String mStorageManagerPackage; 1182 final @NonNull String mServicesSystemSharedLibraryPackageName; 1183 final @NonNull String mSharedSystemSharedLibraryPackageName; 1184 1185 final boolean mPermissionReviewRequired; 1186 1187 private final PackageUsage mPackageUsage = new PackageUsage(); 1188 private final CompilerStats mCompilerStats = new CompilerStats(); 1189 1190 class PackageHandler extends Handler { 1191 private boolean mBound = false; 1192 final ArrayList<HandlerParams> mPendingInstalls = 1193 new ArrayList<HandlerParams>(); 1194 1195 private boolean connectToService() { 1196 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1197 " DefaultContainerService"); 1198 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1199 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1200 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1201 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1202 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1203 mBound = true; 1204 return true; 1205 } 1206 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1207 return false; 1208 } 1209 1210 private void disconnectService() { 1211 mContainerService = null; 1212 mBound = false; 1213 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1214 mContext.unbindService(mDefContainerConn); 1215 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1216 } 1217 1218 PackageHandler(Looper looper) { 1219 super(looper); 1220 } 1221 1222 public void handleMessage(Message msg) { 1223 try { 1224 doHandleMessage(msg); 1225 } finally { 1226 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1227 } 1228 } 1229 1230 void doHandleMessage(Message msg) { 1231 switch (msg.what) { 1232 case INIT_COPY: { 1233 HandlerParams params = (HandlerParams) msg.obj; 1234 int idx = mPendingInstalls.size(); 1235 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1236 // If a bind was already initiated we dont really 1237 // need to do anything. The pending install 1238 // will be processed later on. 1239 if (!mBound) { 1240 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1241 System.identityHashCode(mHandler)); 1242 // If this is the only one pending we might 1243 // have to bind to the service again. 1244 if (!connectToService()) { 1245 Slog.e(TAG, "Failed to bind to media container service"); 1246 params.serviceError(); 1247 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1248 System.identityHashCode(mHandler)); 1249 if (params.traceMethod != null) { 1250 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1251 params.traceCookie); 1252 } 1253 return; 1254 } else { 1255 // Once we bind to the service, the first 1256 // pending request will be processed. 1257 mPendingInstalls.add(idx, params); 1258 } 1259 } else { 1260 mPendingInstalls.add(idx, params); 1261 // Already bound to the service. Just make 1262 // sure we trigger off processing the first request. 1263 if (idx == 0) { 1264 mHandler.sendEmptyMessage(MCS_BOUND); 1265 } 1266 } 1267 break; 1268 } 1269 case MCS_BOUND: { 1270 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1271 if (msg.obj != null) { 1272 mContainerService = (IMediaContainerService) msg.obj; 1273 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1274 System.identityHashCode(mHandler)); 1275 } 1276 if (mContainerService == null) { 1277 if (!mBound) { 1278 // Something seriously wrong since we are not bound and we are not 1279 // waiting for connection. Bail out. 1280 Slog.e(TAG, "Cannot bind to media container service"); 1281 for (HandlerParams params : mPendingInstalls) { 1282 // Indicate service bind error 1283 params.serviceError(); 1284 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1285 System.identityHashCode(params)); 1286 if (params.traceMethod != null) { 1287 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1288 params.traceMethod, params.traceCookie); 1289 } 1290 return; 1291 } 1292 mPendingInstalls.clear(); 1293 } else { 1294 Slog.w(TAG, "Waiting to connect to media container service"); 1295 } 1296 } else if (mPendingInstalls.size() > 0) { 1297 HandlerParams params = mPendingInstalls.get(0); 1298 if (params != null) { 1299 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1300 System.identityHashCode(params)); 1301 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1302 if (params.startCopy()) { 1303 // We are done... look for more work or to 1304 // go idle. 1305 if (DEBUG_SD_INSTALL) Log.i(TAG, 1306 "Checking for more work or unbind..."); 1307 // Delete pending install 1308 if (mPendingInstalls.size() > 0) { 1309 mPendingInstalls.remove(0); 1310 } 1311 if (mPendingInstalls.size() == 0) { 1312 if (mBound) { 1313 if (DEBUG_SD_INSTALL) Log.i(TAG, 1314 "Posting delayed MCS_UNBIND"); 1315 removeMessages(MCS_UNBIND); 1316 Message ubmsg = obtainMessage(MCS_UNBIND); 1317 // Unbind after a little delay, to avoid 1318 // continual thrashing. 1319 sendMessageDelayed(ubmsg, 10000); 1320 } 1321 } else { 1322 // There are more pending requests in queue. 1323 // Just post MCS_BOUND message to trigger processing 1324 // of next pending install. 1325 if (DEBUG_SD_INSTALL) Log.i(TAG, 1326 "Posting MCS_BOUND for next work"); 1327 mHandler.sendEmptyMessage(MCS_BOUND); 1328 } 1329 } 1330 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1331 } 1332 } else { 1333 // Should never happen ideally. 1334 Slog.w(TAG, "Empty queue"); 1335 } 1336 break; 1337 } 1338 case MCS_RECONNECT: { 1339 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1340 if (mPendingInstalls.size() > 0) { 1341 if (mBound) { 1342 disconnectService(); 1343 } 1344 if (!connectToService()) { 1345 Slog.e(TAG, "Failed to bind to media container service"); 1346 for (HandlerParams params : mPendingInstalls) { 1347 // Indicate service bind error 1348 params.serviceError(); 1349 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1350 System.identityHashCode(params)); 1351 } 1352 mPendingInstalls.clear(); 1353 } 1354 } 1355 break; 1356 } 1357 case MCS_UNBIND: { 1358 // If there is no actual work left, then time to unbind. 1359 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1360 1361 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1362 if (mBound) { 1363 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1364 1365 disconnectService(); 1366 } 1367 } else if (mPendingInstalls.size() > 0) { 1368 // There are more pending requests in queue. 1369 // Just post MCS_BOUND message to trigger processing 1370 // of next pending install. 1371 mHandler.sendEmptyMessage(MCS_BOUND); 1372 } 1373 1374 break; 1375 } 1376 case MCS_GIVE_UP: { 1377 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1378 HandlerParams params = mPendingInstalls.remove(0); 1379 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1380 System.identityHashCode(params)); 1381 break; 1382 } 1383 case SEND_PENDING_BROADCAST: { 1384 String packages[]; 1385 ArrayList<String> components[]; 1386 int size = 0; 1387 int uids[]; 1388 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1389 synchronized (mPackages) { 1390 if (mPendingBroadcasts == null) { 1391 return; 1392 } 1393 size = mPendingBroadcasts.size(); 1394 if (size <= 0) { 1395 // Nothing to be done. Just return 1396 return; 1397 } 1398 packages = new String[size]; 1399 components = new ArrayList[size]; 1400 uids = new int[size]; 1401 int i = 0; // filling out the above arrays 1402 1403 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1404 int packageUserId = mPendingBroadcasts.userIdAt(n); 1405 Iterator<Map.Entry<String, ArrayList<String>>> it 1406 = mPendingBroadcasts.packagesForUserId(packageUserId) 1407 .entrySet().iterator(); 1408 while (it.hasNext() && i < size) { 1409 Map.Entry<String, ArrayList<String>> ent = it.next(); 1410 packages[i] = ent.getKey(); 1411 components[i] = ent.getValue(); 1412 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1413 uids[i] = (ps != null) 1414 ? UserHandle.getUid(packageUserId, ps.appId) 1415 : -1; 1416 i++; 1417 } 1418 } 1419 size = i; 1420 mPendingBroadcasts.clear(); 1421 } 1422 // Send broadcasts 1423 for (int i = 0; i < size; i++) { 1424 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1425 } 1426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1427 break; 1428 } 1429 case START_CLEANING_PACKAGE: { 1430 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1431 final String packageName = (String)msg.obj; 1432 final int userId = msg.arg1; 1433 final boolean andCode = msg.arg2 != 0; 1434 synchronized (mPackages) { 1435 if (userId == UserHandle.USER_ALL) { 1436 int[] users = sUserManager.getUserIds(); 1437 for (int user : users) { 1438 mSettings.addPackageToCleanLPw( 1439 new PackageCleanItem(user, packageName, andCode)); 1440 } 1441 } else { 1442 mSettings.addPackageToCleanLPw( 1443 new PackageCleanItem(userId, packageName, andCode)); 1444 } 1445 } 1446 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1447 startCleaningPackages(); 1448 } break; 1449 case POST_INSTALL: { 1450 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1451 1452 PostInstallData data = mRunningInstalls.get(msg.arg1); 1453 final boolean didRestore = (msg.arg2 != 0); 1454 mRunningInstalls.delete(msg.arg1); 1455 1456 if (data != null) { 1457 InstallArgs args = data.args; 1458 PackageInstalledInfo parentRes = data.res; 1459 1460 final boolean grantPermissions = (args.installFlags 1461 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1462 final boolean killApp = (args.installFlags 1463 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1464 final String[] grantedPermissions = args.installGrantPermissions; 1465 1466 // Handle the parent package 1467 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1468 grantedPermissions, didRestore, args.installerPackageName, 1469 args.observer); 1470 1471 // Handle the child packages 1472 final int childCount = (parentRes.addedChildPackages != null) 1473 ? parentRes.addedChildPackages.size() : 0; 1474 for (int i = 0; i < childCount; i++) { 1475 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1476 handlePackagePostInstall(childRes, grantPermissions, killApp, 1477 grantedPermissions, false, args.installerPackageName, 1478 args.observer); 1479 } 1480 1481 // Log tracing if needed 1482 if (args.traceMethod != null) { 1483 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1484 args.traceCookie); 1485 } 1486 } else { 1487 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1488 } 1489 1490 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1491 } break; 1492 case UPDATED_MEDIA_STATUS: { 1493 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1494 boolean reportStatus = msg.arg1 == 1; 1495 boolean doGc = msg.arg2 == 1; 1496 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1497 if (doGc) { 1498 // Force a gc to clear up stale containers. 1499 Runtime.getRuntime().gc(); 1500 } 1501 if (msg.obj != null) { 1502 @SuppressWarnings("unchecked") 1503 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1504 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1505 // Unload containers 1506 unloadAllContainers(args); 1507 } 1508 if (reportStatus) { 1509 try { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, 1511 "Invoking StorageManagerService call back"); 1512 PackageHelper.getStorageManager().finishMediaUpdate(); 1513 } catch (RemoteException e) { 1514 Log.e(TAG, "StorageManagerService not running?"); 1515 } 1516 } 1517 } break; 1518 case WRITE_SETTINGS: { 1519 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1520 synchronized (mPackages) { 1521 removeMessages(WRITE_SETTINGS); 1522 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1523 mSettings.writeLPr(); 1524 mDirtyUsers.clear(); 1525 } 1526 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1527 } break; 1528 case WRITE_PACKAGE_RESTRICTIONS: { 1529 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1530 synchronized (mPackages) { 1531 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1532 for (int userId : mDirtyUsers) { 1533 mSettings.writePackageRestrictionsLPr(userId); 1534 } 1535 mDirtyUsers.clear(); 1536 } 1537 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1538 } break; 1539 case WRITE_PACKAGE_LIST: { 1540 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1541 synchronized (mPackages) { 1542 removeMessages(WRITE_PACKAGE_LIST); 1543 mSettings.writePackageListLPr(msg.arg1); 1544 } 1545 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1546 } break; 1547 case CHECK_PENDING_VERIFICATION: { 1548 final int verificationId = msg.arg1; 1549 final PackageVerificationState state = mPendingVerification.get(verificationId); 1550 1551 if ((state != null) && !state.timeoutExtended()) { 1552 final InstallArgs args = state.getInstallArgs(); 1553 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1554 1555 Slog.i(TAG, "Verification timed out for " + originUri); 1556 mPendingVerification.remove(verificationId); 1557 1558 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1559 1560 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1561 Slog.i(TAG, "Continuing with installation of " + originUri); 1562 state.setVerifierResponse(Binder.getCallingUid(), 1563 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1564 broadcastPackageVerified(verificationId, originUri, 1565 PackageManager.VERIFICATION_ALLOW, 1566 state.getInstallArgs().getUser()); 1567 try { 1568 ret = args.copyApk(mContainerService, true); 1569 } catch (RemoteException e) { 1570 Slog.e(TAG, "Could not contact the ContainerService"); 1571 } 1572 } else { 1573 broadcastPackageVerified(verificationId, originUri, 1574 PackageManager.VERIFICATION_REJECT, 1575 state.getInstallArgs().getUser()); 1576 } 1577 1578 Trace.asyncTraceEnd( 1579 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1580 1581 processPendingInstall(args, ret); 1582 mHandler.sendEmptyMessage(MCS_UNBIND); 1583 } 1584 break; 1585 } 1586 case PACKAGE_VERIFIED: { 1587 final int verificationId = msg.arg1; 1588 1589 final PackageVerificationState state = mPendingVerification.get(verificationId); 1590 if (state == null) { 1591 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1592 break; 1593 } 1594 1595 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1596 1597 state.setVerifierResponse(response.callerUid, response.code); 1598 1599 if (state.isVerificationComplete()) { 1600 mPendingVerification.remove(verificationId); 1601 1602 final InstallArgs args = state.getInstallArgs(); 1603 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1604 1605 int ret; 1606 if (state.isInstallAllowed()) { 1607 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1608 broadcastPackageVerified(verificationId, originUri, 1609 response.code, state.getInstallArgs().getUser()); 1610 try { 1611 ret = args.copyApk(mContainerService, true); 1612 } catch (RemoteException e) { 1613 Slog.e(TAG, "Could not contact the ContainerService"); 1614 } 1615 } else { 1616 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1617 } 1618 1619 Trace.asyncTraceEnd( 1620 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1621 1622 processPendingInstall(args, ret); 1623 mHandler.sendEmptyMessage(MCS_UNBIND); 1624 } 1625 1626 break; 1627 } 1628 case START_INTENT_FILTER_VERIFICATIONS: { 1629 IFVerificationParams params = (IFVerificationParams) msg.obj; 1630 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1631 params.replacing, params.pkg); 1632 break; 1633 } 1634 case INTENT_FILTER_VERIFIED: { 1635 final int verificationId = msg.arg1; 1636 1637 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1638 verificationId); 1639 if (state == null) { 1640 Slog.w(TAG, "Invalid IntentFilter verification token " 1641 + verificationId + " received"); 1642 break; 1643 } 1644 1645 final int userId = state.getUserId(); 1646 1647 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1648 "Processing IntentFilter verification with token:" 1649 + verificationId + " and userId:" + userId); 1650 1651 final IntentFilterVerificationResponse response = 1652 (IntentFilterVerificationResponse) msg.obj; 1653 1654 state.setVerifierResponse(response.callerUid, response.code); 1655 1656 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1657 "IntentFilter verification with token:" + verificationId 1658 + " and userId:" + userId 1659 + " is settings verifier response with response code:" 1660 + response.code); 1661 1662 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1663 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1664 + response.getFailedDomainsString()); 1665 } 1666 1667 if (state.isVerificationComplete()) { 1668 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1669 } else { 1670 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1671 "IntentFilter verification with token:" + verificationId 1672 + " was not said to be complete"); 1673 } 1674 1675 break; 1676 } 1677 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1678 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1679 mEphemeralResolverConnection, 1680 (EphemeralRequest) msg.obj, 1681 mEphemeralInstallerActivity, 1682 mHandler); 1683 } 1684 } 1685 } 1686 } 1687 1688 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1689 boolean killApp, String[] grantedPermissions, 1690 boolean launchedForRestore, String installerPackage, 1691 IPackageInstallObserver2 installObserver) { 1692 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1693 // Send the removed broadcasts 1694 if (res.removedInfo != null) { 1695 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1696 } 1697 1698 // Now that we successfully installed the package, grant runtime 1699 // permissions if requested before broadcasting the install. 1700 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1701 >= Build.VERSION_CODES.M) { 1702 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1703 } 1704 1705 final boolean update = res.removedInfo != null 1706 && res.removedInfo.removedPackage != null; 1707 1708 // If this is the first time we have child packages for a disabled privileged 1709 // app that had no children, we grant requested runtime permissions to the new 1710 // children if the parent on the system image had them already granted. 1711 if (res.pkg.parentPackage != null) { 1712 synchronized (mPackages) { 1713 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1714 } 1715 } 1716 1717 synchronized (mPackages) { 1718 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1719 } 1720 1721 final String packageName = res.pkg.applicationInfo.packageName; 1722 1723 // Determine the set of users who are adding this package for 1724 // the first time vs. those who are seeing an update. 1725 int[] firstUsers = EMPTY_INT_ARRAY; 1726 int[] updateUsers = EMPTY_INT_ARRAY; 1727 if (res.origUsers == null || res.origUsers.length == 0) { 1728 firstUsers = res.newUsers; 1729 } else { 1730 for (int newUser : res.newUsers) { 1731 boolean isNew = true; 1732 for (int origUser : res.origUsers) { 1733 if (origUser == newUser) { 1734 isNew = false; 1735 break; 1736 } 1737 } 1738 if (isNew) { 1739 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1740 } else { 1741 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1742 } 1743 } 1744 } 1745 1746 // Send installed broadcasts if the install/update is not ephemeral 1747 if (!isEphemeral(res.pkg)) { 1748 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1749 1750 // Send added for users that see the package for the first time 1751 // sendPackageAddedForNewUsers also deals with system apps 1752 int appId = UserHandle.getAppId(res.uid); 1753 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1754 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1755 1756 // Send added for users that don't see the package for the first time 1757 Bundle extras = new Bundle(1); 1758 extras.putInt(Intent.EXTRA_UID, res.uid); 1759 if (update) { 1760 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1761 } 1762 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1763 extras, 0 /*flags*/, null /*targetPackage*/, 1764 null /*finishedReceiver*/, updateUsers); 1765 1766 // Send replaced for users that don't see the package for the first time 1767 if (update) { 1768 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1769 packageName, extras, 0 /*flags*/, 1770 null /*targetPackage*/, null /*finishedReceiver*/, 1771 updateUsers); 1772 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1773 null /*package*/, null /*extras*/, 0 /*flags*/, 1774 packageName /*targetPackage*/, 1775 null /*finishedReceiver*/, updateUsers); 1776 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1777 // First-install and we did a restore, so we're responsible for the 1778 // first-launch broadcast. 1779 if (DEBUG_BACKUP) { 1780 Slog.i(TAG, "Post-restore of " + packageName 1781 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1782 } 1783 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1784 } 1785 1786 // Send broadcast package appeared if forward locked/external for all users 1787 // treat asec-hosted packages like removable media on upgrade 1788 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1789 if (DEBUG_INSTALL) { 1790 Slog.i(TAG, "upgrading pkg " + res.pkg 1791 + " is ASEC-hosted -> AVAILABLE"); 1792 } 1793 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1794 ArrayList<String> pkgList = new ArrayList<>(1); 1795 pkgList.add(packageName); 1796 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1797 } 1798 } 1799 1800 // Work that needs to happen on first install within each user 1801 if (firstUsers != null && firstUsers.length > 0) { 1802 synchronized (mPackages) { 1803 for (int userId : firstUsers) { 1804 // If this app is a browser and it's newly-installed for some 1805 // users, clear any default-browser state in those users. The 1806 // app's nature doesn't depend on the user, so we can just check 1807 // its browser nature in any user and generalize. 1808 if (packageIsBrowser(packageName, userId)) { 1809 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1810 } 1811 1812 // We may also need to apply pending (restored) runtime 1813 // permission grants within these users. 1814 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1815 } 1816 } 1817 } 1818 1819 // Log current value of "unknown sources" setting 1820 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1821 getUnknownSourcesSettings()); 1822 1823 // Force a gc to clear up things 1824 Runtime.getRuntime().gc(); 1825 1826 // Remove the replaced package's older resources safely now 1827 // We delete after a gc for applications on sdcard. 1828 if (res.removedInfo != null && res.removedInfo.args != null) { 1829 synchronized (mInstallLock) { 1830 res.removedInfo.args.doPostDeleteLI(true); 1831 } 1832 } 1833 } 1834 1835 // If someone is watching installs - notify them 1836 if (installObserver != null) { 1837 try { 1838 Bundle extras = extrasForInstallResult(res); 1839 installObserver.onPackageInstalled(res.name, res.returnCode, 1840 res.returnMsg, extras); 1841 } catch (RemoteException e) { 1842 Slog.i(TAG, "Observer no longer exists."); 1843 } 1844 } 1845 } 1846 1847 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1848 PackageParser.Package pkg) { 1849 if (pkg.parentPackage == null) { 1850 return; 1851 } 1852 if (pkg.requestedPermissions == null) { 1853 return; 1854 } 1855 final PackageSetting disabledSysParentPs = mSettings 1856 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1857 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1858 || !disabledSysParentPs.isPrivileged() 1859 || (disabledSysParentPs.childPackageNames != null 1860 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1861 return; 1862 } 1863 final int[] allUserIds = sUserManager.getUserIds(); 1864 final int permCount = pkg.requestedPermissions.size(); 1865 for (int i = 0; i < permCount; i++) { 1866 String permission = pkg.requestedPermissions.get(i); 1867 BasePermission bp = mSettings.mPermissions.get(permission); 1868 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1869 continue; 1870 } 1871 for (int userId : allUserIds) { 1872 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1873 permission, userId)) { 1874 grantRuntimePermission(pkg.packageName, permission, userId); 1875 } 1876 } 1877 } 1878 } 1879 1880 private StorageEventListener mStorageListener = new StorageEventListener() { 1881 @Override 1882 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1883 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1884 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1885 final String volumeUuid = vol.getFsUuid(); 1886 1887 // Clean up any users or apps that were removed or recreated 1888 // while this volume was missing 1889 reconcileUsers(volumeUuid); 1890 reconcileApps(volumeUuid); 1891 1892 // Clean up any install sessions that expired or were 1893 // cancelled while this volume was missing 1894 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1895 1896 loadPrivatePackages(vol); 1897 1898 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1899 unloadPrivatePackages(vol); 1900 } 1901 } 1902 1903 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1904 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1905 updateExternalMediaStatus(true, false); 1906 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1907 updateExternalMediaStatus(false, false); 1908 } 1909 } 1910 } 1911 1912 @Override 1913 public void onVolumeForgotten(String fsUuid) { 1914 if (TextUtils.isEmpty(fsUuid)) { 1915 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1916 return; 1917 } 1918 1919 // Remove any apps installed on the forgotten volume 1920 synchronized (mPackages) { 1921 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1922 for (PackageSetting ps : packages) { 1923 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1924 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1925 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1926 1927 // Try very hard to release any references to this package 1928 // so we don't risk the system server being killed due to 1929 // open FDs 1930 AttributeCache.instance().removePackage(ps.name); 1931 } 1932 1933 mSettings.onVolumeForgotten(fsUuid); 1934 mSettings.writeLPr(); 1935 } 1936 } 1937 }; 1938 1939 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1940 String[] grantedPermissions) { 1941 for (int userId : userIds) { 1942 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1943 } 1944 1945 // We could have touched GID membership, so flush out packages.list 1946 synchronized (mPackages) { 1947 mSettings.writePackageListLPr(); 1948 } 1949 } 1950 1951 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1952 String[] grantedPermissions) { 1953 SettingBase sb = (SettingBase) pkg.mExtras; 1954 if (sb == null) { 1955 return; 1956 } 1957 1958 PermissionsState permissionsState = sb.getPermissionsState(); 1959 1960 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1961 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1962 1963 for (String permission : pkg.requestedPermissions) { 1964 final BasePermission bp; 1965 synchronized (mPackages) { 1966 bp = mSettings.mPermissions.get(permission); 1967 } 1968 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1969 && (grantedPermissions == null 1970 || ArrayUtils.contains(grantedPermissions, permission))) { 1971 final int flags = permissionsState.getPermissionFlags(permission, userId); 1972 // Installer cannot change immutable permissions. 1973 if ((flags & immutableFlags) == 0) { 1974 grantRuntimePermission(pkg.packageName, permission, userId); 1975 } 1976 } 1977 } 1978 } 1979 1980 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1981 Bundle extras = null; 1982 switch (res.returnCode) { 1983 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1984 extras = new Bundle(); 1985 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1986 res.origPermission); 1987 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1988 res.origPackage); 1989 break; 1990 } 1991 case PackageManager.INSTALL_SUCCEEDED: { 1992 extras = new Bundle(); 1993 extras.putBoolean(Intent.EXTRA_REPLACING, 1994 res.removedInfo != null && res.removedInfo.removedPackage != null); 1995 break; 1996 } 1997 } 1998 return extras; 1999 } 2000 2001 void scheduleWriteSettingsLocked() { 2002 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2003 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2004 } 2005 } 2006 2007 void scheduleWritePackageListLocked(int userId) { 2008 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2009 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2010 msg.arg1 = userId; 2011 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2012 } 2013 } 2014 2015 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2016 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2017 scheduleWritePackageRestrictionsLocked(userId); 2018 } 2019 2020 void scheduleWritePackageRestrictionsLocked(int userId) { 2021 final int[] userIds = (userId == UserHandle.USER_ALL) 2022 ? sUserManager.getUserIds() : new int[]{userId}; 2023 for (int nextUserId : userIds) { 2024 if (!sUserManager.exists(nextUserId)) return; 2025 mDirtyUsers.add(nextUserId); 2026 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2027 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2028 } 2029 } 2030 } 2031 2032 public static PackageManagerService main(Context context, Installer installer, 2033 boolean factoryTest, boolean onlyCore) { 2034 // Self-check for initial settings. 2035 PackageManagerServiceCompilerMapping.checkProperties(); 2036 2037 PackageManagerService m = new PackageManagerService(context, installer, 2038 factoryTest, onlyCore); 2039 m.enableSystemUserPackages(); 2040 ServiceManager.addService("package", m); 2041 return m; 2042 } 2043 2044 private void enableSystemUserPackages() { 2045 if (!UserManager.isSplitSystemUser()) { 2046 return; 2047 } 2048 // For system user, enable apps based on the following conditions: 2049 // - app is whitelisted or belong to one of these groups: 2050 // -- system app which has no launcher icons 2051 // -- system app which has INTERACT_ACROSS_USERS permission 2052 // -- system IME app 2053 // - app is not in the blacklist 2054 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2055 Set<String> enableApps = new ArraySet<>(); 2056 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2057 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2058 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2059 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2060 enableApps.addAll(wlApps); 2061 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2062 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2063 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2064 enableApps.removeAll(blApps); 2065 Log.i(TAG, "Applications installed for system user: " + enableApps); 2066 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2067 UserHandle.SYSTEM); 2068 final int allAppsSize = allAps.size(); 2069 synchronized (mPackages) { 2070 for (int i = 0; i < allAppsSize; i++) { 2071 String pName = allAps.get(i); 2072 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2073 // Should not happen, but we shouldn't be failing if it does 2074 if (pkgSetting == null) { 2075 continue; 2076 } 2077 boolean install = enableApps.contains(pName); 2078 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2079 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2080 + " for system user"); 2081 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2082 } 2083 } 2084 } 2085 } 2086 2087 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2088 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2089 Context.DISPLAY_SERVICE); 2090 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2091 } 2092 2093 /** 2094 * Requests that files preopted on a secondary system partition be copied to the data partition 2095 * if possible. Note that the actual copying of the files is accomplished by init for security 2096 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2097 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2098 */ 2099 private static void requestCopyPreoptedFiles() { 2100 final int WAIT_TIME_MS = 100; 2101 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2102 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2103 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2104 // We will wait for up to 100 seconds. 2105 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2106 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2107 try { 2108 Thread.sleep(WAIT_TIME_MS); 2109 } catch (InterruptedException e) { 2110 // Do nothing 2111 } 2112 if (SystemClock.uptimeMillis() > timeEnd) { 2113 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2114 Slog.wtf(TAG, "cppreopt did not finish!"); 2115 break; 2116 } 2117 } 2118 } 2119 } 2120 2121 public PackageManagerService(Context context, Installer installer, 2122 boolean factoryTest, boolean onlyCore) { 2123 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2124 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2125 SystemClock.uptimeMillis()); 2126 2127 if (mSdkVersion <= 0) { 2128 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2129 } 2130 2131 mContext = context; 2132 2133 mPermissionReviewRequired = context.getResources().getBoolean( 2134 R.bool.config_permissionReviewRequired); 2135 2136 mFactoryTest = factoryTest; 2137 mOnlyCore = onlyCore; 2138 mMetrics = new DisplayMetrics(); 2139 mSettings = new Settings(mPackages); 2140 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2141 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2142 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2143 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2144 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2145 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2146 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2147 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2148 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2149 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2150 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2151 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2152 2153 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2154 if (separateProcesses != null && separateProcesses.length() > 0) { 2155 if ("*".equals(separateProcesses)) { 2156 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2157 mSeparateProcesses = null; 2158 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2159 } else { 2160 mDefParseFlags = 0; 2161 mSeparateProcesses = separateProcesses.split(","); 2162 Slog.w(TAG, "Running with debug.separate_processes: " 2163 + separateProcesses); 2164 } 2165 } else { 2166 mDefParseFlags = 0; 2167 mSeparateProcesses = null; 2168 } 2169 2170 mInstaller = installer; 2171 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2172 "*dexopt*"); 2173 mDexManager = new DexManager(); 2174 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2175 2176 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2177 FgThread.get().getLooper()); 2178 2179 getDefaultDisplayMetrics(context, mMetrics); 2180 2181 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2182 SystemConfig systemConfig = SystemConfig.getInstance(); 2183 mGlobalGids = systemConfig.getGlobalGids(); 2184 mSystemPermissions = systemConfig.getSystemPermissions(); 2185 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2186 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2187 2188 mProtectedPackages = new ProtectedPackages(mContext); 2189 2190 synchronized (mInstallLock) { 2191 // writer 2192 synchronized (mPackages) { 2193 mHandlerThread = new ServiceThread(TAG, 2194 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2195 mHandlerThread.start(); 2196 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2197 mProcessLoggingHandler = new ProcessLoggingHandler(); 2198 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2199 2200 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2201 2202 File dataDir = Environment.getDataDirectory(); 2203 mAppInstallDir = new File(dataDir, "app"); 2204 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2205 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2206 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2207 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2208 2209 sUserManager = new UserManagerService(context, this, mPackages); 2210 2211 // Propagate permission configuration in to package manager. 2212 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2213 = systemConfig.getPermissions(); 2214 for (int i=0; i<permConfig.size(); i++) { 2215 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2216 BasePermission bp = mSettings.mPermissions.get(perm.name); 2217 if (bp == null) { 2218 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2219 mSettings.mPermissions.put(perm.name, bp); 2220 } 2221 if (perm.gids != null) { 2222 bp.setGids(perm.gids, perm.perUser); 2223 } 2224 } 2225 2226 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2227 for (int i=0; i<libConfig.size(); i++) { 2228 mSharedLibraries.put(libConfig.keyAt(i), 2229 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2230 } 2231 2232 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2233 2234 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2235 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2236 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2237 2238 // Clean up orphaned packages for which the code path doesn't exist 2239 // and they are an update to a system app - caused by bug/32321269 2240 final int packageSettingCount = mSettings.mPackages.size(); 2241 for (int i = packageSettingCount - 1; i >= 0; i--) { 2242 PackageSetting ps = mSettings.mPackages.valueAt(i); 2243 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2244 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2245 mSettings.mPackages.removeAt(i); 2246 mSettings.enableSystemPackageLPw(ps.name); 2247 } 2248 } 2249 2250 if (mFirstBoot) { 2251 requestCopyPreoptedFiles(); 2252 } 2253 2254 String customResolverActivity = Resources.getSystem().getString( 2255 R.string.config_customResolverActivity); 2256 if (TextUtils.isEmpty(customResolverActivity)) { 2257 customResolverActivity = null; 2258 } else { 2259 mCustomResolverComponentName = ComponentName.unflattenFromString( 2260 customResolverActivity); 2261 } 2262 2263 long startTime = SystemClock.uptimeMillis(); 2264 2265 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2266 startTime); 2267 2268 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2269 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2270 2271 if (bootClassPath == null) { 2272 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2273 } 2274 2275 if (systemServerClassPath == null) { 2276 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2277 } 2278 2279 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2280 final String[] dexCodeInstructionSets = 2281 getDexCodeInstructionSets( 2282 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2283 2284 /** 2285 * Ensure all external libraries have had dexopt run on them. 2286 */ 2287 if (mSharedLibraries.size() > 0) { 2288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2289 // NOTE: For now, we're compiling these system "shared libraries" 2290 // (and framework jars) into all available architectures. It's possible 2291 // to compile them only when we come across an app that uses them (there's 2292 // already logic for that in scanPackageLI) but that adds some complexity. 2293 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2294 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2295 final String lib = libEntry.path; 2296 if (lib == null) { 2297 continue; 2298 } 2299 2300 try { 2301 // Shared libraries do not have profiles so we perform a full 2302 // AOT compilation (if needed). 2303 int dexoptNeeded = DexFile.getDexOptNeeded( 2304 lib, dexCodeInstructionSet, 2305 getCompilerFilterForReason(REASON_SHARED_APK), 2306 false /* newProfile */); 2307 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2308 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2309 dexCodeInstructionSet, dexoptNeeded, null, 2310 DEXOPT_PUBLIC, 2311 getCompilerFilterForReason(REASON_SHARED_APK), 2312 StorageManager.UUID_PRIVATE_INTERNAL, 2313 SKIP_SHARED_LIBRARY_CHECK); 2314 } 2315 } catch (FileNotFoundException e) { 2316 Slog.w(TAG, "Library not found: " + lib); 2317 } catch (IOException | InstallerException e) { 2318 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2319 + e.getMessage()); 2320 } 2321 } 2322 } 2323 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2324 } 2325 2326 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2327 2328 final VersionInfo ver = mSettings.getInternalVersion(); 2329 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2330 2331 // when upgrading from pre-M, promote system app permissions from install to runtime 2332 mPromoteSystemApps = 2333 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2334 2335 // When upgrading from pre-N, we need to handle package extraction like first boot, 2336 // as there is no profiling data available. 2337 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2338 2339 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2340 2341 // save off the names of pre-existing system packages prior to scanning; we don't 2342 // want to automatically grant runtime permissions for new system apps 2343 if (mPromoteSystemApps) { 2344 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2345 while (pkgSettingIter.hasNext()) { 2346 PackageSetting ps = pkgSettingIter.next(); 2347 if (isSystemApp(ps)) { 2348 mExistingSystemPackages.add(ps.name); 2349 } 2350 } 2351 } 2352 2353 // Set flag to monitor and not change apk file paths when 2354 // scanning install directories. 2355 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2356 2357 if (mIsUpgrade || mFirstBoot) { 2358 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2359 } 2360 2361 // Collect vendor overlay packages. (Do this before scanning any apps.) 2362 // For security and version matching reason, only consider 2363 // overlay packages if they reside in the right directory. 2364 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2365 if (overlayThemeDir.isEmpty()) { 2366 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2367 } 2368 if (!overlayThemeDir.isEmpty()) { 2369 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2370 | PackageParser.PARSE_IS_SYSTEM 2371 | PackageParser.PARSE_IS_SYSTEM_DIR 2372 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2373 } 2374 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2375 | PackageParser.PARSE_IS_SYSTEM 2376 | PackageParser.PARSE_IS_SYSTEM_DIR 2377 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2378 2379 // Find base frameworks (resource packages without code). 2380 scanDirTracedLI(frameworkDir, mDefParseFlags 2381 | PackageParser.PARSE_IS_SYSTEM 2382 | PackageParser.PARSE_IS_SYSTEM_DIR 2383 | PackageParser.PARSE_IS_PRIVILEGED, 2384 scanFlags | SCAN_NO_DEX, 0); 2385 2386 // Collected privileged system packages. 2387 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2388 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2389 | PackageParser.PARSE_IS_SYSTEM 2390 | PackageParser.PARSE_IS_SYSTEM_DIR 2391 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2392 2393 // Collect ordinary system packages. 2394 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2395 scanDirTracedLI(systemAppDir, mDefParseFlags 2396 | PackageParser.PARSE_IS_SYSTEM 2397 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2398 2399 // Collect all vendor packages. 2400 File vendorAppDir = new File("/vendor/app"); 2401 try { 2402 vendorAppDir = vendorAppDir.getCanonicalFile(); 2403 } catch (IOException e) { 2404 // failed to look up canonical path, continue with original one 2405 } 2406 scanDirTracedLI(vendorAppDir, mDefParseFlags 2407 | PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2409 2410 // Collect all OEM packages. 2411 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2412 scanDirTracedLI(oemAppDir, mDefParseFlags 2413 | PackageParser.PARSE_IS_SYSTEM 2414 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2415 2416 // Prune any system packages that no longer exist. 2417 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2418 if (!mOnlyCore) { 2419 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2420 while (psit.hasNext()) { 2421 PackageSetting ps = psit.next(); 2422 2423 /* 2424 * If this is not a system app, it can't be a 2425 * disable system app. 2426 */ 2427 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2428 continue; 2429 } 2430 2431 /* 2432 * If the package is scanned, it's not erased. 2433 */ 2434 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2435 if (scannedPkg != null) { 2436 /* 2437 * If the system app is both scanned and in the 2438 * disabled packages list, then it must have been 2439 * added via OTA. Remove it from the currently 2440 * scanned package so the previously user-installed 2441 * application can be scanned. 2442 */ 2443 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2444 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2445 + ps.name + "; removing system app. Last known codePath=" 2446 + ps.codePathString + ", installStatus=" + ps.installStatus 2447 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2448 + scannedPkg.mVersionCode); 2449 removePackageLI(scannedPkg, true); 2450 mExpectingBetter.put(ps.name, ps.codePath); 2451 } 2452 2453 continue; 2454 } 2455 2456 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2457 psit.remove(); 2458 logCriticalInfo(Log.WARN, "System package " + ps.name 2459 + " no longer exists; it's data will be wiped"); 2460 // Actual deletion of code and data will be handled by later 2461 // reconciliation step 2462 } else { 2463 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2464 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2465 possiblyDeletedUpdatedSystemApps.add(ps.name); 2466 } 2467 } 2468 } 2469 } 2470 2471 //look for any incomplete package installations 2472 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2473 for (int i = 0; i < deletePkgsList.size(); i++) { 2474 // Actual deletion of code and data will be handled by later 2475 // reconciliation step 2476 final String packageName = deletePkgsList.get(i).name; 2477 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2478 synchronized (mPackages) { 2479 mSettings.removePackageLPw(packageName); 2480 } 2481 } 2482 2483 //delete tmp files 2484 deleteTempPackageFiles(); 2485 2486 // Remove any shared userIDs that have no associated packages 2487 mSettings.pruneSharedUsersLPw(); 2488 2489 if (!mOnlyCore) { 2490 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2491 SystemClock.uptimeMillis()); 2492 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2493 2494 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2495 | PackageParser.PARSE_FORWARD_LOCK, 2496 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2497 2498 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2499 | PackageParser.PARSE_IS_EPHEMERAL, 2500 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2501 2502 /** 2503 * Remove disable package settings for any updated system 2504 * apps that were removed via an OTA. If they're not a 2505 * previously-updated app, remove them completely. 2506 * Otherwise, just revoke their system-level permissions. 2507 */ 2508 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2509 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2510 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2511 2512 String msg; 2513 if (deletedPkg == null) { 2514 msg = "Updated system package " + deletedAppName 2515 + " no longer exists; it's data will be wiped"; 2516 // Actual deletion of code and data will be handled by later 2517 // reconciliation step 2518 } else { 2519 msg = "Updated system app + " + deletedAppName 2520 + " no longer present; removing system privileges for " 2521 + deletedAppName; 2522 2523 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2524 2525 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2526 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2527 } 2528 logCriticalInfo(Log.WARN, msg); 2529 } 2530 2531 /** 2532 * Make sure all system apps that we expected to appear on 2533 * the userdata partition actually showed up. If they never 2534 * appeared, crawl back and revive the system version. 2535 */ 2536 for (int i = 0; i < mExpectingBetter.size(); i++) { 2537 final String packageName = mExpectingBetter.keyAt(i); 2538 if (!mPackages.containsKey(packageName)) { 2539 final File scanFile = mExpectingBetter.valueAt(i); 2540 2541 logCriticalInfo(Log.WARN, "Expected better " + packageName 2542 + " but never showed up; reverting to system"); 2543 2544 int reparseFlags = mDefParseFlags; 2545 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2546 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2547 | PackageParser.PARSE_IS_SYSTEM_DIR 2548 | PackageParser.PARSE_IS_PRIVILEGED; 2549 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2550 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2551 | PackageParser.PARSE_IS_SYSTEM_DIR; 2552 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2553 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2554 | PackageParser.PARSE_IS_SYSTEM_DIR; 2555 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2556 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2557 | PackageParser.PARSE_IS_SYSTEM_DIR; 2558 } else { 2559 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2560 continue; 2561 } 2562 2563 mSettings.enableSystemPackageLPw(packageName); 2564 2565 try { 2566 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2567 } catch (PackageManagerException e) { 2568 Slog.e(TAG, "Failed to parse original system package: " 2569 + e.getMessage()); 2570 } 2571 } 2572 } 2573 } 2574 mExpectingBetter.clear(); 2575 2576 // Resolve the storage manager. 2577 mStorageManagerPackage = getStorageManagerPackageName(); 2578 2579 // Resolve protected action filters. Only the setup wizard is allowed to 2580 // have a high priority filter for these actions. 2581 mSetupWizardPackage = getSetupWizardPackageName(); 2582 if (mProtectedFilters.size() > 0) { 2583 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2584 Slog.i(TAG, "No setup wizard;" 2585 + " All protected intents capped to priority 0"); 2586 } 2587 for (ActivityIntentInfo filter : mProtectedFilters) { 2588 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2589 if (DEBUG_FILTERS) { 2590 Slog.i(TAG, "Found setup wizard;" 2591 + " allow priority " + filter.getPriority() + ";" 2592 + " package: " + filter.activity.info.packageName 2593 + " activity: " + filter.activity.className 2594 + " priority: " + filter.getPriority()); 2595 } 2596 // skip setup wizard; allow it to keep the high priority filter 2597 continue; 2598 } 2599 Slog.w(TAG, "Protected action; cap priority to 0;" 2600 + " package: " + filter.activity.info.packageName 2601 + " activity: " + filter.activity.className 2602 + " origPrio: " + filter.getPriority()); 2603 filter.setPriority(0); 2604 } 2605 } 2606 mDeferProtectedFilters = false; 2607 mProtectedFilters.clear(); 2608 2609 // Now that we know all of the shared libraries, update all clients to have 2610 // the correct library paths. 2611 updateAllSharedLibrariesLPw(); 2612 2613 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2614 // NOTE: We ignore potential failures here during a system scan (like 2615 // the rest of the commands above) because there's precious little we 2616 // can do about it. A settings error is reported, though. 2617 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2618 } 2619 2620 // Now that we know all the packages we are keeping, 2621 // read and update their last usage times. 2622 mPackageUsage.read(mPackages); 2623 mCompilerStats.read(); 2624 2625 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2626 SystemClock.uptimeMillis()); 2627 Slog.i(TAG, "Time to scan packages: " 2628 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2629 + " seconds"); 2630 2631 // If the platform SDK has changed since the last time we booted, 2632 // we need to re-grant app permission to catch any new ones that 2633 // appear. This is really a hack, and means that apps can in some 2634 // cases get permissions that the user didn't initially explicitly 2635 // allow... it would be nice to have some better way to handle 2636 // this situation. 2637 int updateFlags = UPDATE_PERMISSIONS_ALL; 2638 if (ver.sdkVersion != mSdkVersion) { 2639 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2640 + mSdkVersion + "; regranting permissions for internal storage"); 2641 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2642 } 2643 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2644 ver.sdkVersion = mSdkVersion; 2645 2646 // If this is the first boot or an update from pre-M, and it is a normal 2647 // boot, then we need to initialize the default preferred apps across 2648 // all defined users. 2649 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2650 for (UserInfo user : sUserManager.getUsers(true)) { 2651 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2652 applyFactoryDefaultBrowserLPw(user.id); 2653 primeDomainVerificationsLPw(user.id); 2654 } 2655 } 2656 2657 // Prepare storage for system user really early during boot, 2658 // since core system apps like SettingsProvider and SystemUI 2659 // can't wait for user to start 2660 final int storageFlags; 2661 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2662 storageFlags = StorageManager.FLAG_STORAGE_DE; 2663 } else { 2664 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2665 } 2666 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2667 storageFlags, true /* migrateAppData */); 2668 2669 // If this is first boot after an OTA, and a normal boot, then 2670 // we need to clear code cache directories. 2671 // Note that we do *not* clear the application profiles. These remain valid 2672 // across OTAs and are used to drive profile verification (post OTA) and 2673 // profile compilation (without waiting to collect a fresh set of profiles). 2674 if (mIsUpgrade && !onlyCore) { 2675 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2676 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2677 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2678 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2679 // No apps are running this early, so no need to freeze 2680 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2681 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2682 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2683 } 2684 } 2685 ver.fingerprint = Build.FINGERPRINT; 2686 } 2687 2688 checkDefaultBrowser(); 2689 2690 // clear only after permissions and other defaults have been updated 2691 mExistingSystemPackages.clear(); 2692 mPromoteSystemApps = false; 2693 2694 // All the changes are done during package scanning. 2695 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2696 2697 // can downgrade to reader 2698 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2699 mSettings.writeLPr(); 2700 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2701 2702 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2703 // early on (before the package manager declares itself as early) because other 2704 // components in the system server might ask for package contexts for these apps. 2705 // 2706 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2707 // (i.e, that the data partition is unavailable). 2708 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2709 long start = System.nanoTime(); 2710 List<PackageParser.Package> coreApps = new ArrayList<>(); 2711 for (PackageParser.Package pkg : mPackages.values()) { 2712 if (pkg.coreApp) { 2713 coreApps.add(pkg); 2714 } 2715 } 2716 2717 int[] stats = performDexOptUpgrade(coreApps, false, 2718 getCompilerFilterForReason(REASON_CORE_APP)); 2719 2720 final int elapsedTimeSeconds = 2721 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2722 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2723 2724 if (DEBUG_DEXOPT) { 2725 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2726 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2727 } 2728 2729 2730 // TODO: Should we log these stats to tron too ? 2731 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2732 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2733 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2734 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2735 } 2736 2737 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2738 SystemClock.uptimeMillis()); 2739 2740 if (!mOnlyCore) { 2741 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2742 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2743 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2744 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2745 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2746 mIntentFilterVerifierComponent); 2747 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2748 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2749 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2750 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2751 } else { 2752 mRequiredVerifierPackage = null; 2753 mRequiredInstallerPackage = null; 2754 mRequiredUninstallerPackage = null; 2755 mIntentFilterVerifierComponent = null; 2756 mIntentFilterVerifier = null; 2757 mServicesSystemSharedLibraryPackageName = null; 2758 mSharedSystemSharedLibraryPackageName = null; 2759 } 2760 2761 mInstallerService = new PackageInstallerService(context, this); 2762 2763 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2764 if (ephemeralResolverComponent != null) { 2765 if (DEBUG_EPHEMERAL) { 2766 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2767 } 2768 mEphemeralResolverConnection = 2769 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2770 } else { 2771 mEphemeralResolverConnection = null; 2772 } 2773 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2774 if (mEphemeralInstallerComponent != null) { 2775 if (DEBUG_EPHEMERAL) { 2776 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2777 } 2778 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2779 } 2780 2781 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2782 2783 // Read and update the usage of dex files. 2784 // Do this at the end of PM init so that all the packages have their 2785 // data directory reconciled. 2786 // At this point we know the code paths of the packages, so we can validate 2787 // the disk file and build the internal cache. 2788 // The usage file is expected to be small so loading and verifying it 2789 // should take a fairly small time compare to the other activities (e.g. package 2790 // scanning). 2791 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2792 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2793 for (int userId : currentUserIds) { 2794 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2795 } 2796 mDexManager.load(userPackages); 2797 } // synchronized (mPackages) 2798 } // synchronized (mInstallLock) 2799 2800 // Now after opening every single application zip, make sure they 2801 // are all flushed. Not really needed, but keeps things nice and 2802 // tidy. 2803 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2804 Runtime.getRuntime().gc(); 2805 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2806 2807 // The initial scanning above does many calls into installd while 2808 // holding the mPackages lock, but we're mostly interested in yelling 2809 // once we have a booted system. 2810 mInstaller.setWarnIfHeld(mPackages); 2811 2812 // Expose private service for system components to use. 2813 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2814 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2815 } 2816 2817 @Override 2818 public boolean isFirstBoot() { 2819 return mFirstBoot; 2820 } 2821 2822 @Override 2823 public boolean isOnlyCoreApps() { 2824 return mOnlyCore; 2825 } 2826 2827 @Override 2828 public boolean isUpgrade() { 2829 return mIsUpgrade; 2830 } 2831 2832 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2833 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2834 2835 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2836 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2837 UserHandle.USER_SYSTEM); 2838 if (matches.size() == 1) { 2839 return matches.get(0).getComponentInfo().packageName; 2840 } else if (matches.size() == 0) { 2841 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2842 return null; 2843 } 2844 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2845 } 2846 2847 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2848 synchronized (mPackages) { 2849 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2850 if (libraryEntry == null) { 2851 throw new IllegalStateException("Missing required shared library:" + libraryName); 2852 } 2853 return libraryEntry.apk; 2854 } 2855 } 2856 2857 private @NonNull String getRequiredInstallerLPr() { 2858 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2859 intent.addCategory(Intent.CATEGORY_DEFAULT); 2860 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2861 2862 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2863 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2864 UserHandle.USER_SYSTEM); 2865 if (matches.size() == 1) { 2866 ResolveInfo resolveInfo = matches.get(0); 2867 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2868 throw new RuntimeException("The installer must be a privileged app"); 2869 } 2870 return matches.get(0).getComponentInfo().packageName; 2871 } else { 2872 throw new RuntimeException("There must be exactly one installer; found " + matches); 2873 } 2874 } 2875 2876 private @NonNull String getRequiredUninstallerLPr() { 2877 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2878 intent.addCategory(Intent.CATEGORY_DEFAULT); 2879 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2880 2881 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2882 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2883 UserHandle.USER_SYSTEM); 2884 if (resolveInfo == null || 2885 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2886 throw new RuntimeException("There must be exactly one uninstaller; found " 2887 + resolveInfo); 2888 } 2889 return resolveInfo.getComponentInfo().packageName; 2890 } 2891 2892 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2893 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2894 2895 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2896 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2897 UserHandle.USER_SYSTEM); 2898 ResolveInfo best = null; 2899 final int N = matches.size(); 2900 for (int i = 0; i < N; i++) { 2901 final ResolveInfo cur = matches.get(i); 2902 final String packageName = cur.getComponentInfo().packageName; 2903 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2904 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2905 continue; 2906 } 2907 2908 if (best == null || cur.priority > best.priority) { 2909 best = cur; 2910 } 2911 } 2912 2913 if (best != null) { 2914 return best.getComponentInfo().getComponentName(); 2915 } else { 2916 throw new RuntimeException("There must be at least one intent filter verifier"); 2917 } 2918 } 2919 2920 private @Nullable ComponentName getEphemeralResolverLPr() { 2921 final String[] packageArray = 2922 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2923 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2924 if (DEBUG_EPHEMERAL) { 2925 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2926 } 2927 return null; 2928 } 2929 2930 final int resolveFlags = 2931 MATCH_DIRECT_BOOT_AWARE 2932 | MATCH_DIRECT_BOOT_UNAWARE 2933 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2934 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2935 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2936 resolveFlags, UserHandle.USER_SYSTEM); 2937 2938 final int N = resolvers.size(); 2939 if (N == 0) { 2940 if (DEBUG_EPHEMERAL) { 2941 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2942 } 2943 return null; 2944 } 2945 2946 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2947 for (int i = 0; i < N; i++) { 2948 final ResolveInfo info = resolvers.get(i); 2949 2950 if (info.serviceInfo == null) { 2951 continue; 2952 } 2953 2954 final String packageName = info.serviceInfo.packageName; 2955 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2956 if (DEBUG_EPHEMERAL) { 2957 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2958 + " pkg: " + packageName + ", info:" + info); 2959 } 2960 continue; 2961 } 2962 2963 if (DEBUG_EPHEMERAL) { 2964 Slog.v(TAG, "Ephemeral resolver found;" 2965 + " pkg: " + packageName + ", info:" + info); 2966 } 2967 return new ComponentName(packageName, info.serviceInfo.name); 2968 } 2969 if (DEBUG_EPHEMERAL) { 2970 Slog.v(TAG, "Ephemeral resolver NOT found"); 2971 } 2972 return null; 2973 } 2974 2975 private @Nullable ComponentName getEphemeralInstallerLPr() { 2976 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2977 intent.addCategory(Intent.CATEGORY_DEFAULT); 2978 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2979 2980 final int resolveFlags = 2981 MATCH_DIRECT_BOOT_AWARE 2982 | MATCH_DIRECT_BOOT_UNAWARE 2983 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2984 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2985 resolveFlags, UserHandle.USER_SYSTEM); 2986 Iterator<ResolveInfo> iter = matches.iterator(); 2987 while (iter.hasNext()) { 2988 final ResolveInfo rInfo = iter.next(); 2989 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 2990 if (ps != null) { 2991 final PermissionsState permissionsState = ps.getPermissionsState(); 2992 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 2993 continue; 2994 } 2995 } 2996 iter.remove(); 2997 } 2998 if (matches.size() == 0) { 2999 return null; 3000 } else if (matches.size() == 1) { 3001 return matches.get(0).getComponentInfo().getComponentName(); 3002 } else { 3003 throw new RuntimeException( 3004 "There must be at most one ephemeral installer; found " + matches); 3005 } 3006 } 3007 3008 private void primeDomainVerificationsLPw(int userId) { 3009 if (DEBUG_DOMAIN_VERIFICATION) { 3010 Slog.d(TAG, "Priming domain verifications in user " + userId); 3011 } 3012 3013 SystemConfig systemConfig = SystemConfig.getInstance(); 3014 ArraySet<String> packages = systemConfig.getLinkedApps(); 3015 3016 for (String packageName : packages) { 3017 PackageParser.Package pkg = mPackages.get(packageName); 3018 if (pkg != null) { 3019 if (!pkg.isSystemApp()) { 3020 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3021 continue; 3022 } 3023 3024 ArraySet<String> domains = null; 3025 for (PackageParser.Activity a : pkg.activities) { 3026 for (ActivityIntentInfo filter : a.intents) { 3027 if (hasValidDomains(filter)) { 3028 if (domains == null) { 3029 domains = new ArraySet<String>(); 3030 } 3031 domains.addAll(filter.getHostsList()); 3032 } 3033 } 3034 } 3035 3036 if (domains != null && domains.size() > 0) { 3037 if (DEBUG_DOMAIN_VERIFICATION) { 3038 Slog.v(TAG, " + " + packageName); 3039 } 3040 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3041 // state w.r.t. the formal app-linkage "no verification attempted" state; 3042 // and then 'always' in the per-user state actually used for intent resolution. 3043 final IntentFilterVerificationInfo ivi; 3044 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3045 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3046 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3047 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3048 } else { 3049 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3050 + "' does not handle web links"); 3051 } 3052 } else { 3053 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3054 } 3055 } 3056 3057 scheduleWritePackageRestrictionsLocked(userId); 3058 scheduleWriteSettingsLocked(); 3059 } 3060 3061 private void applyFactoryDefaultBrowserLPw(int userId) { 3062 // The default browser app's package name is stored in a string resource, 3063 // with a product-specific overlay used for vendor customization. 3064 String browserPkg = mContext.getResources().getString( 3065 com.android.internal.R.string.default_browser); 3066 if (!TextUtils.isEmpty(browserPkg)) { 3067 // non-empty string => required to be a known package 3068 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3069 if (ps == null) { 3070 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3071 browserPkg = null; 3072 } else { 3073 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3074 } 3075 } 3076 3077 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3078 // default. If there's more than one, just leave everything alone. 3079 if (browserPkg == null) { 3080 calculateDefaultBrowserLPw(userId); 3081 } 3082 } 3083 3084 private void calculateDefaultBrowserLPw(int userId) { 3085 List<String> allBrowsers = resolveAllBrowserApps(userId); 3086 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3087 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3088 } 3089 3090 private List<String> resolveAllBrowserApps(int userId) { 3091 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3092 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3093 PackageManager.MATCH_ALL, userId); 3094 3095 final int count = list.size(); 3096 List<String> result = new ArrayList<String>(count); 3097 for (int i=0; i<count; i++) { 3098 ResolveInfo info = list.get(i); 3099 if (info.activityInfo == null 3100 || !info.handleAllWebDataURI 3101 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3102 || result.contains(info.activityInfo.packageName)) { 3103 continue; 3104 } 3105 result.add(info.activityInfo.packageName); 3106 } 3107 3108 return result; 3109 } 3110 3111 private boolean packageIsBrowser(String packageName, int userId) { 3112 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3113 PackageManager.MATCH_ALL, userId); 3114 final int N = list.size(); 3115 for (int i = 0; i < N; i++) { 3116 ResolveInfo info = list.get(i); 3117 if (packageName.equals(info.activityInfo.packageName)) { 3118 return true; 3119 } 3120 } 3121 return false; 3122 } 3123 3124 private void checkDefaultBrowser() { 3125 final int myUserId = UserHandle.myUserId(); 3126 final String packageName = getDefaultBrowserPackageName(myUserId); 3127 if (packageName != null) { 3128 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3129 if (info == null) { 3130 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3131 synchronized (mPackages) { 3132 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3133 } 3134 } 3135 } 3136 } 3137 3138 @Override 3139 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3140 throws RemoteException { 3141 try { 3142 return super.onTransact(code, data, reply, flags); 3143 } catch (RuntimeException e) { 3144 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3145 Slog.wtf(TAG, "Package Manager Crash", e); 3146 } 3147 throw e; 3148 } 3149 } 3150 3151 static int[] appendInts(int[] cur, int[] add) { 3152 if (add == null) return cur; 3153 if (cur == null) return add; 3154 final int N = add.length; 3155 for (int i=0; i<N; i++) { 3156 cur = appendInt(cur, add[i]); 3157 } 3158 return cur; 3159 } 3160 3161 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3162 if (!sUserManager.exists(userId)) return null; 3163 if (ps == null) { 3164 return null; 3165 } 3166 final PackageParser.Package p = ps.pkg; 3167 if (p == null) { 3168 return null; 3169 } 3170 3171 final PermissionsState permissionsState = ps.getPermissionsState(); 3172 3173 // Compute GIDs only if requested 3174 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3175 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3176 // Compute granted permissions only if package has requested permissions 3177 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3178 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3179 final PackageUserState state = ps.readUserState(userId); 3180 3181 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3182 && ps.isSystem()) { 3183 flags |= MATCH_ANY_USER; 3184 } 3185 3186 return PackageParser.generatePackageInfo(p, gids, flags, 3187 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3188 } 3189 3190 @Override 3191 public void checkPackageStartable(String packageName, int userId) { 3192 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3193 3194 synchronized (mPackages) { 3195 final PackageSetting ps = mSettings.mPackages.get(packageName); 3196 if (ps == null) { 3197 throw new SecurityException("Package " + packageName + " was not found!"); 3198 } 3199 3200 if (!ps.getInstalled(userId)) { 3201 throw new SecurityException( 3202 "Package " + packageName + " was not installed for user " + userId + "!"); 3203 } 3204 3205 if (mSafeMode && !ps.isSystem()) { 3206 throw new SecurityException("Package " + packageName + " not a system app!"); 3207 } 3208 3209 if (mFrozenPackages.contains(packageName)) { 3210 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3211 } 3212 3213 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3214 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3215 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3216 } 3217 } 3218 } 3219 3220 @Override 3221 public boolean isPackageAvailable(String packageName, int userId) { 3222 if (!sUserManager.exists(userId)) return false; 3223 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3224 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3225 synchronized (mPackages) { 3226 PackageParser.Package p = mPackages.get(packageName); 3227 if (p != null) { 3228 final PackageSetting ps = (PackageSetting) p.mExtras; 3229 if (ps != null) { 3230 final PackageUserState state = ps.readUserState(userId); 3231 if (state != null) { 3232 return PackageParser.isAvailable(state); 3233 } 3234 } 3235 } 3236 } 3237 return false; 3238 } 3239 3240 @Override 3241 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3242 if (!sUserManager.exists(userId)) return null; 3243 flags = updateFlagsForPackage(flags, userId, packageName); 3244 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3245 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3246 3247 // reader 3248 synchronized (mPackages) { 3249 // Normalize package name to hanlde renamed packages 3250 packageName = normalizePackageNameLPr(packageName); 3251 3252 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3253 PackageParser.Package p = null; 3254 if (matchFactoryOnly) { 3255 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3256 if (ps != null) { 3257 return generatePackageInfo(ps, flags, userId); 3258 } 3259 } 3260 if (p == null) { 3261 p = mPackages.get(packageName); 3262 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3263 return null; 3264 } 3265 } 3266 if (DEBUG_PACKAGE_INFO) 3267 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3268 if (p != null) { 3269 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3270 } 3271 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3272 final PackageSetting ps = mSettings.mPackages.get(packageName); 3273 return generatePackageInfo(ps, flags, userId); 3274 } 3275 } 3276 return null; 3277 } 3278 3279 @Override 3280 public String[] currentToCanonicalPackageNames(String[] names) { 3281 String[] out = new String[names.length]; 3282 // reader 3283 synchronized (mPackages) { 3284 for (int i=names.length-1; i>=0; i--) { 3285 PackageSetting ps = mSettings.mPackages.get(names[i]); 3286 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3287 } 3288 } 3289 return out; 3290 } 3291 3292 @Override 3293 public String[] canonicalToCurrentPackageNames(String[] names) { 3294 String[] out = new String[names.length]; 3295 // reader 3296 synchronized (mPackages) { 3297 for (int i=names.length-1; i>=0; i--) { 3298 String cur = mSettings.getRenamedPackageLPr(names[i]); 3299 out[i] = cur != null ? cur : names[i]; 3300 } 3301 } 3302 return out; 3303 } 3304 3305 @Override 3306 public int getPackageUid(String packageName, int flags, int userId) { 3307 if (!sUserManager.exists(userId)) return -1; 3308 flags = updateFlagsForPackage(flags, userId, packageName); 3309 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3310 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3311 3312 // reader 3313 synchronized (mPackages) { 3314 final PackageParser.Package p = mPackages.get(packageName); 3315 if (p != null && p.isMatch(flags)) { 3316 return UserHandle.getUid(userId, p.applicationInfo.uid); 3317 } 3318 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3319 final PackageSetting ps = mSettings.mPackages.get(packageName); 3320 if (ps != null && ps.isMatch(flags)) { 3321 return UserHandle.getUid(userId, ps.appId); 3322 } 3323 } 3324 } 3325 3326 return -1; 3327 } 3328 3329 @Override 3330 public int[] getPackageGids(String packageName, int flags, int userId) { 3331 if (!sUserManager.exists(userId)) return null; 3332 flags = updateFlagsForPackage(flags, userId, packageName); 3333 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3334 false /* requireFullPermission */, false /* checkShell */, 3335 "getPackageGids"); 3336 3337 // reader 3338 synchronized (mPackages) { 3339 final PackageParser.Package p = mPackages.get(packageName); 3340 if (p != null && p.isMatch(flags)) { 3341 PackageSetting ps = (PackageSetting) p.mExtras; 3342 // TODO: Shouldn't this be checking for package installed state for userId and 3343 // return null? 3344 return ps.getPermissionsState().computeGids(userId); 3345 } 3346 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3347 final PackageSetting ps = mSettings.mPackages.get(packageName); 3348 if (ps != null && ps.isMatch(flags)) { 3349 return ps.getPermissionsState().computeGids(userId); 3350 } 3351 } 3352 } 3353 3354 return null; 3355 } 3356 3357 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3358 if (bp.perm != null) { 3359 return PackageParser.generatePermissionInfo(bp.perm, flags); 3360 } 3361 PermissionInfo pi = new PermissionInfo(); 3362 pi.name = bp.name; 3363 pi.packageName = bp.sourcePackage; 3364 pi.nonLocalizedLabel = bp.name; 3365 pi.protectionLevel = bp.protectionLevel; 3366 return pi; 3367 } 3368 3369 @Override 3370 public PermissionInfo getPermissionInfo(String name, int flags) { 3371 // reader 3372 synchronized (mPackages) { 3373 final BasePermission p = mSettings.mPermissions.get(name); 3374 if (p != null) { 3375 return generatePermissionInfo(p, flags); 3376 } 3377 return null; 3378 } 3379 } 3380 3381 @Override 3382 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3383 int flags) { 3384 // reader 3385 synchronized (mPackages) { 3386 if (group != null && !mPermissionGroups.containsKey(group)) { 3387 // This is thrown as NameNotFoundException 3388 return null; 3389 } 3390 3391 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3392 for (BasePermission p : mSettings.mPermissions.values()) { 3393 if (group == null) { 3394 if (p.perm == null || p.perm.info.group == null) { 3395 out.add(generatePermissionInfo(p, flags)); 3396 } 3397 } else { 3398 if (p.perm != null && group.equals(p.perm.info.group)) { 3399 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3400 } 3401 } 3402 } 3403 return new ParceledListSlice<>(out); 3404 } 3405 } 3406 3407 @Override 3408 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3409 // reader 3410 synchronized (mPackages) { 3411 return PackageParser.generatePermissionGroupInfo( 3412 mPermissionGroups.get(name), flags); 3413 } 3414 } 3415 3416 @Override 3417 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3418 // reader 3419 synchronized (mPackages) { 3420 final int N = mPermissionGroups.size(); 3421 ArrayList<PermissionGroupInfo> out 3422 = new ArrayList<PermissionGroupInfo>(N); 3423 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3424 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3425 } 3426 return new ParceledListSlice<>(out); 3427 } 3428 } 3429 3430 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3431 int userId) { 3432 if (!sUserManager.exists(userId)) return null; 3433 PackageSetting ps = mSettings.mPackages.get(packageName); 3434 if (ps != null) { 3435 if (ps.pkg == null) { 3436 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3437 if (pInfo != null) { 3438 return pInfo.applicationInfo; 3439 } 3440 return null; 3441 } 3442 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3443 ps.readUserState(userId), userId); 3444 } 3445 return null; 3446 } 3447 3448 @Override 3449 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3450 if (!sUserManager.exists(userId)) return null; 3451 flags = updateFlagsForApplication(flags, userId, packageName); 3452 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3453 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3454 3455 // writer 3456 synchronized (mPackages) { 3457 // Normalize package name to hanlde renamed packages 3458 packageName = normalizePackageNameLPr(packageName); 3459 3460 PackageParser.Package p = mPackages.get(packageName); 3461 if (DEBUG_PACKAGE_INFO) Log.v( 3462 TAG, "getApplicationInfo " + packageName 3463 + ": " + p); 3464 if (p != null) { 3465 PackageSetting ps = mSettings.mPackages.get(packageName); 3466 if (ps == null) return null; 3467 // Note: isEnabledLP() does not apply here - always return info 3468 return PackageParser.generateApplicationInfo( 3469 p, flags, ps.readUserState(userId), userId); 3470 } 3471 if ("android".equals(packageName)||"system".equals(packageName)) { 3472 return mAndroidApplication; 3473 } 3474 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3475 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3476 } 3477 } 3478 return null; 3479 } 3480 3481 private String normalizePackageNameLPr(String packageName) { 3482 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3483 return normalizedPackageName != null ? normalizedPackageName : packageName; 3484 } 3485 3486 @Override 3487 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3488 final IPackageDataObserver observer) { 3489 mContext.enforceCallingOrSelfPermission( 3490 android.Manifest.permission.CLEAR_APP_CACHE, null); 3491 // Queue up an async operation since clearing cache may take a little while. 3492 mHandler.post(new Runnable() { 3493 public void run() { 3494 mHandler.removeCallbacks(this); 3495 boolean success = true; 3496 synchronized (mInstallLock) { 3497 try { 3498 mInstaller.freeCache(volumeUuid, freeStorageSize); 3499 } catch (InstallerException e) { 3500 Slog.w(TAG, "Couldn't clear application caches: " + e); 3501 success = false; 3502 } 3503 } 3504 if (observer != null) { 3505 try { 3506 observer.onRemoveCompleted(null, success); 3507 } catch (RemoteException e) { 3508 Slog.w(TAG, "RemoveException when invoking call back"); 3509 } 3510 } 3511 } 3512 }); 3513 } 3514 3515 @Override 3516 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3517 final IntentSender pi) { 3518 mContext.enforceCallingOrSelfPermission( 3519 android.Manifest.permission.CLEAR_APP_CACHE, null); 3520 // Queue up an async operation since clearing cache may take a little while. 3521 mHandler.post(new Runnable() { 3522 public void run() { 3523 mHandler.removeCallbacks(this); 3524 boolean success = true; 3525 synchronized (mInstallLock) { 3526 try { 3527 mInstaller.freeCache(volumeUuid, freeStorageSize); 3528 } catch (InstallerException e) { 3529 Slog.w(TAG, "Couldn't clear application caches: " + e); 3530 success = false; 3531 } 3532 } 3533 if(pi != null) { 3534 try { 3535 // Callback via pending intent 3536 int code = success ? 1 : 0; 3537 pi.sendIntent(null, code, null, 3538 null, null); 3539 } catch (SendIntentException e1) { 3540 Slog.i(TAG, "Failed to send pending intent"); 3541 } 3542 } 3543 } 3544 }); 3545 } 3546 3547 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3548 synchronized (mInstallLock) { 3549 try { 3550 mInstaller.freeCache(volumeUuid, freeStorageSize); 3551 } catch (InstallerException e) { 3552 throw new IOException("Failed to free enough space", e); 3553 } 3554 } 3555 } 3556 3557 /** 3558 * Update given flags based on encryption status of current user. 3559 */ 3560 private int updateFlags(int flags, int userId) { 3561 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3562 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3563 // Caller expressed an explicit opinion about what encryption 3564 // aware/unaware components they want to see, so fall through and 3565 // give them what they want 3566 } else { 3567 // Caller expressed no opinion, so match based on user state 3568 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3569 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3570 } else { 3571 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3572 } 3573 } 3574 return flags; 3575 } 3576 3577 private UserManagerInternal getUserManagerInternal() { 3578 if (mUserManagerInternal == null) { 3579 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3580 } 3581 return mUserManagerInternal; 3582 } 3583 3584 /** 3585 * Update given flags when being used to request {@link PackageInfo}. 3586 */ 3587 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3588 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3589 boolean triaged = true; 3590 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3591 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3592 // Caller is asking for component details, so they'd better be 3593 // asking for specific encryption matching behavior, or be triaged 3594 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3595 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3596 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3597 triaged = false; 3598 } 3599 } 3600 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3601 | PackageManager.MATCH_SYSTEM_ONLY 3602 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3603 triaged = false; 3604 } 3605 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3606 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3607 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3608 + Debug.getCallers(5)); 3609 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3610 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3611 // If the caller wants all packages and has a restricted profile associated with it, 3612 // then match all users. This is to make sure that launchers that need to access work 3613 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3614 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3615 flags |= PackageManager.MATCH_ANY_USER; 3616 } 3617 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3618 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3619 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3620 } 3621 return updateFlags(flags, userId); 3622 } 3623 3624 /** 3625 * Update given flags when being used to request {@link ApplicationInfo}. 3626 */ 3627 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3628 return updateFlagsForPackage(flags, userId, cookie); 3629 } 3630 3631 /** 3632 * Update given flags when being used to request {@link ComponentInfo}. 3633 */ 3634 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3635 if (cookie instanceof Intent) { 3636 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3637 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3638 } 3639 } 3640 3641 boolean triaged = true; 3642 // Caller is asking for component details, so they'd better be 3643 // asking for specific encryption matching behavior, or be triaged 3644 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3645 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3646 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3647 triaged = false; 3648 } 3649 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3650 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3651 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3652 } 3653 3654 return updateFlags(flags, userId); 3655 } 3656 3657 /** 3658 * Update given flags when being used to request {@link ResolveInfo}. 3659 */ 3660 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3661 // Safe mode means we shouldn't match any third-party components 3662 if (mSafeMode) { 3663 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3664 } 3665 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 3666 if (ephemeralPkgName != null) { 3667 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3668 flags |= PackageManager.MATCH_EPHEMERAL; 3669 } 3670 3671 return updateFlagsForComponent(flags, userId, cookie); 3672 } 3673 3674 @Override 3675 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3676 if (!sUserManager.exists(userId)) return null; 3677 flags = updateFlagsForComponent(flags, userId, component); 3678 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3679 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3680 synchronized (mPackages) { 3681 PackageParser.Activity a = mActivities.mActivities.get(component); 3682 3683 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3684 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3685 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3686 if (ps == null) return null; 3687 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3688 userId); 3689 } 3690 if (mResolveComponentName.equals(component)) { 3691 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3692 new PackageUserState(), userId); 3693 } 3694 } 3695 return null; 3696 } 3697 3698 @Override 3699 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3700 String resolvedType) { 3701 synchronized (mPackages) { 3702 if (component.equals(mResolveComponentName)) { 3703 // The resolver supports EVERYTHING! 3704 return true; 3705 } 3706 PackageParser.Activity a = mActivities.mActivities.get(component); 3707 if (a == null) { 3708 return false; 3709 } 3710 for (int i=0; i<a.intents.size(); i++) { 3711 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3712 intent.getData(), intent.getCategories(), TAG) >= 0) { 3713 return true; 3714 } 3715 } 3716 return false; 3717 } 3718 } 3719 3720 @Override 3721 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3722 if (!sUserManager.exists(userId)) return null; 3723 flags = updateFlagsForComponent(flags, userId, component); 3724 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3725 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3726 synchronized (mPackages) { 3727 PackageParser.Activity a = mReceivers.mActivities.get(component); 3728 if (DEBUG_PACKAGE_INFO) Log.v( 3729 TAG, "getReceiverInfo " + component + ": " + a); 3730 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3731 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3732 if (ps == null) return null; 3733 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3734 userId); 3735 } 3736 } 3737 return null; 3738 } 3739 3740 @Override 3741 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3742 if (!sUserManager.exists(userId)) return null; 3743 flags = updateFlagsForComponent(flags, userId, component); 3744 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3745 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3746 synchronized (mPackages) { 3747 PackageParser.Service s = mServices.mServices.get(component); 3748 if (DEBUG_PACKAGE_INFO) Log.v( 3749 TAG, "getServiceInfo " + component + ": " + s); 3750 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3751 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3752 if (ps == null) return null; 3753 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3754 userId); 3755 } 3756 } 3757 return null; 3758 } 3759 3760 @Override 3761 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3762 if (!sUserManager.exists(userId)) return null; 3763 flags = updateFlagsForComponent(flags, userId, component); 3764 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3765 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3766 synchronized (mPackages) { 3767 PackageParser.Provider p = mProviders.mProviders.get(component); 3768 if (DEBUG_PACKAGE_INFO) Log.v( 3769 TAG, "getProviderInfo " + component + ": " + p); 3770 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3771 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3772 if (ps == null) return null; 3773 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3774 userId); 3775 } 3776 } 3777 return null; 3778 } 3779 3780 @Override 3781 public String[] getSystemSharedLibraryNames() { 3782 Set<String> libSet; 3783 synchronized (mPackages) { 3784 libSet = mSharedLibraries.keySet(); 3785 int size = libSet.size(); 3786 if (size > 0) { 3787 String[] libs = new String[size]; 3788 libSet.toArray(libs); 3789 return libs; 3790 } 3791 } 3792 return null; 3793 } 3794 3795 @Override 3796 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3797 synchronized (mPackages) { 3798 return mServicesSystemSharedLibraryPackageName; 3799 } 3800 } 3801 3802 @Override 3803 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3804 synchronized (mPackages) { 3805 return mSharedSystemSharedLibraryPackageName; 3806 } 3807 } 3808 3809 @Override 3810 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3811 synchronized (mPackages) { 3812 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3813 3814 final FeatureInfo fi = new FeatureInfo(); 3815 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3816 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3817 res.add(fi); 3818 3819 return new ParceledListSlice<>(res); 3820 } 3821 } 3822 3823 @Override 3824 public boolean hasSystemFeature(String name, int version) { 3825 synchronized (mPackages) { 3826 final FeatureInfo feat = mAvailableFeatures.get(name); 3827 if (feat == null) { 3828 return false; 3829 } else { 3830 return feat.version >= version; 3831 } 3832 } 3833 } 3834 3835 @Override 3836 public int checkPermission(String permName, String pkgName, int userId) { 3837 if (!sUserManager.exists(userId)) { 3838 return PackageManager.PERMISSION_DENIED; 3839 } 3840 3841 synchronized (mPackages) { 3842 final PackageParser.Package p = mPackages.get(pkgName); 3843 if (p != null && p.mExtras != null) { 3844 final PackageSetting ps = (PackageSetting) p.mExtras; 3845 final PermissionsState permissionsState = ps.getPermissionsState(); 3846 if (permissionsState.hasPermission(permName, userId)) { 3847 return PackageManager.PERMISSION_GRANTED; 3848 } 3849 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3850 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3851 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3852 return PackageManager.PERMISSION_GRANTED; 3853 } 3854 } 3855 } 3856 3857 return PackageManager.PERMISSION_DENIED; 3858 } 3859 3860 @Override 3861 public int checkUidPermission(String permName, int uid) { 3862 final int userId = UserHandle.getUserId(uid); 3863 3864 if (!sUserManager.exists(userId)) { 3865 return PackageManager.PERMISSION_DENIED; 3866 } 3867 3868 synchronized (mPackages) { 3869 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3870 if (obj != null) { 3871 final SettingBase ps = (SettingBase) obj; 3872 final PermissionsState permissionsState = ps.getPermissionsState(); 3873 if (permissionsState.hasPermission(permName, userId)) { 3874 return PackageManager.PERMISSION_GRANTED; 3875 } 3876 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3877 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3878 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3879 return PackageManager.PERMISSION_GRANTED; 3880 } 3881 } else { 3882 ArraySet<String> perms = mSystemPermissions.get(uid); 3883 if (perms != null) { 3884 if (perms.contains(permName)) { 3885 return PackageManager.PERMISSION_GRANTED; 3886 } 3887 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3888 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3889 return PackageManager.PERMISSION_GRANTED; 3890 } 3891 } 3892 } 3893 } 3894 3895 return PackageManager.PERMISSION_DENIED; 3896 } 3897 3898 @Override 3899 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3900 if (UserHandle.getCallingUserId() != userId) { 3901 mContext.enforceCallingPermission( 3902 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3903 "isPermissionRevokedByPolicy for user " + userId); 3904 } 3905 3906 if (checkPermission(permission, packageName, userId) 3907 == PackageManager.PERMISSION_GRANTED) { 3908 return false; 3909 } 3910 3911 final long identity = Binder.clearCallingIdentity(); 3912 try { 3913 final int flags = getPermissionFlags(permission, packageName, userId); 3914 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3915 } finally { 3916 Binder.restoreCallingIdentity(identity); 3917 } 3918 } 3919 3920 @Override 3921 public String getPermissionControllerPackageName() { 3922 synchronized (mPackages) { 3923 return mRequiredInstallerPackage; 3924 } 3925 } 3926 3927 /** 3928 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3929 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3930 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3931 * @param message the message to log on security exception 3932 */ 3933 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3934 boolean checkShell, String message) { 3935 if (userId < 0) { 3936 throw new IllegalArgumentException("Invalid userId " + userId); 3937 } 3938 if (checkShell) { 3939 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3940 } 3941 if (userId == UserHandle.getUserId(callingUid)) return; 3942 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3943 if (requireFullPermission) { 3944 mContext.enforceCallingOrSelfPermission( 3945 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3946 } else { 3947 try { 3948 mContext.enforceCallingOrSelfPermission( 3949 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3950 } catch (SecurityException se) { 3951 mContext.enforceCallingOrSelfPermission( 3952 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3953 } 3954 } 3955 } 3956 } 3957 3958 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3959 if (callingUid == Process.SHELL_UID) { 3960 if (userHandle >= 0 3961 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3962 throw new SecurityException("Shell does not have permission to access user " 3963 + userHandle); 3964 } else if (userHandle < 0) { 3965 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3966 + Debug.getCallers(3)); 3967 } 3968 } 3969 } 3970 3971 private BasePermission findPermissionTreeLP(String permName) { 3972 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3973 if (permName.startsWith(bp.name) && 3974 permName.length() > bp.name.length() && 3975 permName.charAt(bp.name.length()) == '.') { 3976 return bp; 3977 } 3978 } 3979 return null; 3980 } 3981 3982 private BasePermission checkPermissionTreeLP(String permName) { 3983 if (permName != null) { 3984 BasePermission bp = findPermissionTreeLP(permName); 3985 if (bp != null) { 3986 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3987 return bp; 3988 } 3989 throw new SecurityException("Calling uid " 3990 + Binder.getCallingUid() 3991 + " is not allowed to add to permission tree " 3992 + bp.name + " owned by uid " + bp.uid); 3993 } 3994 } 3995 throw new SecurityException("No permission tree found for " + permName); 3996 } 3997 3998 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3999 if (s1 == null) { 4000 return s2 == null; 4001 } 4002 if (s2 == null) { 4003 return false; 4004 } 4005 if (s1.getClass() != s2.getClass()) { 4006 return false; 4007 } 4008 return s1.equals(s2); 4009 } 4010 4011 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4012 if (pi1.icon != pi2.icon) return false; 4013 if (pi1.logo != pi2.logo) return false; 4014 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4015 if (!compareStrings(pi1.name, pi2.name)) return false; 4016 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4017 // We'll take care of setting this one. 4018 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4019 // These are not currently stored in settings. 4020 //if (!compareStrings(pi1.group, pi2.group)) return false; 4021 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4022 //if (pi1.labelRes != pi2.labelRes) return false; 4023 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4024 return true; 4025 } 4026 4027 int permissionInfoFootprint(PermissionInfo info) { 4028 int size = info.name.length(); 4029 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4030 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4031 return size; 4032 } 4033 4034 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4035 int size = 0; 4036 for (BasePermission perm : mSettings.mPermissions.values()) { 4037 if (perm.uid == tree.uid) { 4038 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4039 } 4040 } 4041 return size; 4042 } 4043 4044 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4045 // We calculate the max size of permissions defined by this uid and throw 4046 // if that plus the size of 'info' would exceed our stated maximum. 4047 if (tree.uid != Process.SYSTEM_UID) { 4048 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4049 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4050 throw new SecurityException("Permission tree size cap exceeded"); 4051 } 4052 } 4053 } 4054 4055 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4056 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4057 throw new SecurityException("Label must be specified in permission"); 4058 } 4059 BasePermission tree = checkPermissionTreeLP(info.name); 4060 BasePermission bp = mSettings.mPermissions.get(info.name); 4061 boolean added = bp == null; 4062 boolean changed = true; 4063 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4064 if (added) { 4065 enforcePermissionCapLocked(info, tree); 4066 bp = new BasePermission(info.name, tree.sourcePackage, 4067 BasePermission.TYPE_DYNAMIC); 4068 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4069 throw new SecurityException( 4070 "Not allowed to modify non-dynamic permission " 4071 + info.name); 4072 } else { 4073 if (bp.protectionLevel == fixedLevel 4074 && bp.perm.owner.equals(tree.perm.owner) 4075 && bp.uid == tree.uid 4076 && comparePermissionInfos(bp.perm.info, info)) { 4077 changed = false; 4078 } 4079 } 4080 bp.protectionLevel = fixedLevel; 4081 info = new PermissionInfo(info); 4082 info.protectionLevel = fixedLevel; 4083 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4084 bp.perm.info.packageName = tree.perm.info.packageName; 4085 bp.uid = tree.uid; 4086 if (added) { 4087 mSettings.mPermissions.put(info.name, bp); 4088 } 4089 if (changed) { 4090 if (!async) { 4091 mSettings.writeLPr(); 4092 } else { 4093 scheduleWriteSettingsLocked(); 4094 } 4095 } 4096 return added; 4097 } 4098 4099 @Override 4100 public boolean addPermission(PermissionInfo info) { 4101 synchronized (mPackages) { 4102 return addPermissionLocked(info, false); 4103 } 4104 } 4105 4106 @Override 4107 public boolean addPermissionAsync(PermissionInfo info) { 4108 synchronized (mPackages) { 4109 return addPermissionLocked(info, true); 4110 } 4111 } 4112 4113 @Override 4114 public void removePermission(String name) { 4115 synchronized (mPackages) { 4116 checkPermissionTreeLP(name); 4117 BasePermission bp = mSettings.mPermissions.get(name); 4118 if (bp != null) { 4119 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4120 throw new SecurityException( 4121 "Not allowed to modify non-dynamic permission " 4122 + name); 4123 } 4124 mSettings.mPermissions.remove(name); 4125 mSettings.writeLPr(); 4126 } 4127 } 4128 } 4129 4130 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4131 BasePermission bp) { 4132 int index = pkg.requestedPermissions.indexOf(bp.name); 4133 if (index == -1) { 4134 throw new SecurityException("Package " + pkg.packageName 4135 + " has not requested permission " + bp.name); 4136 } 4137 if (!bp.isRuntime() && !bp.isDevelopment()) { 4138 throw new SecurityException("Permission " + bp.name 4139 + " is not a changeable permission type"); 4140 } 4141 } 4142 4143 @Override 4144 public void grantRuntimePermission(String packageName, String name, final int userId) { 4145 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4146 } 4147 4148 private void grantRuntimePermission(String packageName, String name, final int userId, 4149 boolean overridePolicy) { 4150 if (!sUserManager.exists(userId)) { 4151 Log.e(TAG, "No such user:" + userId); 4152 return; 4153 } 4154 4155 mContext.enforceCallingOrSelfPermission( 4156 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4157 "grantRuntimePermission"); 4158 4159 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4160 true /* requireFullPermission */, true /* checkShell */, 4161 "grantRuntimePermission"); 4162 4163 final int uid; 4164 final SettingBase sb; 4165 4166 synchronized (mPackages) { 4167 final PackageParser.Package pkg = mPackages.get(packageName); 4168 if (pkg == null) { 4169 throw new IllegalArgumentException("Unknown package: " + packageName); 4170 } 4171 4172 final BasePermission bp = mSettings.mPermissions.get(name); 4173 if (bp == null) { 4174 throw new IllegalArgumentException("Unknown permission: " + name); 4175 } 4176 4177 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4178 4179 // If a permission review is required for legacy apps we represent 4180 // their permissions as always granted runtime ones since we need 4181 // to keep the review required permission flag per user while an 4182 // install permission's state is shared across all users. 4183 if (mPermissionReviewRequired 4184 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4185 && bp.isRuntime()) { 4186 return; 4187 } 4188 4189 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4190 sb = (SettingBase) pkg.mExtras; 4191 if (sb == null) { 4192 throw new IllegalArgumentException("Unknown package: " + packageName); 4193 } 4194 4195 final PermissionsState permissionsState = sb.getPermissionsState(); 4196 4197 final int flags = permissionsState.getPermissionFlags(name, userId); 4198 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4199 throw new SecurityException("Cannot grant system fixed permission " 4200 + name + " for package " + packageName); 4201 } 4202 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4203 throw new SecurityException("Cannot grant policy fixed permission " 4204 + name + " for package " + packageName); 4205 } 4206 4207 if (bp.isDevelopment()) { 4208 // Development permissions must be handled specially, since they are not 4209 // normal runtime permissions. For now they apply to all users. 4210 if (permissionsState.grantInstallPermission(bp) != 4211 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4212 scheduleWriteSettingsLocked(); 4213 } 4214 return; 4215 } 4216 4217 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4218 throw new SecurityException("Cannot grant non-ephemeral permission" 4219 + name + " for package " + packageName); 4220 } 4221 4222 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4223 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4224 return; 4225 } 4226 4227 final int result = permissionsState.grantRuntimePermission(bp, userId); 4228 switch (result) { 4229 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4230 return; 4231 } 4232 4233 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4234 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4235 mHandler.post(new Runnable() { 4236 @Override 4237 public void run() { 4238 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4239 } 4240 }); 4241 } 4242 break; 4243 } 4244 4245 if (bp.isRuntime()) { 4246 logPermissionGranted(mContext, name, packageName); 4247 } 4248 4249 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4250 4251 // Not critical if that is lost - app has to request again. 4252 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4253 } 4254 4255 // Only need to do this if user is initialized. Otherwise it's a new user 4256 // and there are no processes running as the user yet and there's no need 4257 // to make an expensive call to remount processes for the changed permissions. 4258 if (READ_EXTERNAL_STORAGE.equals(name) 4259 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4260 final long token = Binder.clearCallingIdentity(); 4261 try { 4262 if (sUserManager.isInitialized(userId)) { 4263 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4264 StorageManagerInternal.class); 4265 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4266 } 4267 } finally { 4268 Binder.restoreCallingIdentity(token); 4269 } 4270 } 4271 } 4272 4273 @Override 4274 public void revokeRuntimePermission(String packageName, String name, int userId) { 4275 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4276 } 4277 4278 private void revokeRuntimePermission(String packageName, String name, int userId, 4279 boolean overridePolicy) { 4280 if (!sUserManager.exists(userId)) { 4281 Log.e(TAG, "No such user:" + userId); 4282 return; 4283 } 4284 4285 mContext.enforceCallingOrSelfPermission( 4286 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4287 "revokeRuntimePermission"); 4288 4289 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4290 true /* requireFullPermission */, true /* checkShell */, 4291 "revokeRuntimePermission"); 4292 4293 final int appId; 4294 4295 synchronized (mPackages) { 4296 final PackageParser.Package pkg = mPackages.get(packageName); 4297 if (pkg == null) { 4298 throw new IllegalArgumentException("Unknown package: " + packageName); 4299 } 4300 4301 final BasePermission bp = mSettings.mPermissions.get(name); 4302 if (bp == null) { 4303 throw new IllegalArgumentException("Unknown permission: " + name); 4304 } 4305 4306 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4307 4308 // If a permission review is required for legacy apps we represent 4309 // their permissions as always granted runtime ones since we need 4310 // to keep the review required permission flag per user while an 4311 // install permission's state is shared across all users. 4312 if (mPermissionReviewRequired 4313 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4314 && bp.isRuntime()) { 4315 return; 4316 } 4317 4318 SettingBase sb = (SettingBase) pkg.mExtras; 4319 if (sb == null) { 4320 throw new IllegalArgumentException("Unknown package: " + packageName); 4321 } 4322 4323 final PermissionsState permissionsState = sb.getPermissionsState(); 4324 4325 final int flags = permissionsState.getPermissionFlags(name, userId); 4326 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4327 throw new SecurityException("Cannot revoke system fixed permission " 4328 + name + " for package " + packageName); 4329 } 4330 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4331 throw new SecurityException("Cannot revoke policy fixed permission " 4332 + name + " for package " + packageName); 4333 } 4334 4335 if (bp.isDevelopment()) { 4336 // Development permissions must be handled specially, since they are not 4337 // normal runtime permissions. For now they apply to all users. 4338 if (permissionsState.revokeInstallPermission(bp) != 4339 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4340 scheduleWriteSettingsLocked(); 4341 } 4342 return; 4343 } 4344 4345 if (permissionsState.revokeRuntimePermission(bp, userId) == 4346 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4347 return; 4348 } 4349 4350 if (bp.isRuntime()) { 4351 logPermissionRevoked(mContext, name, packageName); 4352 } 4353 4354 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4355 4356 // Critical, after this call app should never have the permission. 4357 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4358 4359 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4360 } 4361 4362 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4363 } 4364 4365 /** 4366 * Get the first event id for the permission. 4367 * 4368 * <p>There are four events for each permission: <ul> 4369 * <li>Request permission: first id + 0</li> 4370 * <li>Grant permission: first id + 1</li> 4371 * <li>Request for permission denied: first id + 2</li> 4372 * <li>Revoke permission: first id + 3</li> 4373 * </ul></p> 4374 * 4375 * @param name name of the permission 4376 * 4377 * @return The first event id for the permission 4378 */ 4379 private static int getBaseEventId(@NonNull String name) { 4380 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4381 4382 if (eventIdIndex == -1) { 4383 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4384 || "user".equals(Build.TYPE)) { 4385 Log.i(TAG, "Unknown permission " + name); 4386 4387 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4388 } else { 4389 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4390 // 4391 // Also update 4392 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4393 // - metrics_constants.proto 4394 throw new IllegalStateException("Unknown permission " + name); 4395 } 4396 } 4397 4398 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4399 } 4400 4401 /** 4402 * Log that a permission was revoked. 4403 * 4404 * @param context Context of the caller 4405 * @param name name of the permission 4406 * @param packageName package permission if for 4407 */ 4408 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4409 @NonNull String packageName) { 4410 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4411 } 4412 4413 /** 4414 * Log that a permission request was granted. 4415 * 4416 * @param context Context of the caller 4417 * @param name name of the permission 4418 * @param packageName package permission if for 4419 */ 4420 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4421 @NonNull String packageName) { 4422 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4423 } 4424 4425 @Override 4426 public void resetRuntimePermissions() { 4427 mContext.enforceCallingOrSelfPermission( 4428 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4429 "revokeRuntimePermission"); 4430 4431 int callingUid = Binder.getCallingUid(); 4432 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4433 mContext.enforceCallingOrSelfPermission( 4434 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4435 "resetRuntimePermissions"); 4436 } 4437 4438 synchronized (mPackages) { 4439 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4440 for (int userId : UserManagerService.getInstance().getUserIds()) { 4441 final int packageCount = mPackages.size(); 4442 for (int i = 0; i < packageCount; i++) { 4443 PackageParser.Package pkg = mPackages.valueAt(i); 4444 if (!(pkg.mExtras instanceof PackageSetting)) { 4445 continue; 4446 } 4447 PackageSetting ps = (PackageSetting) pkg.mExtras; 4448 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4449 } 4450 } 4451 } 4452 } 4453 4454 @Override 4455 public int getPermissionFlags(String name, String packageName, int userId) { 4456 if (!sUserManager.exists(userId)) { 4457 return 0; 4458 } 4459 4460 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4461 4462 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4463 true /* requireFullPermission */, false /* checkShell */, 4464 "getPermissionFlags"); 4465 4466 synchronized (mPackages) { 4467 final PackageParser.Package pkg = mPackages.get(packageName); 4468 if (pkg == null) { 4469 return 0; 4470 } 4471 4472 final BasePermission bp = mSettings.mPermissions.get(name); 4473 if (bp == null) { 4474 return 0; 4475 } 4476 4477 SettingBase sb = (SettingBase) pkg.mExtras; 4478 if (sb == null) { 4479 return 0; 4480 } 4481 4482 PermissionsState permissionsState = sb.getPermissionsState(); 4483 return permissionsState.getPermissionFlags(name, userId); 4484 } 4485 } 4486 4487 @Override 4488 public void updatePermissionFlags(String name, String packageName, int flagMask, 4489 int flagValues, int userId) { 4490 if (!sUserManager.exists(userId)) { 4491 return; 4492 } 4493 4494 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4495 4496 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4497 true /* requireFullPermission */, true /* checkShell */, 4498 "updatePermissionFlags"); 4499 4500 // Only the system can change these flags and nothing else. 4501 if (getCallingUid() != Process.SYSTEM_UID) { 4502 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4503 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4504 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4505 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4506 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4507 } 4508 4509 synchronized (mPackages) { 4510 final PackageParser.Package pkg = mPackages.get(packageName); 4511 if (pkg == null) { 4512 throw new IllegalArgumentException("Unknown package: " + packageName); 4513 } 4514 4515 final BasePermission bp = mSettings.mPermissions.get(name); 4516 if (bp == null) { 4517 throw new IllegalArgumentException("Unknown permission: " + name); 4518 } 4519 4520 SettingBase sb = (SettingBase) pkg.mExtras; 4521 if (sb == null) { 4522 throw new IllegalArgumentException("Unknown package: " + packageName); 4523 } 4524 4525 PermissionsState permissionsState = sb.getPermissionsState(); 4526 4527 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4528 4529 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4530 // Install and runtime permissions are stored in different places, 4531 // so figure out what permission changed and persist the change. 4532 if (permissionsState.getInstallPermissionState(name) != null) { 4533 scheduleWriteSettingsLocked(); 4534 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4535 || hadState) { 4536 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4537 } 4538 } 4539 } 4540 } 4541 4542 /** 4543 * Update the permission flags for all packages and runtime permissions of a user in order 4544 * to allow device or profile owner to remove POLICY_FIXED. 4545 */ 4546 @Override 4547 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4548 if (!sUserManager.exists(userId)) { 4549 return; 4550 } 4551 4552 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4553 4554 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4555 true /* requireFullPermission */, true /* checkShell */, 4556 "updatePermissionFlagsForAllApps"); 4557 4558 // Only the system can change system fixed flags. 4559 if (getCallingUid() != Process.SYSTEM_UID) { 4560 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4561 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4562 } 4563 4564 synchronized (mPackages) { 4565 boolean changed = false; 4566 final int packageCount = mPackages.size(); 4567 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4568 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4569 SettingBase sb = (SettingBase) pkg.mExtras; 4570 if (sb == null) { 4571 continue; 4572 } 4573 PermissionsState permissionsState = sb.getPermissionsState(); 4574 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4575 userId, flagMask, flagValues); 4576 } 4577 if (changed) { 4578 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4579 } 4580 } 4581 } 4582 4583 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4584 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4585 != PackageManager.PERMISSION_GRANTED 4586 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4587 != PackageManager.PERMISSION_GRANTED) { 4588 throw new SecurityException(message + " requires " 4589 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4590 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4591 } 4592 } 4593 4594 @Override 4595 public boolean shouldShowRequestPermissionRationale(String permissionName, 4596 String packageName, int userId) { 4597 if (UserHandle.getCallingUserId() != userId) { 4598 mContext.enforceCallingPermission( 4599 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4600 "canShowRequestPermissionRationale for user " + userId); 4601 } 4602 4603 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4604 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4605 return false; 4606 } 4607 4608 if (checkPermission(permissionName, packageName, userId) 4609 == PackageManager.PERMISSION_GRANTED) { 4610 return false; 4611 } 4612 4613 final int flags; 4614 4615 final long identity = Binder.clearCallingIdentity(); 4616 try { 4617 flags = getPermissionFlags(permissionName, 4618 packageName, userId); 4619 } finally { 4620 Binder.restoreCallingIdentity(identity); 4621 } 4622 4623 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4624 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4625 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4626 4627 if ((flags & fixedFlags) != 0) { 4628 return false; 4629 } 4630 4631 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4632 } 4633 4634 @Override 4635 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4636 mContext.enforceCallingOrSelfPermission( 4637 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4638 "addOnPermissionsChangeListener"); 4639 4640 synchronized (mPackages) { 4641 mOnPermissionChangeListeners.addListenerLocked(listener); 4642 } 4643 } 4644 4645 @Override 4646 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4647 synchronized (mPackages) { 4648 mOnPermissionChangeListeners.removeListenerLocked(listener); 4649 } 4650 } 4651 4652 @Override 4653 public boolean isProtectedBroadcast(String actionName) { 4654 synchronized (mPackages) { 4655 if (mProtectedBroadcasts.contains(actionName)) { 4656 return true; 4657 } else if (actionName != null) { 4658 // TODO: remove these terrible hacks 4659 if (actionName.startsWith("android.net.netmon.lingerExpired") 4660 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4661 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4662 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4663 return true; 4664 } 4665 } 4666 } 4667 return false; 4668 } 4669 4670 @Override 4671 public int checkSignatures(String pkg1, String pkg2) { 4672 synchronized (mPackages) { 4673 final PackageParser.Package p1 = mPackages.get(pkg1); 4674 final PackageParser.Package p2 = mPackages.get(pkg2); 4675 if (p1 == null || p1.mExtras == null 4676 || p2 == null || p2.mExtras == null) { 4677 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4678 } 4679 return compareSignatures(p1.mSignatures, p2.mSignatures); 4680 } 4681 } 4682 4683 @Override 4684 public int checkUidSignatures(int uid1, int uid2) { 4685 // Map to base uids. 4686 uid1 = UserHandle.getAppId(uid1); 4687 uid2 = UserHandle.getAppId(uid2); 4688 // reader 4689 synchronized (mPackages) { 4690 Signature[] s1; 4691 Signature[] s2; 4692 Object obj = mSettings.getUserIdLPr(uid1); 4693 if (obj != null) { 4694 if (obj instanceof SharedUserSetting) { 4695 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4696 } else if (obj instanceof PackageSetting) { 4697 s1 = ((PackageSetting)obj).signatures.mSignatures; 4698 } else { 4699 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4700 } 4701 } else { 4702 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4703 } 4704 obj = mSettings.getUserIdLPr(uid2); 4705 if (obj != null) { 4706 if (obj instanceof SharedUserSetting) { 4707 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4708 } else if (obj instanceof PackageSetting) { 4709 s2 = ((PackageSetting)obj).signatures.mSignatures; 4710 } else { 4711 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4712 } 4713 } else { 4714 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4715 } 4716 return compareSignatures(s1, s2); 4717 } 4718 } 4719 4720 /** 4721 * This method should typically only be used when granting or revoking 4722 * permissions, since the app may immediately restart after this call. 4723 * <p> 4724 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4725 * guard your work against the app being relaunched. 4726 */ 4727 private void killUid(int appId, int userId, String reason) { 4728 final long identity = Binder.clearCallingIdentity(); 4729 try { 4730 IActivityManager am = ActivityManager.getService(); 4731 if (am != null) { 4732 try { 4733 am.killUid(appId, userId, reason); 4734 } catch (RemoteException e) { 4735 /* ignore - same process */ 4736 } 4737 } 4738 } finally { 4739 Binder.restoreCallingIdentity(identity); 4740 } 4741 } 4742 4743 /** 4744 * Compares two sets of signatures. Returns: 4745 * <br /> 4746 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4747 * <br /> 4748 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4749 * <br /> 4750 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4751 * <br /> 4752 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4753 * <br /> 4754 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4755 */ 4756 static int compareSignatures(Signature[] s1, Signature[] s2) { 4757 if (s1 == null) { 4758 return s2 == null 4759 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4760 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4761 } 4762 4763 if (s2 == null) { 4764 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4765 } 4766 4767 if (s1.length != s2.length) { 4768 return PackageManager.SIGNATURE_NO_MATCH; 4769 } 4770 4771 // Since both signature sets are of size 1, we can compare without HashSets. 4772 if (s1.length == 1) { 4773 return s1[0].equals(s2[0]) ? 4774 PackageManager.SIGNATURE_MATCH : 4775 PackageManager.SIGNATURE_NO_MATCH; 4776 } 4777 4778 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4779 for (Signature sig : s1) { 4780 set1.add(sig); 4781 } 4782 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4783 for (Signature sig : s2) { 4784 set2.add(sig); 4785 } 4786 // Make sure s2 contains all signatures in s1. 4787 if (set1.equals(set2)) { 4788 return PackageManager.SIGNATURE_MATCH; 4789 } 4790 return PackageManager.SIGNATURE_NO_MATCH; 4791 } 4792 4793 /** 4794 * If the database version for this type of package (internal storage or 4795 * external storage) is less than the version where package signatures 4796 * were updated, return true. 4797 */ 4798 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4799 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4800 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4801 } 4802 4803 /** 4804 * Used for backward compatibility to make sure any packages with 4805 * certificate chains get upgraded to the new style. {@code existingSigs} 4806 * will be in the old format (since they were stored on disk from before the 4807 * system upgrade) and {@code scannedSigs} will be in the newer format. 4808 */ 4809 private int compareSignaturesCompat(PackageSignatures existingSigs, 4810 PackageParser.Package scannedPkg) { 4811 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4812 return PackageManager.SIGNATURE_NO_MATCH; 4813 } 4814 4815 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4816 for (Signature sig : existingSigs.mSignatures) { 4817 existingSet.add(sig); 4818 } 4819 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4820 for (Signature sig : scannedPkg.mSignatures) { 4821 try { 4822 Signature[] chainSignatures = sig.getChainSignatures(); 4823 for (Signature chainSig : chainSignatures) { 4824 scannedCompatSet.add(chainSig); 4825 } 4826 } catch (CertificateEncodingException e) { 4827 scannedCompatSet.add(sig); 4828 } 4829 } 4830 /* 4831 * Make sure the expanded scanned set contains all signatures in the 4832 * existing one. 4833 */ 4834 if (scannedCompatSet.equals(existingSet)) { 4835 // Migrate the old signatures to the new scheme. 4836 existingSigs.assignSignatures(scannedPkg.mSignatures); 4837 // The new KeySets will be re-added later in the scanning process. 4838 synchronized (mPackages) { 4839 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4840 } 4841 return PackageManager.SIGNATURE_MATCH; 4842 } 4843 return PackageManager.SIGNATURE_NO_MATCH; 4844 } 4845 4846 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4847 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4848 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4849 } 4850 4851 private int compareSignaturesRecover(PackageSignatures existingSigs, 4852 PackageParser.Package scannedPkg) { 4853 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4854 return PackageManager.SIGNATURE_NO_MATCH; 4855 } 4856 4857 String msg = null; 4858 try { 4859 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4860 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4861 + scannedPkg.packageName); 4862 return PackageManager.SIGNATURE_MATCH; 4863 } 4864 } catch (CertificateException e) { 4865 msg = e.getMessage(); 4866 } 4867 4868 logCriticalInfo(Log.INFO, 4869 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4870 return PackageManager.SIGNATURE_NO_MATCH; 4871 } 4872 4873 @Override 4874 public List<String> getAllPackages() { 4875 synchronized (mPackages) { 4876 return new ArrayList<String>(mPackages.keySet()); 4877 } 4878 } 4879 4880 @Override 4881 public String[] getPackagesForUid(int uid) { 4882 final int userId = UserHandle.getUserId(uid); 4883 uid = UserHandle.getAppId(uid); 4884 // reader 4885 synchronized (mPackages) { 4886 Object obj = mSettings.getUserIdLPr(uid); 4887 if (obj instanceof SharedUserSetting) { 4888 final SharedUserSetting sus = (SharedUserSetting) obj; 4889 final int N = sus.packages.size(); 4890 String[] res = new String[N]; 4891 final Iterator<PackageSetting> it = sus.packages.iterator(); 4892 int i = 0; 4893 while (it.hasNext()) { 4894 PackageSetting ps = it.next(); 4895 if (ps.getInstalled(userId)) { 4896 res[i++] = ps.name; 4897 } else { 4898 res = ArrayUtils.removeElement(String.class, res, res[i]); 4899 } 4900 } 4901 return res; 4902 } else if (obj instanceof PackageSetting) { 4903 final PackageSetting ps = (PackageSetting) obj; 4904 return new String[] { ps.name }; 4905 } 4906 } 4907 return null; 4908 } 4909 4910 @Override 4911 public String getNameForUid(int uid) { 4912 // reader 4913 synchronized (mPackages) { 4914 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4915 if (obj instanceof SharedUserSetting) { 4916 final SharedUserSetting sus = (SharedUserSetting) obj; 4917 return sus.name + ":" + sus.userId; 4918 } else if (obj instanceof PackageSetting) { 4919 final PackageSetting ps = (PackageSetting) obj; 4920 return ps.name; 4921 } 4922 } 4923 return null; 4924 } 4925 4926 @Override 4927 public int getUidForSharedUser(String sharedUserName) { 4928 if(sharedUserName == null) { 4929 return -1; 4930 } 4931 // reader 4932 synchronized (mPackages) { 4933 SharedUserSetting suid; 4934 try { 4935 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4936 if (suid != null) { 4937 return suid.userId; 4938 } 4939 } catch (PackageManagerException ignore) { 4940 // can't happen, but, still need to catch it 4941 } 4942 return -1; 4943 } 4944 } 4945 4946 @Override 4947 public int getFlagsForUid(int uid) { 4948 synchronized (mPackages) { 4949 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4950 if (obj instanceof SharedUserSetting) { 4951 final SharedUserSetting sus = (SharedUserSetting) obj; 4952 return sus.pkgFlags; 4953 } else if (obj instanceof PackageSetting) { 4954 final PackageSetting ps = (PackageSetting) obj; 4955 return ps.pkgFlags; 4956 } 4957 } 4958 return 0; 4959 } 4960 4961 @Override 4962 public int getPrivateFlagsForUid(int uid) { 4963 synchronized (mPackages) { 4964 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4965 if (obj instanceof SharedUserSetting) { 4966 final SharedUserSetting sus = (SharedUserSetting) obj; 4967 return sus.pkgPrivateFlags; 4968 } else if (obj instanceof PackageSetting) { 4969 final PackageSetting ps = (PackageSetting) obj; 4970 return ps.pkgPrivateFlags; 4971 } 4972 } 4973 return 0; 4974 } 4975 4976 @Override 4977 public boolean isUidPrivileged(int uid) { 4978 uid = UserHandle.getAppId(uid); 4979 // reader 4980 synchronized (mPackages) { 4981 Object obj = mSettings.getUserIdLPr(uid); 4982 if (obj instanceof SharedUserSetting) { 4983 final SharedUserSetting sus = (SharedUserSetting) obj; 4984 final Iterator<PackageSetting> it = sus.packages.iterator(); 4985 while (it.hasNext()) { 4986 if (it.next().isPrivileged()) { 4987 return true; 4988 } 4989 } 4990 } else if (obj instanceof PackageSetting) { 4991 final PackageSetting ps = (PackageSetting) obj; 4992 return ps.isPrivileged(); 4993 } 4994 } 4995 return false; 4996 } 4997 4998 @Override 4999 public String[] getAppOpPermissionPackages(String permissionName) { 5000 synchronized (mPackages) { 5001 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5002 if (pkgs == null) { 5003 return null; 5004 } 5005 return pkgs.toArray(new String[pkgs.size()]); 5006 } 5007 } 5008 5009 @Override 5010 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5011 int flags, int userId) { 5012 try { 5013 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5014 5015 if (!sUserManager.exists(userId)) return null; 5016 flags = updateFlagsForResolve(flags, userId, intent); 5017 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5018 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5019 5020 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5021 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5022 flags, userId); 5023 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5024 5025 final ResolveInfo bestChoice = 5026 chooseBestActivity(intent, resolvedType, flags, query, userId); 5027 return bestChoice; 5028 } finally { 5029 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5030 } 5031 } 5032 5033 @Override 5034 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5035 IntentFilter filter, int match, ComponentName activity) { 5036 final int userId = UserHandle.getCallingUserId(); 5037 if (DEBUG_PREFERRED) { 5038 Log.v(TAG, "setLastChosenActivity intent=" + intent 5039 + " resolvedType=" + resolvedType 5040 + " flags=" + flags 5041 + " filter=" + filter 5042 + " match=" + match 5043 + " activity=" + activity); 5044 filter.dump(new PrintStreamPrinter(System.out), " "); 5045 } 5046 intent.setComponent(null); 5047 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5048 userId); 5049 // Find any earlier preferred or last chosen entries and nuke them 5050 findPreferredActivity(intent, resolvedType, 5051 flags, query, 0, false, true, false, userId); 5052 // Add the new activity as the last chosen for this filter 5053 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5054 "Setting last chosen"); 5055 } 5056 5057 @Override 5058 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5059 final int userId = UserHandle.getCallingUserId(); 5060 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5061 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5062 userId); 5063 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5064 false, false, false, userId); 5065 } 5066 5067 private boolean isEphemeralDisabled() { 5068 // ephemeral apps have been disabled across the board 5069 if (DISABLE_EPHEMERAL_APPS) { 5070 return true; 5071 } 5072 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5073 if (!mSystemReady) { 5074 return true; 5075 } 5076 // we can't get a content resolver until the system is ready; these checks must happen last 5077 final ContentResolver resolver = mContext.getContentResolver(); 5078 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5079 return true; 5080 } 5081 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5082 } 5083 5084 private boolean isEphemeralAllowed( 5085 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5086 boolean skipPackageCheck) { 5087 // Short circuit and return early if possible. 5088 if (isEphemeralDisabled()) { 5089 return false; 5090 } 5091 final int callingUser = UserHandle.getCallingUserId(); 5092 if (callingUser != UserHandle.USER_SYSTEM) { 5093 return false; 5094 } 5095 if (mEphemeralResolverConnection == null) { 5096 return false; 5097 } 5098 if (mEphemeralInstallerComponent == null) { 5099 return false; 5100 } 5101 if (intent.getComponent() != null) { 5102 return false; 5103 } 5104 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5105 return false; 5106 } 5107 if (!skipPackageCheck && intent.getPackage() != null) { 5108 return false; 5109 } 5110 final boolean isWebUri = hasWebURI(intent); 5111 if (!isWebUri || intent.getData().getHost() == null) { 5112 return false; 5113 } 5114 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5115 synchronized (mPackages) { 5116 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5117 for (int n = 0; n < count; n++) { 5118 ResolveInfo info = resolvedActivities.get(n); 5119 String packageName = info.activityInfo.packageName; 5120 PackageSetting ps = mSettings.mPackages.get(packageName); 5121 if (ps != null) { 5122 // Try to get the status from User settings first 5123 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5124 int status = (int) (packedStatus >> 32); 5125 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5126 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5127 if (DEBUG_EPHEMERAL) { 5128 Slog.v(TAG, "DENY ephemeral apps;" 5129 + " pkg: " + packageName + ", status: " + status); 5130 } 5131 return false; 5132 } 5133 } 5134 } 5135 } 5136 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5137 return true; 5138 } 5139 5140 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5141 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5142 int userId) { 5143 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5144 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5145 callingPackage, userId)); 5146 mHandler.sendMessage(msg); 5147 } 5148 5149 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5150 int flags, List<ResolveInfo> query, int userId) { 5151 if (query != null) { 5152 final int N = query.size(); 5153 if (N == 1) { 5154 return query.get(0); 5155 } else if (N > 1) { 5156 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5157 // If there is more than one activity with the same priority, 5158 // then let the user decide between them. 5159 ResolveInfo r0 = query.get(0); 5160 ResolveInfo r1 = query.get(1); 5161 if (DEBUG_INTENT_MATCHING || debug) { 5162 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5163 + r1.activityInfo.name + "=" + r1.priority); 5164 } 5165 // If the first activity has a higher priority, or a different 5166 // default, then it is always desirable to pick it. 5167 if (r0.priority != r1.priority 5168 || r0.preferredOrder != r1.preferredOrder 5169 || r0.isDefault != r1.isDefault) { 5170 return query.get(0); 5171 } 5172 // If we have saved a preference for a preferred activity for 5173 // this Intent, use that. 5174 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5175 flags, query, r0.priority, true, false, debug, userId); 5176 if (ri != null) { 5177 return ri; 5178 } 5179 ri = new ResolveInfo(mResolveInfo); 5180 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5181 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5182 // If all of the options come from the same package, show the application's 5183 // label and icon instead of the generic resolver's. 5184 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5185 // and then throw away the ResolveInfo itself, meaning that the caller loses 5186 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5187 // a fallback for this case; we only set the target package's resources on 5188 // the ResolveInfo, not the ActivityInfo. 5189 final String intentPackage = intent.getPackage(); 5190 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5191 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5192 ri.resolvePackageName = intentPackage; 5193 if (userNeedsBadging(userId)) { 5194 ri.noResourceId = true; 5195 } else { 5196 ri.icon = appi.icon; 5197 } 5198 ri.iconResourceId = appi.icon; 5199 ri.labelRes = appi.labelRes; 5200 } 5201 ri.activityInfo.applicationInfo = new ApplicationInfo( 5202 ri.activityInfo.applicationInfo); 5203 if (userId != 0) { 5204 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5205 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5206 } 5207 // Make sure that the resolver is displayable in car mode 5208 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5209 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5210 return ri; 5211 } 5212 } 5213 return null; 5214 } 5215 5216 /** 5217 * Return true if the given list is not empty and all of its contents have 5218 * an activityInfo with the given package name. 5219 */ 5220 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5221 if (ArrayUtils.isEmpty(list)) { 5222 return false; 5223 } 5224 for (int i = 0, N = list.size(); i < N; i++) { 5225 final ResolveInfo ri = list.get(i); 5226 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5227 if (ai == null || !packageName.equals(ai.packageName)) { 5228 return false; 5229 } 5230 } 5231 return true; 5232 } 5233 5234 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5235 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5236 final int N = query.size(); 5237 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5238 .get(userId); 5239 // Get the list of persistent preferred activities that handle the intent 5240 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5241 List<PersistentPreferredActivity> pprefs = ppir != null 5242 ? ppir.queryIntent(intent, resolvedType, 5243 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5244 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5245 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5246 : null; 5247 if (pprefs != null && pprefs.size() > 0) { 5248 final int M = pprefs.size(); 5249 for (int i=0; i<M; i++) { 5250 final PersistentPreferredActivity ppa = pprefs.get(i); 5251 if (DEBUG_PREFERRED || debug) { 5252 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5253 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5254 + "\n component=" + ppa.mComponent); 5255 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5256 } 5257 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5258 flags | MATCH_DISABLED_COMPONENTS, userId); 5259 if (DEBUG_PREFERRED || debug) { 5260 Slog.v(TAG, "Found persistent preferred activity:"); 5261 if (ai != null) { 5262 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5263 } else { 5264 Slog.v(TAG, " null"); 5265 } 5266 } 5267 if (ai == null) { 5268 // This previously registered persistent preferred activity 5269 // component is no longer known. Ignore it and do NOT remove it. 5270 continue; 5271 } 5272 for (int j=0; j<N; j++) { 5273 final ResolveInfo ri = query.get(j); 5274 if (!ri.activityInfo.applicationInfo.packageName 5275 .equals(ai.applicationInfo.packageName)) { 5276 continue; 5277 } 5278 if (!ri.activityInfo.name.equals(ai.name)) { 5279 continue; 5280 } 5281 // Found a persistent preference that can handle the intent. 5282 if (DEBUG_PREFERRED || debug) { 5283 Slog.v(TAG, "Returning persistent preferred activity: " + 5284 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5285 } 5286 return ri; 5287 } 5288 } 5289 } 5290 return null; 5291 } 5292 5293 // TODO: handle preferred activities missing while user has amnesia 5294 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5295 List<ResolveInfo> query, int priority, boolean always, 5296 boolean removeMatches, boolean debug, int userId) { 5297 if (!sUserManager.exists(userId)) return null; 5298 flags = updateFlagsForResolve(flags, userId, intent); 5299 // writer 5300 synchronized (mPackages) { 5301 if (intent.getSelector() != null) { 5302 intent = intent.getSelector(); 5303 } 5304 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5305 5306 // Try to find a matching persistent preferred activity. 5307 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5308 debug, userId); 5309 5310 // If a persistent preferred activity matched, use it. 5311 if (pri != null) { 5312 return pri; 5313 } 5314 5315 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5316 // Get the list of preferred activities that handle the intent 5317 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5318 List<PreferredActivity> prefs = pir != null 5319 ? pir.queryIntent(intent, resolvedType, 5320 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5321 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5322 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5323 : null; 5324 if (prefs != null && prefs.size() > 0) { 5325 boolean changed = false; 5326 try { 5327 // First figure out how good the original match set is. 5328 // We will only allow preferred activities that came 5329 // from the same match quality. 5330 int match = 0; 5331 5332 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5333 5334 final int N = query.size(); 5335 for (int j=0; j<N; j++) { 5336 final ResolveInfo ri = query.get(j); 5337 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5338 + ": 0x" + Integer.toHexString(match)); 5339 if (ri.match > match) { 5340 match = ri.match; 5341 } 5342 } 5343 5344 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5345 + Integer.toHexString(match)); 5346 5347 match &= IntentFilter.MATCH_CATEGORY_MASK; 5348 final int M = prefs.size(); 5349 for (int i=0; i<M; i++) { 5350 final PreferredActivity pa = prefs.get(i); 5351 if (DEBUG_PREFERRED || debug) { 5352 Slog.v(TAG, "Checking PreferredActivity ds=" 5353 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5354 + "\n component=" + pa.mPref.mComponent); 5355 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5356 } 5357 if (pa.mPref.mMatch != match) { 5358 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5359 + Integer.toHexString(pa.mPref.mMatch)); 5360 continue; 5361 } 5362 // If it's not an "always" type preferred activity and that's what we're 5363 // looking for, skip it. 5364 if (always && !pa.mPref.mAlways) { 5365 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5366 continue; 5367 } 5368 final ActivityInfo ai = getActivityInfo( 5369 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5370 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5371 userId); 5372 if (DEBUG_PREFERRED || debug) { 5373 Slog.v(TAG, "Found preferred activity:"); 5374 if (ai != null) { 5375 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5376 } else { 5377 Slog.v(TAG, " null"); 5378 } 5379 } 5380 if (ai == null) { 5381 // This previously registered preferred activity 5382 // component is no longer known. Most likely an update 5383 // to the app was installed and in the new version this 5384 // component no longer exists. Clean it up by removing 5385 // it from the preferred activities list, and skip it. 5386 Slog.w(TAG, "Removing dangling preferred activity: " 5387 + pa.mPref.mComponent); 5388 pir.removeFilter(pa); 5389 changed = true; 5390 continue; 5391 } 5392 for (int j=0; j<N; j++) { 5393 final ResolveInfo ri = query.get(j); 5394 if (!ri.activityInfo.applicationInfo.packageName 5395 .equals(ai.applicationInfo.packageName)) { 5396 continue; 5397 } 5398 if (!ri.activityInfo.name.equals(ai.name)) { 5399 continue; 5400 } 5401 5402 if (removeMatches) { 5403 pir.removeFilter(pa); 5404 changed = true; 5405 if (DEBUG_PREFERRED) { 5406 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5407 } 5408 break; 5409 } 5410 5411 // Okay we found a previously set preferred or last chosen app. 5412 // If the result set is different from when this 5413 // was created, we need to clear it and re-ask the 5414 // user their preference, if we're looking for an "always" type entry. 5415 if (always && !pa.mPref.sameSet(query)) { 5416 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5417 + intent + " type " + resolvedType); 5418 if (DEBUG_PREFERRED) { 5419 Slog.v(TAG, "Removing preferred activity since set changed " 5420 + pa.mPref.mComponent); 5421 } 5422 pir.removeFilter(pa); 5423 // Re-add the filter as a "last chosen" entry (!always) 5424 PreferredActivity lastChosen = new PreferredActivity( 5425 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5426 pir.addFilter(lastChosen); 5427 changed = true; 5428 return null; 5429 } 5430 5431 // Yay! Either the set matched or we're looking for the last chosen 5432 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5433 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5434 return ri; 5435 } 5436 } 5437 } finally { 5438 if (changed) { 5439 if (DEBUG_PREFERRED) { 5440 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5441 } 5442 scheduleWritePackageRestrictionsLocked(userId); 5443 } 5444 } 5445 } 5446 } 5447 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5448 return null; 5449 } 5450 5451 /* 5452 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5453 */ 5454 @Override 5455 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5456 int targetUserId) { 5457 mContext.enforceCallingOrSelfPermission( 5458 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5459 List<CrossProfileIntentFilter> matches = 5460 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5461 if (matches != null) { 5462 int size = matches.size(); 5463 for (int i = 0; i < size; i++) { 5464 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5465 } 5466 } 5467 if (hasWebURI(intent)) { 5468 // cross-profile app linking works only towards the parent. 5469 final UserInfo parent = getProfileParent(sourceUserId); 5470 synchronized(mPackages) { 5471 int flags = updateFlagsForResolve(0, parent.id, intent); 5472 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5473 intent, resolvedType, flags, sourceUserId, parent.id); 5474 return xpDomainInfo != null; 5475 } 5476 } 5477 return false; 5478 } 5479 5480 private UserInfo getProfileParent(int userId) { 5481 final long identity = Binder.clearCallingIdentity(); 5482 try { 5483 return sUserManager.getProfileParent(userId); 5484 } finally { 5485 Binder.restoreCallingIdentity(identity); 5486 } 5487 } 5488 5489 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5490 String resolvedType, int userId) { 5491 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5492 if (resolver != null) { 5493 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5494 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5495 } 5496 return null; 5497 } 5498 5499 @Override 5500 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5501 String resolvedType, int flags, int userId) { 5502 try { 5503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5504 5505 return new ParceledListSlice<>( 5506 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5507 } finally { 5508 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5509 } 5510 } 5511 5512 /** 5513 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5514 * ephemeral, returns {@code null}. 5515 */ 5516 private String getEphemeralPackageName(int callingUid) { 5517 final int appId = UserHandle.getAppId(callingUid); 5518 synchronized (mPackages) { 5519 final Object obj = mSettings.getUserIdLPr(appId); 5520 if (obj instanceof PackageSetting) { 5521 final PackageSetting ps = (PackageSetting) obj; 5522 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5523 } 5524 } 5525 return null; 5526 } 5527 5528 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5529 String resolvedType, int flags, int userId) { 5530 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5531 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5532 flags = updateFlagsForResolve(flags, userId, intent); 5533 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5534 false /* requireFullPermission */, false /* checkShell */, 5535 "query intent activities"); 5536 ComponentName comp = intent.getComponent(); 5537 if (comp == null) { 5538 if (intent.getSelector() != null) { 5539 intent = intent.getSelector(); 5540 comp = intent.getComponent(); 5541 } 5542 } 5543 5544 if (comp != null) { 5545 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5546 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5547 if (ai != null) { 5548 // When specifying an explicit component, we prevent the activity from being 5549 // used when either 1) the calling package is normal and the activity is within 5550 // an ephemeral application or 2) the calling package is ephemeral and the 5551 // activity is not visible to ephemeral applications. 5552 boolean blockResolution = 5553 (ephemeralPkgName == null 5554 && (ai.applicationInfo.privateFlags 5555 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5556 || (ephemeralPkgName != null 5557 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5558 if (!blockResolution) { 5559 final ResolveInfo ri = new ResolveInfo(); 5560 ri.activityInfo = ai; 5561 list.add(ri); 5562 } 5563 } 5564 return list; 5565 } 5566 5567 // reader 5568 boolean sortResult = false; 5569 boolean addEphemeral = false; 5570 List<ResolveInfo> result; 5571 final String pkgName = intent.getPackage(); 5572 synchronized (mPackages) { 5573 if (pkgName == null) { 5574 List<CrossProfileIntentFilter> matchingFilters = 5575 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5576 // Check for results that need to skip the current profile. 5577 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5578 resolvedType, flags, userId); 5579 if (xpResolveInfo != null) { 5580 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5581 xpResult.add(xpResolveInfo); 5582 return filterForEphemeral( 5583 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5584 } 5585 5586 // Check for results in the current profile. 5587 result = filterIfNotSystemUser(mActivities.queryIntent( 5588 intent, resolvedType, flags, userId), userId); 5589 addEphemeral = 5590 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5591 5592 // Check for cross profile results. 5593 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5594 xpResolveInfo = queryCrossProfileIntents( 5595 matchingFilters, intent, resolvedType, flags, userId, 5596 hasNonNegativePriorityResult); 5597 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5598 boolean isVisibleToUser = filterIfNotSystemUser( 5599 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5600 if (isVisibleToUser) { 5601 result.add(xpResolveInfo); 5602 sortResult = true; 5603 } 5604 } 5605 if (hasWebURI(intent)) { 5606 CrossProfileDomainInfo xpDomainInfo = null; 5607 final UserInfo parent = getProfileParent(userId); 5608 if (parent != null) { 5609 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5610 flags, userId, parent.id); 5611 } 5612 if (xpDomainInfo != null) { 5613 if (xpResolveInfo != null) { 5614 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5615 // in the result. 5616 result.remove(xpResolveInfo); 5617 } 5618 if (result.size() == 0 && !addEphemeral) { 5619 // No result in current profile, but found candidate in parent user. 5620 // And we are not going to add emphemeral app, so we can return the 5621 // result straight away. 5622 result.add(xpDomainInfo.resolveInfo); 5623 return filterForEphemeral(result, ephemeralPkgName); 5624 } 5625 } else if (result.size() <= 1 && !addEphemeral) { 5626 // No result in parent user and <= 1 result in current profile, and we 5627 // are not going to add emphemeral app, so we can return the result without 5628 // further processing. 5629 return filterForEphemeral(result, ephemeralPkgName); 5630 } 5631 // We have more than one candidate (combining results from current and parent 5632 // profile), so we need filtering and sorting. 5633 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5634 intent, flags, result, xpDomainInfo, userId); 5635 sortResult = true; 5636 } 5637 } else { 5638 final PackageParser.Package pkg = mPackages.get(pkgName); 5639 if (pkg != null) { 5640 result = filterForEphemeral(filterIfNotSystemUser( 5641 mActivities.queryIntentForPackage( 5642 intent, resolvedType, flags, pkg.activities, userId), 5643 userId), ephemeralPkgName); 5644 } else { 5645 // the caller wants to resolve for a particular package; however, there 5646 // were no installed results, so, try to find an ephemeral result 5647 addEphemeral = isEphemeralAllowed( 5648 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5649 result = new ArrayList<ResolveInfo>(); 5650 } 5651 } 5652 } 5653 if (addEphemeral) { 5654 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5655 final EphemeralRequest requestObject = new EphemeralRequest( 5656 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5657 null /*launchIntent*/, null /*callingPackage*/, userId); 5658 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5659 mContext, mEphemeralResolverConnection, requestObject); 5660 if (intentInfo != null) { 5661 if (DEBUG_EPHEMERAL) { 5662 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5663 } 5664 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5665 ephemeralInstaller.ephemeralResponse = intentInfo; 5666 // make sure this resolver is the default 5667 ephemeralInstaller.isDefault = true; 5668 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5669 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5670 // add a non-generic filter 5671 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5672 ephemeralInstaller.filter.addDataPath( 5673 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5674 result.add(ephemeralInstaller); 5675 } 5676 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5677 } 5678 if (sortResult) { 5679 Collections.sort(result, mResolvePrioritySorter); 5680 } 5681 return filterForEphemeral(result, ephemeralPkgName); 5682 } 5683 5684 private static class CrossProfileDomainInfo { 5685 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5686 ResolveInfo resolveInfo; 5687 /* Best domain verification status of the activities found in the other profile */ 5688 int bestDomainVerificationStatus; 5689 } 5690 5691 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5692 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5693 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5694 sourceUserId)) { 5695 return null; 5696 } 5697 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5698 resolvedType, flags, parentUserId); 5699 5700 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5701 return null; 5702 } 5703 CrossProfileDomainInfo result = null; 5704 int size = resultTargetUser.size(); 5705 for (int i = 0; i < size; i++) { 5706 ResolveInfo riTargetUser = resultTargetUser.get(i); 5707 // Intent filter verification is only for filters that specify a host. So don't return 5708 // those that handle all web uris. 5709 if (riTargetUser.handleAllWebDataURI) { 5710 continue; 5711 } 5712 String packageName = riTargetUser.activityInfo.packageName; 5713 PackageSetting ps = mSettings.mPackages.get(packageName); 5714 if (ps == null) { 5715 continue; 5716 } 5717 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5718 int status = (int)(verificationState >> 32); 5719 if (result == null) { 5720 result = new CrossProfileDomainInfo(); 5721 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5722 sourceUserId, parentUserId); 5723 result.bestDomainVerificationStatus = status; 5724 } else { 5725 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5726 result.bestDomainVerificationStatus); 5727 } 5728 } 5729 // Don't consider matches with status NEVER across profiles. 5730 if (result != null && result.bestDomainVerificationStatus 5731 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5732 return null; 5733 } 5734 return result; 5735 } 5736 5737 /** 5738 * Verification statuses are ordered from the worse to the best, except for 5739 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5740 */ 5741 private int bestDomainVerificationStatus(int status1, int status2) { 5742 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5743 return status2; 5744 } 5745 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5746 return status1; 5747 } 5748 return (int) MathUtils.max(status1, status2); 5749 } 5750 5751 private boolean isUserEnabled(int userId) { 5752 long callingId = Binder.clearCallingIdentity(); 5753 try { 5754 UserInfo userInfo = sUserManager.getUserInfo(userId); 5755 return userInfo != null && userInfo.isEnabled(); 5756 } finally { 5757 Binder.restoreCallingIdentity(callingId); 5758 } 5759 } 5760 5761 /** 5762 * Filter out activities with systemUserOnly flag set, when current user is not System. 5763 * 5764 * @return filtered list 5765 */ 5766 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5767 if (userId == UserHandle.USER_SYSTEM) { 5768 return resolveInfos; 5769 } 5770 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5771 ResolveInfo info = resolveInfos.get(i); 5772 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5773 resolveInfos.remove(i); 5774 } 5775 } 5776 return resolveInfos; 5777 } 5778 5779 /** 5780 * Filters out ephemeral activities. 5781 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 5782 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 5783 * 5784 * @param resolveInfos The pre-filtered list of resolved activities 5785 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 5786 * is performed. 5787 * @return A filtered list of resolved activities. 5788 */ 5789 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 5790 String ephemeralPkgName) { 5791 if (ephemeralPkgName == null) { 5792 return resolveInfos; 5793 } 5794 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5795 ResolveInfo info = resolveInfos.get(i); 5796 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 5797 // allow activities that are defined in the provided package 5798 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 5799 continue; 5800 } 5801 // allow activities that have been explicitly exposed to ephemeral apps 5802 if (!isEphemeralApp 5803 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 5804 continue; 5805 } 5806 resolveInfos.remove(i); 5807 } 5808 return resolveInfos; 5809 } 5810 5811 /** 5812 * @param resolveInfos list of resolve infos in descending priority order 5813 * @return if the list contains a resolve info with non-negative priority 5814 */ 5815 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5816 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5817 } 5818 5819 private static boolean hasWebURI(Intent intent) { 5820 if (intent.getData() == null) { 5821 return false; 5822 } 5823 final String scheme = intent.getScheme(); 5824 if (TextUtils.isEmpty(scheme)) { 5825 return false; 5826 } 5827 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5828 } 5829 5830 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5831 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5832 int userId) { 5833 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5834 5835 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5836 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5837 candidates.size()); 5838 } 5839 5840 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5841 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5842 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5843 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5844 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5845 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5846 5847 synchronized (mPackages) { 5848 final int count = candidates.size(); 5849 // First, try to use linked apps. Partition the candidates into four lists: 5850 // one for the final results, one for the "do not use ever", one for "undefined status" 5851 // and finally one for "browser app type". 5852 for (int n=0; n<count; n++) { 5853 ResolveInfo info = candidates.get(n); 5854 String packageName = info.activityInfo.packageName; 5855 PackageSetting ps = mSettings.mPackages.get(packageName); 5856 if (ps != null) { 5857 // Add to the special match all list (Browser use case) 5858 if (info.handleAllWebDataURI) { 5859 matchAllList.add(info); 5860 continue; 5861 } 5862 // Try to get the status from User settings first 5863 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5864 int status = (int)(packedStatus >> 32); 5865 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5866 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5867 if (DEBUG_DOMAIN_VERIFICATION) { 5868 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5869 + " : linkgen=" + linkGeneration); 5870 } 5871 // Use link-enabled generation as preferredOrder, i.e. 5872 // prefer newly-enabled over earlier-enabled. 5873 info.preferredOrder = linkGeneration; 5874 alwaysList.add(info); 5875 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5876 if (DEBUG_DOMAIN_VERIFICATION) { 5877 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5878 } 5879 neverList.add(info); 5880 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5881 if (DEBUG_DOMAIN_VERIFICATION) { 5882 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5883 } 5884 alwaysAskList.add(info); 5885 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5886 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5887 if (DEBUG_DOMAIN_VERIFICATION) { 5888 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5889 } 5890 undefinedList.add(info); 5891 } 5892 } 5893 } 5894 5895 // We'll want to include browser possibilities in a few cases 5896 boolean includeBrowser = false; 5897 5898 // First try to add the "always" resolution(s) for the current user, if any 5899 if (alwaysList.size() > 0) { 5900 result.addAll(alwaysList); 5901 } else { 5902 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5903 result.addAll(undefinedList); 5904 // Maybe add one for the other profile. 5905 if (xpDomainInfo != null && ( 5906 xpDomainInfo.bestDomainVerificationStatus 5907 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5908 result.add(xpDomainInfo.resolveInfo); 5909 } 5910 includeBrowser = true; 5911 } 5912 5913 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5914 // If there were 'always' entries their preferred order has been set, so we also 5915 // back that off to make the alternatives equivalent 5916 if (alwaysAskList.size() > 0) { 5917 for (ResolveInfo i : result) { 5918 i.preferredOrder = 0; 5919 } 5920 result.addAll(alwaysAskList); 5921 includeBrowser = true; 5922 } 5923 5924 if (includeBrowser) { 5925 // Also add browsers (all of them or only the default one) 5926 if (DEBUG_DOMAIN_VERIFICATION) { 5927 Slog.v(TAG, " ...including browsers in candidate set"); 5928 } 5929 if ((matchFlags & MATCH_ALL) != 0) { 5930 result.addAll(matchAllList); 5931 } else { 5932 // Browser/generic handling case. If there's a default browser, go straight 5933 // to that (but only if there is no other higher-priority match). 5934 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5935 int maxMatchPrio = 0; 5936 ResolveInfo defaultBrowserMatch = null; 5937 final int numCandidates = matchAllList.size(); 5938 for (int n = 0; n < numCandidates; n++) { 5939 ResolveInfo info = matchAllList.get(n); 5940 // track the highest overall match priority... 5941 if (info.priority > maxMatchPrio) { 5942 maxMatchPrio = info.priority; 5943 } 5944 // ...and the highest-priority default browser match 5945 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5946 if (defaultBrowserMatch == null 5947 || (defaultBrowserMatch.priority < info.priority)) { 5948 if (debug) { 5949 Slog.v(TAG, "Considering default browser match " + info); 5950 } 5951 defaultBrowserMatch = info; 5952 } 5953 } 5954 } 5955 if (defaultBrowserMatch != null 5956 && defaultBrowserMatch.priority >= maxMatchPrio 5957 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5958 { 5959 if (debug) { 5960 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5961 } 5962 result.add(defaultBrowserMatch); 5963 } else { 5964 result.addAll(matchAllList); 5965 } 5966 } 5967 5968 // If there is nothing selected, add all candidates and remove the ones that the user 5969 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5970 if (result.size() == 0) { 5971 result.addAll(candidates); 5972 result.removeAll(neverList); 5973 } 5974 } 5975 } 5976 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5977 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5978 result.size()); 5979 for (ResolveInfo info : result) { 5980 Slog.v(TAG, " + " + info.activityInfo); 5981 } 5982 } 5983 return result; 5984 } 5985 5986 // Returns a packed value as a long: 5987 // 5988 // high 'int'-sized word: link status: undefined/ask/never/always. 5989 // low 'int'-sized word: relative priority among 'always' results. 5990 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5991 long result = ps.getDomainVerificationStatusForUser(userId); 5992 // if none available, get the master status 5993 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5994 if (ps.getIntentFilterVerificationInfo() != null) { 5995 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5996 } 5997 } 5998 return result; 5999 } 6000 6001 private ResolveInfo querySkipCurrentProfileIntents( 6002 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6003 int flags, int sourceUserId) { 6004 if (matchingFilters != null) { 6005 int size = matchingFilters.size(); 6006 for (int i = 0; i < size; i ++) { 6007 CrossProfileIntentFilter filter = matchingFilters.get(i); 6008 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6009 // Checking if there are activities in the target user that can handle the 6010 // intent. 6011 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6012 resolvedType, flags, sourceUserId); 6013 if (resolveInfo != null) { 6014 return resolveInfo; 6015 } 6016 } 6017 } 6018 } 6019 return null; 6020 } 6021 6022 // Return matching ResolveInfo in target user if any. 6023 private ResolveInfo queryCrossProfileIntents( 6024 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6025 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6026 if (matchingFilters != null) { 6027 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6028 // match the same intent. For performance reasons, it is better not to 6029 // run queryIntent twice for the same userId 6030 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6031 int size = matchingFilters.size(); 6032 for (int i = 0; i < size; i++) { 6033 CrossProfileIntentFilter filter = matchingFilters.get(i); 6034 int targetUserId = filter.getTargetUserId(); 6035 boolean skipCurrentProfile = 6036 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6037 boolean skipCurrentProfileIfNoMatchFound = 6038 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6039 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6040 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6041 // Checking if there are activities in the target user that can handle the 6042 // intent. 6043 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6044 resolvedType, flags, sourceUserId); 6045 if (resolveInfo != null) return resolveInfo; 6046 alreadyTriedUserIds.put(targetUserId, true); 6047 } 6048 } 6049 } 6050 return null; 6051 } 6052 6053 /** 6054 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6055 * will forward the intent to the filter's target user. 6056 * Otherwise, returns null. 6057 */ 6058 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6059 String resolvedType, int flags, int sourceUserId) { 6060 int targetUserId = filter.getTargetUserId(); 6061 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6062 resolvedType, flags, targetUserId); 6063 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6064 // If all the matches in the target profile are suspended, return null. 6065 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6066 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6067 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6068 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6069 targetUserId); 6070 } 6071 } 6072 } 6073 return null; 6074 } 6075 6076 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6077 int sourceUserId, int targetUserId) { 6078 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6079 long ident = Binder.clearCallingIdentity(); 6080 boolean targetIsProfile; 6081 try { 6082 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6083 } finally { 6084 Binder.restoreCallingIdentity(ident); 6085 } 6086 String className; 6087 if (targetIsProfile) { 6088 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6089 } else { 6090 className = FORWARD_INTENT_TO_PARENT; 6091 } 6092 ComponentName forwardingActivityComponentName = new ComponentName( 6093 mAndroidApplication.packageName, className); 6094 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6095 sourceUserId); 6096 if (!targetIsProfile) { 6097 forwardingActivityInfo.showUserIcon = targetUserId; 6098 forwardingResolveInfo.noResourceId = true; 6099 } 6100 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6101 forwardingResolveInfo.priority = 0; 6102 forwardingResolveInfo.preferredOrder = 0; 6103 forwardingResolveInfo.match = 0; 6104 forwardingResolveInfo.isDefault = true; 6105 forwardingResolveInfo.filter = filter; 6106 forwardingResolveInfo.targetUserId = targetUserId; 6107 return forwardingResolveInfo; 6108 } 6109 6110 @Override 6111 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6112 Intent[] specifics, String[] specificTypes, Intent intent, 6113 String resolvedType, int flags, int userId) { 6114 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6115 specificTypes, intent, resolvedType, flags, userId)); 6116 } 6117 6118 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6119 Intent[] specifics, String[] specificTypes, Intent intent, 6120 String resolvedType, int flags, int userId) { 6121 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6122 flags = updateFlagsForResolve(flags, userId, intent); 6123 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6124 false /* requireFullPermission */, false /* checkShell */, 6125 "query intent activity options"); 6126 final String resultsAction = intent.getAction(); 6127 6128 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6129 | PackageManager.GET_RESOLVED_FILTER, userId); 6130 6131 if (DEBUG_INTENT_MATCHING) { 6132 Log.v(TAG, "Query " + intent + ": " + results); 6133 } 6134 6135 int specificsPos = 0; 6136 int N; 6137 6138 // todo: note that the algorithm used here is O(N^2). This 6139 // isn't a problem in our current environment, but if we start running 6140 // into situations where we have more than 5 or 10 matches then this 6141 // should probably be changed to something smarter... 6142 6143 // First we go through and resolve each of the specific items 6144 // that were supplied, taking care of removing any corresponding 6145 // duplicate items in the generic resolve list. 6146 if (specifics != null) { 6147 for (int i=0; i<specifics.length; i++) { 6148 final Intent sintent = specifics[i]; 6149 if (sintent == null) { 6150 continue; 6151 } 6152 6153 if (DEBUG_INTENT_MATCHING) { 6154 Log.v(TAG, "Specific #" + i + ": " + sintent); 6155 } 6156 6157 String action = sintent.getAction(); 6158 if (resultsAction != null && resultsAction.equals(action)) { 6159 // If this action was explicitly requested, then don't 6160 // remove things that have it. 6161 action = null; 6162 } 6163 6164 ResolveInfo ri = null; 6165 ActivityInfo ai = null; 6166 6167 ComponentName comp = sintent.getComponent(); 6168 if (comp == null) { 6169 ri = resolveIntent( 6170 sintent, 6171 specificTypes != null ? specificTypes[i] : null, 6172 flags, userId); 6173 if (ri == null) { 6174 continue; 6175 } 6176 if (ri == mResolveInfo) { 6177 // ACK! Must do something better with this. 6178 } 6179 ai = ri.activityInfo; 6180 comp = new ComponentName(ai.applicationInfo.packageName, 6181 ai.name); 6182 } else { 6183 ai = getActivityInfo(comp, flags, userId); 6184 if (ai == null) { 6185 continue; 6186 } 6187 } 6188 6189 // Look for any generic query activities that are duplicates 6190 // of this specific one, and remove them from the results. 6191 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6192 N = results.size(); 6193 int j; 6194 for (j=specificsPos; j<N; j++) { 6195 ResolveInfo sri = results.get(j); 6196 if ((sri.activityInfo.name.equals(comp.getClassName()) 6197 && sri.activityInfo.applicationInfo.packageName.equals( 6198 comp.getPackageName())) 6199 || (action != null && sri.filter.matchAction(action))) { 6200 results.remove(j); 6201 if (DEBUG_INTENT_MATCHING) Log.v( 6202 TAG, "Removing duplicate item from " + j 6203 + " due to specific " + specificsPos); 6204 if (ri == null) { 6205 ri = sri; 6206 } 6207 j--; 6208 N--; 6209 } 6210 } 6211 6212 // Add this specific item to its proper place. 6213 if (ri == null) { 6214 ri = new ResolveInfo(); 6215 ri.activityInfo = ai; 6216 } 6217 results.add(specificsPos, ri); 6218 ri.specificIndex = i; 6219 specificsPos++; 6220 } 6221 } 6222 6223 // Now we go through the remaining generic results and remove any 6224 // duplicate actions that are found here. 6225 N = results.size(); 6226 for (int i=specificsPos; i<N-1; i++) { 6227 final ResolveInfo rii = results.get(i); 6228 if (rii.filter == null) { 6229 continue; 6230 } 6231 6232 // Iterate over all of the actions of this result's intent 6233 // filter... typically this should be just one. 6234 final Iterator<String> it = rii.filter.actionsIterator(); 6235 if (it == null) { 6236 continue; 6237 } 6238 while (it.hasNext()) { 6239 final String action = it.next(); 6240 if (resultsAction != null && resultsAction.equals(action)) { 6241 // If this action was explicitly requested, then don't 6242 // remove things that have it. 6243 continue; 6244 } 6245 for (int j=i+1; j<N; j++) { 6246 final ResolveInfo rij = results.get(j); 6247 if (rij.filter != null && rij.filter.hasAction(action)) { 6248 results.remove(j); 6249 if (DEBUG_INTENT_MATCHING) Log.v( 6250 TAG, "Removing duplicate item from " + j 6251 + " due to action " + action + " at " + i); 6252 j--; 6253 N--; 6254 } 6255 } 6256 } 6257 6258 // If the caller didn't request filter information, drop it now 6259 // so we don't have to marshall/unmarshall it. 6260 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6261 rii.filter = null; 6262 } 6263 } 6264 6265 // Filter out the caller activity if so requested. 6266 if (caller != null) { 6267 N = results.size(); 6268 for (int i=0; i<N; i++) { 6269 ActivityInfo ainfo = results.get(i).activityInfo; 6270 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6271 && caller.getClassName().equals(ainfo.name)) { 6272 results.remove(i); 6273 break; 6274 } 6275 } 6276 } 6277 6278 // If the caller didn't request filter information, 6279 // drop them now so we don't have to 6280 // marshall/unmarshall it. 6281 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6282 N = results.size(); 6283 for (int i=0; i<N; i++) { 6284 results.get(i).filter = null; 6285 } 6286 } 6287 6288 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6289 return results; 6290 } 6291 6292 @Override 6293 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6294 String resolvedType, int flags, int userId) { 6295 return new ParceledListSlice<>( 6296 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6297 } 6298 6299 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6300 String resolvedType, int flags, int userId) { 6301 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6302 flags = updateFlagsForResolve(flags, userId, intent); 6303 ComponentName comp = intent.getComponent(); 6304 if (comp == null) { 6305 if (intent.getSelector() != null) { 6306 intent = intent.getSelector(); 6307 comp = intent.getComponent(); 6308 } 6309 } 6310 if (comp != null) { 6311 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6312 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6313 if (ai != null) { 6314 ResolveInfo ri = new ResolveInfo(); 6315 ri.activityInfo = ai; 6316 list.add(ri); 6317 } 6318 return list; 6319 } 6320 6321 // reader 6322 synchronized (mPackages) { 6323 String pkgName = intent.getPackage(); 6324 if (pkgName == null) { 6325 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6326 } 6327 final PackageParser.Package pkg = mPackages.get(pkgName); 6328 if (pkg != null) { 6329 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6330 userId); 6331 } 6332 return Collections.emptyList(); 6333 } 6334 } 6335 6336 @Override 6337 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6338 if (!sUserManager.exists(userId)) return null; 6339 flags = updateFlagsForResolve(flags, userId, intent); 6340 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6341 if (query != null) { 6342 if (query.size() >= 1) { 6343 // If there is more than one service with the same priority, 6344 // just arbitrarily pick the first one. 6345 return query.get(0); 6346 } 6347 } 6348 return null; 6349 } 6350 6351 @Override 6352 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6353 String resolvedType, int flags, int userId) { 6354 return new ParceledListSlice<>( 6355 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6356 } 6357 6358 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6359 String resolvedType, int flags, int userId) { 6360 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6361 flags = updateFlagsForResolve(flags, userId, intent); 6362 ComponentName comp = intent.getComponent(); 6363 if (comp == null) { 6364 if (intent.getSelector() != null) { 6365 intent = intent.getSelector(); 6366 comp = intent.getComponent(); 6367 } 6368 } 6369 if (comp != null) { 6370 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6371 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6372 if (si != null) { 6373 final ResolveInfo ri = new ResolveInfo(); 6374 ri.serviceInfo = si; 6375 list.add(ri); 6376 } 6377 return list; 6378 } 6379 6380 // reader 6381 synchronized (mPackages) { 6382 String pkgName = intent.getPackage(); 6383 if (pkgName == null) { 6384 return mServices.queryIntent(intent, resolvedType, flags, userId); 6385 } 6386 final PackageParser.Package pkg = mPackages.get(pkgName); 6387 if (pkg != null) { 6388 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6389 userId); 6390 } 6391 return Collections.emptyList(); 6392 } 6393 } 6394 6395 @Override 6396 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6397 String resolvedType, int flags, int userId) { 6398 return new ParceledListSlice<>( 6399 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6400 } 6401 6402 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6403 Intent intent, String resolvedType, int flags, int userId) { 6404 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6405 flags = updateFlagsForResolve(flags, userId, intent); 6406 ComponentName comp = intent.getComponent(); 6407 if (comp == null) { 6408 if (intent.getSelector() != null) { 6409 intent = intent.getSelector(); 6410 comp = intent.getComponent(); 6411 } 6412 } 6413 if (comp != null) { 6414 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6415 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6416 if (pi != null) { 6417 final ResolveInfo ri = new ResolveInfo(); 6418 ri.providerInfo = pi; 6419 list.add(ri); 6420 } 6421 return list; 6422 } 6423 6424 // reader 6425 synchronized (mPackages) { 6426 String pkgName = intent.getPackage(); 6427 if (pkgName == null) { 6428 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6429 } 6430 final PackageParser.Package pkg = mPackages.get(pkgName); 6431 if (pkg != null) { 6432 return mProviders.queryIntentForPackage( 6433 intent, resolvedType, flags, pkg.providers, userId); 6434 } 6435 return Collections.emptyList(); 6436 } 6437 } 6438 6439 @Override 6440 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6441 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6442 flags = updateFlagsForPackage(flags, userId, null); 6443 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6444 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6445 true /* requireFullPermission */, false /* checkShell */, 6446 "get installed packages"); 6447 6448 // writer 6449 synchronized (mPackages) { 6450 ArrayList<PackageInfo> list; 6451 if (listUninstalled) { 6452 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6453 for (PackageSetting ps : mSettings.mPackages.values()) { 6454 final PackageInfo pi; 6455 if (ps.pkg != null) { 6456 pi = generatePackageInfo(ps, flags, userId); 6457 } else { 6458 pi = generatePackageInfo(ps, flags, userId); 6459 } 6460 if (pi != null) { 6461 list.add(pi); 6462 } 6463 } 6464 } else { 6465 list = new ArrayList<PackageInfo>(mPackages.size()); 6466 for (PackageParser.Package p : mPackages.values()) { 6467 final PackageInfo pi = 6468 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6469 if (pi != null) { 6470 list.add(pi); 6471 } 6472 } 6473 } 6474 6475 return new ParceledListSlice<PackageInfo>(list); 6476 } 6477 } 6478 6479 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6480 String[] permissions, boolean[] tmp, int flags, int userId) { 6481 int numMatch = 0; 6482 final PermissionsState permissionsState = ps.getPermissionsState(); 6483 for (int i=0; i<permissions.length; i++) { 6484 final String permission = permissions[i]; 6485 if (permissionsState.hasPermission(permission, userId)) { 6486 tmp[i] = true; 6487 numMatch++; 6488 } else { 6489 tmp[i] = false; 6490 } 6491 } 6492 if (numMatch == 0) { 6493 return; 6494 } 6495 final PackageInfo pi; 6496 if (ps.pkg != null) { 6497 pi = generatePackageInfo(ps, flags, userId); 6498 } else { 6499 pi = generatePackageInfo(ps, flags, userId); 6500 } 6501 // The above might return null in cases of uninstalled apps or install-state 6502 // skew across users/profiles. 6503 if (pi != null) { 6504 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6505 if (numMatch == permissions.length) { 6506 pi.requestedPermissions = permissions; 6507 } else { 6508 pi.requestedPermissions = new String[numMatch]; 6509 numMatch = 0; 6510 for (int i=0; i<permissions.length; i++) { 6511 if (tmp[i]) { 6512 pi.requestedPermissions[numMatch] = permissions[i]; 6513 numMatch++; 6514 } 6515 } 6516 } 6517 } 6518 list.add(pi); 6519 } 6520 } 6521 6522 @Override 6523 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6524 String[] permissions, int flags, int userId) { 6525 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6526 flags = updateFlagsForPackage(flags, userId, permissions); 6527 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6528 true /* requireFullPermission */, false /* checkShell */, 6529 "get packages holding permissions"); 6530 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6531 6532 // writer 6533 synchronized (mPackages) { 6534 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6535 boolean[] tmpBools = new boolean[permissions.length]; 6536 if (listUninstalled) { 6537 for (PackageSetting ps : mSettings.mPackages.values()) { 6538 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6539 userId); 6540 } 6541 } else { 6542 for (PackageParser.Package pkg : mPackages.values()) { 6543 PackageSetting ps = (PackageSetting)pkg.mExtras; 6544 if (ps != null) { 6545 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6546 userId); 6547 } 6548 } 6549 } 6550 6551 return new ParceledListSlice<PackageInfo>(list); 6552 } 6553 } 6554 6555 @Override 6556 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6557 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6558 flags = updateFlagsForApplication(flags, userId, null); 6559 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6560 6561 // writer 6562 synchronized (mPackages) { 6563 ArrayList<ApplicationInfo> list; 6564 if (listUninstalled) { 6565 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6566 for (PackageSetting ps : mSettings.mPackages.values()) { 6567 ApplicationInfo ai; 6568 int effectiveFlags = flags; 6569 if (ps.isSystem()) { 6570 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6571 } 6572 if (ps.pkg != null) { 6573 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6574 ps.readUserState(userId), userId); 6575 } else { 6576 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6577 userId); 6578 } 6579 if (ai != null) { 6580 list.add(ai); 6581 } 6582 } 6583 } else { 6584 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6585 for (PackageParser.Package p : mPackages.values()) { 6586 if (p.mExtras != null) { 6587 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6588 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6589 if (ai != null) { 6590 list.add(ai); 6591 } 6592 } 6593 } 6594 } 6595 6596 return new ParceledListSlice<ApplicationInfo>(list); 6597 } 6598 } 6599 6600 @Override 6601 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6602 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6603 return null; 6604 } 6605 6606 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6607 "getEphemeralApplications"); 6608 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6609 true /* requireFullPermission */, false /* checkShell */, 6610 "getEphemeralApplications"); 6611 synchronized (mPackages) { 6612 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6613 .getEphemeralApplicationsLPw(userId); 6614 if (ephemeralApps != null) { 6615 return new ParceledListSlice<>(ephemeralApps); 6616 } 6617 } 6618 return null; 6619 } 6620 6621 @Override 6622 public boolean isEphemeralApplication(String packageName, int userId) { 6623 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6624 true /* requireFullPermission */, false /* checkShell */, 6625 "isEphemeral"); 6626 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6627 return false; 6628 } 6629 6630 if (!isCallerSameApp(packageName)) { 6631 return false; 6632 } 6633 synchronized (mPackages) { 6634 PackageParser.Package pkg = mPackages.get(packageName); 6635 if (pkg != null) { 6636 return pkg.applicationInfo.isEphemeralApp(); 6637 } 6638 } 6639 return false; 6640 } 6641 6642 @Override 6643 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6644 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6645 return null; 6646 } 6647 6648 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6649 true /* requireFullPermission */, false /* checkShell */, 6650 "getCookie"); 6651 if (!isCallerSameApp(packageName)) { 6652 return null; 6653 } 6654 synchronized (mPackages) { 6655 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6656 packageName, userId); 6657 } 6658 } 6659 6660 @Override 6661 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6662 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6663 return true; 6664 } 6665 6666 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6667 true /* requireFullPermission */, true /* checkShell */, 6668 "setCookie"); 6669 if (!isCallerSameApp(packageName)) { 6670 return false; 6671 } 6672 synchronized (mPackages) { 6673 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6674 packageName, cookie, userId); 6675 } 6676 } 6677 6678 @Override 6679 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6680 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6681 return null; 6682 } 6683 6684 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6685 "getEphemeralApplicationIcon"); 6686 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6687 true /* requireFullPermission */, false /* checkShell */, 6688 "getEphemeralApplicationIcon"); 6689 synchronized (mPackages) { 6690 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6691 packageName, userId); 6692 } 6693 } 6694 6695 private boolean isCallerSameApp(String packageName) { 6696 PackageParser.Package pkg = mPackages.get(packageName); 6697 return pkg != null 6698 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6699 } 6700 6701 @Override 6702 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6703 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6704 } 6705 6706 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6707 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6708 6709 // reader 6710 synchronized (mPackages) { 6711 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6712 final int userId = UserHandle.getCallingUserId(); 6713 while (i.hasNext()) { 6714 final PackageParser.Package p = i.next(); 6715 if (p.applicationInfo == null) continue; 6716 6717 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6718 && !p.applicationInfo.isDirectBootAware(); 6719 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6720 && p.applicationInfo.isDirectBootAware(); 6721 6722 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6723 && (!mSafeMode || isSystemApp(p)) 6724 && (matchesUnaware || matchesAware)) { 6725 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6726 if (ps != null) { 6727 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6728 ps.readUserState(userId), userId); 6729 if (ai != null) { 6730 finalList.add(ai); 6731 } 6732 } 6733 } 6734 } 6735 } 6736 6737 return finalList; 6738 } 6739 6740 @Override 6741 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6742 if (!sUserManager.exists(userId)) return null; 6743 flags = updateFlagsForComponent(flags, userId, name); 6744 // reader 6745 synchronized (mPackages) { 6746 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6747 PackageSetting ps = provider != null 6748 ? mSettings.mPackages.get(provider.owner.packageName) 6749 : null; 6750 return ps != null 6751 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6752 ? PackageParser.generateProviderInfo(provider, flags, 6753 ps.readUserState(userId), userId) 6754 : null; 6755 } 6756 } 6757 6758 /** 6759 * @deprecated 6760 */ 6761 @Deprecated 6762 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6763 // reader 6764 synchronized (mPackages) { 6765 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6766 .entrySet().iterator(); 6767 final int userId = UserHandle.getCallingUserId(); 6768 while (i.hasNext()) { 6769 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6770 PackageParser.Provider p = entry.getValue(); 6771 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6772 6773 if (ps != null && p.syncable 6774 && (!mSafeMode || (p.info.applicationInfo.flags 6775 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6776 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6777 ps.readUserState(userId), userId); 6778 if (info != null) { 6779 outNames.add(entry.getKey()); 6780 outInfo.add(info); 6781 } 6782 } 6783 } 6784 } 6785 } 6786 6787 @Override 6788 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6789 int uid, int flags) { 6790 final int userId = processName != null ? UserHandle.getUserId(uid) 6791 : UserHandle.getCallingUserId(); 6792 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6793 flags = updateFlagsForComponent(flags, userId, processName); 6794 6795 ArrayList<ProviderInfo> finalList = null; 6796 // reader 6797 synchronized (mPackages) { 6798 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6799 while (i.hasNext()) { 6800 final PackageParser.Provider p = i.next(); 6801 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6802 if (ps != null && p.info.authority != null 6803 && (processName == null 6804 || (p.info.processName.equals(processName) 6805 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6806 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6807 if (finalList == null) { 6808 finalList = new ArrayList<ProviderInfo>(3); 6809 } 6810 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6811 ps.readUserState(userId), userId); 6812 if (info != null) { 6813 finalList.add(info); 6814 } 6815 } 6816 } 6817 } 6818 6819 if (finalList != null) { 6820 Collections.sort(finalList, mProviderInitOrderSorter); 6821 return new ParceledListSlice<ProviderInfo>(finalList); 6822 } 6823 6824 return ParceledListSlice.emptyList(); 6825 } 6826 6827 @Override 6828 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6829 // reader 6830 synchronized (mPackages) { 6831 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6832 return PackageParser.generateInstrumentationInfo(i, flags); 6833 } 6834 } 6835 6836 @Override 6837 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6838 String targetPackage, int flags) { 6839 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6840 } 6841 6842 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6843 int flags) { 6844 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6845 6846 // reader 6847 synchronized (mPackages) { 6848 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6849 while (i.hasNext()) { 6850 final PackageParser.Instrumentation p = i.next(); 6851 if (targetPackage == null 6852 || targetPackage.equals(p.info.targetPackage)) { 6853 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6854 flags); 6855 if (ii != null) { 6856 finalList.add(ii); 6857 } 6858 } 6859 } 6860 } 6861 6862 return finalList; 6863 } 6864 6865 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6866 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6867 if (overlays == null) { 6868 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6869 return; 6870 } 6871 for (PackageParser.Package opkg : overlays.values()) { 6872 // Not much to do if idmap fails: we already logged the error 6873 // and we certainly don't want to abort installation of pkg simply 6874 // because an overlay didn't fit properly. For these reasons, 6875 // ignore the return value of createIdmapForPackagePairLI. 6876 createIdmapForPackagePairLI(pkg, opkg); 6877 } 6878 } 6879 6880 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6881 PackageParser.Package opkg) { 6882 if (!opkg.mTrustedOverlay) { 6883 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6884 opkg.baseCodePath + ": overlay not trusted"); 6885 return false; 6886 } 6887 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6888 if (overlaySet == null) { 6889 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6890 opkg.baseCodePath + " but target package has no known overlays"); 6891 return false; 6892 } 6893 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6894 // TODO: generate idmap for split APKs 6895 try { 6896 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6897 } catch (InstallerException e) { 6898 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6899 + opkg.baseCodePath); 6900 return false; 6901 } 6902 PackageParser.Package[] overlayArray = 6903 overlaySet.values().toArray(new PackageParser.Package[0]); 6904 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6905 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6906 return p1.mOverlayPriority - p2.mOverlayPriority; 6907 } 6908 }; 6909 Arrays.sort(overlayArray, cmp); 6910 6911 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6912 int i = 0; 6913 for (PackageParser.Package p : overlayArray) { 6914 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6915 } 6916 return true; 6917 } 6918 6919 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6920 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6921 try { 6922 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6923 } finally { 6924 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6925 } 6926 } 6927 6928 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6929 final File[] files = dir.listFiles(); 6930 if (ArrayUtils.isEmpty(files)) { 6931 Log.d(TAG, "No files in app dir " + dir); 6932 return; 6933 } 6934 6935 if (DEBUG_PACKAGE_SCANNING) { 6936 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6937 + " flags=0x" + Integer.toHexString(parseFlags)); 6938 } 6939 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6940 mSeparateProcesses, mOnlyCore, mMetrics); 6941 6942 // Submit files for parsing in parallel 6943 int fileCount = 0; 6944 for (File file : files) { 6945 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6946 && !PackageInstallerService.isStageName(file.getName()); 6947 if (!isPackage) { 6948 // Ignore entries which are not packages 6949 continue; 6950 } 6951 parallelPackageParser.submit(file, parseFlags); 6952 fileCount++; 6953 } 6954 6955 // Process results one by one 6956 for (; fileCount > 0; fileCount--) { 6957 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 6958 Throwable throwable = parseResult.throwable; 6959 int errorCode = PackageManager.INSTALL_SUCCEEDED; 6960 6961 if (throwable == null) { 6962 try { 6963 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 6964 currentTime, null); 6965 } catch (PackageManagerException e) { 6966 errorCode = e.error; 6967 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 6968 } 6969 } else if (throwable instanceof PackageParser.PackageParserException) { 6970 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 6971 throwable; 6972 errorCode = e.error; 6973 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 6974 } else { 6975 throw new IllegalStateException("Unexpected exception occurred while parsing " 6976 + parseResult.scanFile, throwable); 6977 } 6978 6979 // Delete invalid userdata apps 6980 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6981 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 6982 logCriticalInfo(Log.WARN, 6983 "Deleting invalid package at " + parseResult.scanFile); 6984 removeCodePathLI(parseResult.scanFile); 6985 } 6986 } 6987 parallelPackageParser.close(); 6988 } 6989 6990 private static File getSettingsProblemFile() { 6991 File dataDir = Environment.getDataDirectory(); 6992 File systemDir = new File(dataDir, "system"); 6993 File fname = new File(systemDir, "uiderrors.txt"); 6994 return fname; 6995 } 6996 6997 static void reportSettingsProblem(int priority, String msg) { 6998 logCriticalInfo(priority, msg); 6999 } 7000 7001 static void logCriticalInfo(int priority, String msg) { 7002 Slog.println(priority, TAG, msg); 7003 EventLogTags.writePmCriticalInfo(msg); 7004 try { 7005 File fname = getSettingsProblemFile(); 7006 FileOutputStream out = new FileOutputStream(fname, true); 7007 PrintWriter pw = new FastPrintWriter(out); 7008 SimpleDateFormat formatter = new SimpleDateFormat(); 7009 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7010 pw.println(dateString + ": " + msg); 7011 pw.close(); 7012 FileUtils.setPermissions( 7013 fname.toString(), 7014 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7015 -1, -1); 7016 } catch (java.io.IOException e) { 7017 } 7018 } 7019 7020 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7021 if (srcFile.isDirectory()) { 7022 final File baseFile = new File(pkg.baseCodePath); 7023 long maxModifiedTime = baseFile.lastModified(); 7024 if (pkg.splitCodePaths != null) { 7025 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7026 final File splitFile = new File(pkg.splitCodePaths[i]); 7027 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7028 } 7029 } 7030 return maxModifiedTime; 7031 } 7032 return srcFile.lastModified(); 7033 } 7034 7035 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7036 final int policyFlags) throws PackageManagerException { 7037 // When upgrading from pre-N MR1, verify the package time stamp using the package 7038 // directory and not the APK file. 7039 final long lastModifiedTime = mIsPreNMR1Upgrade 7040 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7041 if (ps != null 7042 && ps.codePath.equals(srcFile) 7043 && ps.timeStamp == lastModifiedTime 7044 && !isCompatSignatureUpdateNeeded(pkg) 7045 && !isRecoverSignatureUpdateNeeded(pkg)) { 7046 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7047 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7048 ArraySet<PublicKey> signingKs; 7049 synchronized (mPackages) { 7050 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7051 } 7052 if (ps.signatures.mSignatures != null 7053 && ps.signatures.mSignatures.length != 0 7054 && signingKs != null) { 7055 // Optimization: reuse the existing cached certificates 7056 // if the package appears to be unchanged. 7057 pkg.mSignatures = ps.signatures.mSignatures; 7058 pkg.mSigningKeys = signingKs; 7059 return; 7060 } 7061 7062 Slog.w(TAG, "PackageSetting for " + ps.name 7063 + " is missing signatures. Collecting certs again to recover them."); 7064 } else { 7065 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7066 } 7067 7068 try { 7069 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7070 PackageParser.collectCertificates(pkg, policyFlags); 7071 } catch (PackageParserException e) { 7072 throw PackageManagerException.from(e); 7073 } finally { 7074 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7075 } 7076 } 7077 7078 /** 7079 * Traces a package scan. 7080 * @see #scanPackageLI(File, int, int, long, UserHandle) 7081 */ 7082 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7083 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7084 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7085 try { 7086 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7087 } finally { 7088 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7089 } 7090 } 7091 7092 /** 7093 * Scans a package and returns the newly parsed package. 7094 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7095 */ 7096 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7097 long currentTime, UserHandle user) throws PackageManagerException { 7098 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7099 PackageParser pp = new PackageParser(); 7100 pp.setSeparateProcesses(mSeparateProcesses); 7101 pp.setOnlyCoreApps(mOnlyCore); 7102 pp.setDisplayMetrics(mMetrics); 7103 7104 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7105 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7106 } 7107 7108 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7109 final PackageParser.Package pkg; 7110 try { 7111 pkg = pp.parsePackage(scanFile, parseFlags); 7112 } catch (PackageParserException e) { 7113 throw PackageManagerException.from(e); 7114 } finally { 7115 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7116 } 7117 7118 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7119 } 7120 7121 /** 7122 * Scans a package and returns the newly parsed package. 7123 * @throws PackageManagerException on a parse error. 7124 */ 7125 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7126 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7127 throws PackageManagerException { 7128 // If the package has children and this is the first dive in the function 7129 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7130 // packages (parent and children) would be successfully scanned before the 7131 // actual scan since scanning mutates internal state and we want to atomically 7132 // install the package and its children. 7133 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7134 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7135 scanFlags |= SCAN_CHECK_ONLY; 7136 } 7137 } else { 7138 scanFlags &= ~SCAN_CHECK_ONLY; 7139 } 7140 7141 // Scan the parent 7142 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7143 scanFlags, currentTime, user); 7144 7145 // Scan the children 7146 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7147 for (int i = 0; i < childCount; i++) { 7148 PackageParser.Package childPackage = pkg.childPackages.get(i); 7149 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7150 currentTime, user); 7151 } 7152 7153 7154 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7155 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7156 } 7157 7158 return scannedPkg; 7159 } 7160 7161 /** 7162 * Scans a package and returns the newly parsed package. 7163 * @throws PackageManagerException on a parse error. 7164 */ 7165 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7166 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7167 throws PackageManagerException { 7168 PackageSetting ps = null; 7169 PackageSetting updatedPkg; 7170 // reader 7171 synchronized (mPackages) { 7172 // Look to see if we already know about this package. 7173 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7174 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7175 // This package has been renamed to its original name. Let's 7176 // use that. 7177 ps = mSettings.getPackageLPr(oldName); 7178 } 7179 // If there was no original package, see one for the real package name. 7180 if (ps == null) { 7181 ps = mSettings.getPackageLPr(pkg.packageName); 7182 } 7183 // Check to see if this package could be hiding/updating a system 7184 // package. Must look for it either under the original or real 7185 // package name depending on our state. 7186 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7187 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7188 7189 // If this is a package we don't know about on the system partition, we 7190 // may need to remove disabled child packages on the system partition 7191 // or may need to not add child packages if the parent apk is updated 7192 // on the data partition and no longer defines this child package. 7193 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7194 // If this is a parent package for an updated system app and this system 7195 // app got an OTA update which no longer defines some of the child packages 7196 // we have to prune them from the disabled system packages. 7197 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7198 if (disabledPs != null) { 7199 final int scannedChildCount = (pkg.childPackages != null) 7200 ? pkg.childPackages.size() : 0; 7201 final int disabledChildCount = disabledPs.childPackageNames != null 7202 ? disabledPs.childPackageNames.size() : 0; 7203 for (int i = 0; i < disabledChildCount; i++) { 7204 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7205 boolean disabledPackageAvailable = false; 7206 for (int j = 0; j < scannedChildCount; j++) { 7207 PackageParser.Package childPkg = pkg.childPackages.get(j); 7208 if (childPkg.packageName.equals(disabledChildPackageName)) { 7209 disabledPackageAvailable = true; 7210 break; 7211 } 7212 } 7213 if (!disabledPackageAvailable) { 7214 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7215 } 7216 } 7217 } 7218 } 7219 } 7220 7221 boolean updatedPkgBetter = false; 7222 // First check if this is a system package that may involve an update 7223 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7224 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7225 // it needs to drop FLAG_PRIVILEGED. 7226 if (locationIsPrivileged(scanFile)) { 7227 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7228 } else { 7229 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7230 } 7231 7232 if (ps != null && !ps.codePath.equals(scanFile)) { 7233 // The path has changed from what was last scanned... check the 7234 // version of the new path against what we have stored to determine 7235 // what to do. 7236 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7237 if (pkg.mVersionCode <= ps.versionCode) { 7238 // The system package has been updated and the code path does not match 7239 // Ignore entry. Skip it. 7240 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7241 + " ignored: updated version " + ps.versionCode 7242 + " better than this " + pkg.mVersionCode); 7243 if (!updatedPkg.codePath.equals(scanFile)) { 7244 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7245 + ps.name + " changing from " + updatedPkg.codePathString 7246 + " to " + scanFile); 7247 updatedPkg.codePath = scanFile; 7248 updatedPkg.codePathString = scanFile.toString(); 7249 updatedPkg.resourcePath = scanFile; 7250 updatedPkg.resourcePathString = scanFile.toString(); 7251 } 7252 updatedPkg.pkg = pkg; 7253 updatedPkg.versionCode = pkg.mVersionCode; 7254 7255 // Update the disabled system child packages to point to the package too. 7256 final int childCount = updatedPkg.childPackageNames != null 7257 ? updatedPkg.childPackageNames.size() : 0; 7258 for (int i = 0; i < childCount; i++) { 7259 String childPackageName = updatedPkg.childPackageNames.get(i); 7260 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7261 childPackageName); 7262 if (updatedChildPkg != null) { 7263 updatedChildPkg.pkg = pkg; 7264 updatedChildPkg.versionCode = pkg.mVersionCode; 7265 } 7266 } 7267 7268 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7269 + scanFile + " ignored: updated version " + ps.versionCode 7270 + " better than this " + pkg.mVersionCode); 7271 } else { 7272 // The current app on the system partition is better than 7273 // what we have updated to on the data partition; switch 7274 // back to the system partition version. 7275 // At this point, its safely assumed that package installation for 7276 // apps in system partition will go through. If not there won't be a working 7277 // version of the app 7278 // writer 7279 synchronized (mPackages) { 7280 // Just remove the loaded entries from package lists. 7281 mPackages.remove(ps.name); 7282 } 7283 7284 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7285 + " reverting from " + ps.codePathString 7286 + ": new version " + pkg.mVersionCode 7287 + " better than installed " + ps.versionCode); 7288 7289 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7290 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7291 synchronized (mInstallLock) { 7292 args.cleanUpResourcesLI(); 7293 } 7294 synchronized (mPackages) { 7295 mSettings.enableSystemPackageLPw(ps.name); 7296 } 7297 updatedPkgBetter = true; 7298 } 7299 } 7300 } 7301 7302 if (updatedPkg != null) { 7303 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7304 // initially 7305 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7306 7307 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7308 // flag set initially 7309 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7310 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7311 } 7312 } 7313 7314 // Verify certificates against what was last scanned 7315 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7316 7317 /* 7318 * A new system app appeared, but we already had a non-system one of the 7319 * same name installed earlier. 7320 */ 7321 boolean shouldHideSystemApp = false; 7322 if (updatedPkg == null && ps != null 7323 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7324 /* 7325 * Check to make sure the signatures match first. If they don't, 7326 * wipe the installed application and its data. 7327 */ 7328 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7329 != PackageManager.SIGNATURE_MATCH) { 7330 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7331 + " signatures don't match existing userdata copy; removing"); 7332 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7333 "scanPackageInternalLI")) { 7334 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7335 } 7336 ps = null; 7337 } else { 7338 /* 7339 * If the newly-added system app is an older version than the 7340 * already installed version, hide it. It will be scanned later 7341 * and re-added like an update. 7342 */ 7343 if (pkg.mVersionCode <= ps.versionCode) { 7344 shouldHideSystemApp = true; 7345 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7346 + " but new version " + pkg.mVersionCode + " better than installed " 7347 + ps.versionCode + "; hiding system"); 7348 } else { 7349 /* 7350 * The newly found system app is a newer version that the 7351 * one previously installed. Simply remove the 7352 * already-installed application and replace it with our own 7353 * while keeping the application data. 7354 */ 7355 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7356 + " reverting from " + ps.codePathString + ": new version " 7357 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7358 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7359 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7360 synchronized (mInstallLock) { 7361 args.cleanUpResourcesLI(); 7362 } 7363 } 7364 } 7365 } 7366 7367 // The apk is forward locked (not public) if its code and resources 7368 // are kept in different files. (except for app in either system or 7369 // vendor path). 7370 // TODO grab this value from PackageSettings 7371 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7372 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7373 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7374 } 7375 } 7376 7377 // TODO: extend to support forward-locked splits 7378 String resourcePath = null; 7379 String baseResourcePath = null; 7380 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7381 if (ps != null && ps.resourcePathString != null) { 7382 resourcePath = ps.resourcePathString; 7383 baseResourcePath = ps.resourcePathString; 7384 } else { 7385 // Should not happen at all. Just log an error. 7386 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7387 } 7388 } else { 7389 resourcePath = pkg.codePath; 7390 baseResourcePath = pkg.baseCodePath; 7391 } 7392 7393 // Set application objects path explicitly. 7394 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7395 pkg.setApplicationInfoCodePath(pkg.codePath); 7396 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7397 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7398 pkg.setApplicationInfoResourcePath(resourcePath); 7399 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7400 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7401 7402 // Note that we invoke the following method only if we are about to unpack an application 7403 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7404 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7405 7406 /* 7407 * If the system app should be overridden by a previously installed 7408 * data, hide the system app now and let the /data/app scan pick it up 7409 * again. 7410 */ 7411 if (shouldHideSystemApp) { 7412 synchronized (mPackages) { 7413 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7414 } 7415 } 7416 7417 return scannedPkg; 7418 } 7419 7420 private static String fixProcessName(String defProcessName, 7421 String processName) { 7422 if (processName == null) { 7423 return defProcessName; 7424 } 7425 return processName; 7426 } 7427 7428 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7429 throws PackageManagerException { 7430 if (pkgSetting.signatures.mSignatures != null) { 7431 // Already existing package. Make sure signatures match 7432 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7433 == PackageManager.SIGNATURE_MATCH; 7434 if (!match) { 7435 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7436 == PackageManager.SIGNATURE_MATCH; 7437 } 7438 if (!match) { 7439 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7440 == PackageManager.SIGNATURE_MATCH; 7441 } 7442 if (!match) { 7443 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7444 + pkg.packageName + " signatures do not match the " 7445 + "previously installed version; ignoring!"); 7446 } 7447 } 7448 7449 // Check for shared user signatures 7450 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7451 // Already existing package. Make sure signatures match 7452 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7453 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7454 if (!match) { 7455 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7456 == PackageManager.SIGNATURE_MATCH; 7457 } 7458 if (!match) { 7459 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7460 == PackageManager.SIGNATURE_MATCH; 7461 } 7462 if (!match) { 7463 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7464 "Package " + pkg.packageName 7465 + " has no signatures that match those in shared user " 7466 + pkgSetting.sharedUser.name + "; ignoring!"); 7467 } 7468 } 7469 } 7470 7471 /** 7472 * Enforces that only the system UID or root's UID can call a method exposed 7473 * via Binder. 7474 * 7475 * @param message used as message if SecurityException is thrown 7476 * @throws SecurityException if the caller is not system or root 7477 */ 7478 private static final void enforceSystemOrRoot(String message) { 7479 final int uid = Binder.getCallingUid(); 7480 if (uid != Process.SYSTEM_UID && uid != 0) { 7481 throw new SecurityException(message); 7482 } 7483 } 7484 7485 @Override 7486 public void performFstrimIfNeeded() { 7487 enforceSystemOrRoot("Only the system can request fstrim"); 7488 7489 // Before everything else, see whether we need to fstrim. 7490 try { 7491 IStorageManager sm = PackageHelper.getStorageManager(); 7492 if (sm != null) { 7493 boolean doTrim = false; 7494 final long interval = android.provider.Settings.Global.getLong( 7495 mContext.getContentResolver(), 7496 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7497 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7498 if (interval > 0) { 7499 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7500 if (timeSinceLast > interval) { 7501 doTrim = true; 7502 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7503 + "; running immediately"); 7504 } 7505 } 7506 if (doTrim) { 7507 final boolean dexOptDialogShown; 7508 synchronized (mPackages) { 7509 dexOptDialogShown = mDexOptDialogShown; 7510 } 7511 if (!isFirstBoot() && dexOptDialogShown) { 7512 try { 7513 ActivityManager.getService().showBootMessage( 7514 mContext.getResources().getString( 7515 R.string.android_upgrading_fstrim), true); 7516 } catch (RemoteException e) { 7517 } 7518 } 7519 sm.runMaintenance(); 7520 } 7521 } else { 7522 Slog.e(TAG, "storageManager service unavailable!"); 7523 } 7524 } catch (RemoteException e) { 7525 // Can't happen; StorageManagerService is local 7526 } 7527 } 7528 7529 @Override 7530 public void updatePackagesIfNeeded() { 7531 enforceSystemOrRoot("Only the system can request package update"); 7532 7533 // We need to re-extract after an OTA. 7534 boolean causeUpgrade = isUpgrade(); 7535 7536 // First boot or factory reset. 7537 // Note: we also handle devices that are upgrading to N right now as if it is their 7538 // first boot, as they do not have profile data. 7539 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7540 7541 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7542 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7543 7544 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7545 return; 7546 } 7547 7548 List<PackageParser.Package> pkgs; 7549 synchronized (mPackages) { 7550 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7551 } 7552 7553 final long startTime = System.nanoTime(); 7554 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7555 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7556 7557 final int elapsedTimeSeconds = 7558 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7559 7560 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7561 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7562 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7563 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7564 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7565 } 7566 7567 /** 7568 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7569 * containing statistics about the invocation. The array consists of three elements, 7570 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7571 * and {@code numberOfPackagesFailed}. 7572 */ 7573 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7574 String compilerFilter) { 7575 7576 int numberOfPackagesVisited = 0; 7577 int numberOfPackagesOptimized = 0; 7578 int numberOfPackagesSkipped = 0; 7579 int numberOfPackagesFailed = 0; 7580 final int numberOfPackagesToDexopt = pkgs.size(); 7581 7582 for (PackageParser.Package pkg : pkgs) { 7583 numberOfPackagesVisited++; 7584 7585 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7586 if (DEBUG_DEXOPT) { 7587 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7588 } 7589 numberOfPackagesSkipped++; 7590 continue; 7591 } 7592 7593 if (DEBUG_DEXOPT) { 7594 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7595 numberOfPackagesToDexopt + ": " + pkg.packageName); 7596 } 7597 7598 if (showDialog) { 7599 try { 7600 ActivityManager.getService().showBootMessage( 7601 mContext.getResources().getString(R.string.android_upgrading_apk, 7602 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7603 } catch (RemoteException e) { 7604 } 7605 synchronized (mPackages) { 7606 mDexOptDialogShown = true; 7607 } 7608 } 7609 7610 // If the OTA updates a system app which was previously preopted to a non-preopted state 7611 // the app might end up being verified at runtime. That's because by default the apps 7612 // are verify-profile but for preopted apps there's no profile. 7613 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7614 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7615 // filter (by default interpret-only). 7616 // Note that at this stage unused apps are already filtered. 7617 if (isSystemApp(pkg) && 7618 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7619 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7620 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7621 } 7622 7623 // checkProfiles is false to avoid merging profiles during boot which 7624 // might interfere with background compilation (b/28612421). 7625 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7626 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7627 // trade-off worth doing to save boot time work. 7628 int dexOptStatus = performDexOptTraced(pkg.packageName, 7629 false /* checkProfiles */, 7630 compilerFilter, 7631 false /* force */); 7632 switch (dexOptStatus) { 7633 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7634 numberOfPackagesOptimized++; 7635 break; 7636 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7637 numberOfPackagesSkipped++; 7638 break; 7639 case PackageDexOptimizer.DEX_OPT_FAILED: 7640 numberOfPackagesFailed++; 7641 break; 7642 default: 7643 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7644 break; 7645 } 7646 } 7647 7648 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7649 numberOfPackagesFailed }; 7650 } 7651 7652 @Override 7653 public void notifyPackageUse(String packageName, int reason) { 7654 synchronized (mPackages) { 7655 PackageParser.Package p = mPackages.get(packageName); 7656 if (p == null) { 7657 return; 7658 } 7659 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7660 } 7661 } 7662 7663 @Override 7664 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7665 int userId = UserHandle.getCallingUserId(); 7666 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7667 if (ai == null) { 7668 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7669 + loadingPackageName + ", user=" + userId); 7670 return; 7671 } 7672 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7673 } 7674 7675 // TODO: this is not used nor needed. Delete it. 7676 @Override 7677 public boolean performDexOptIfNeeded(String packageName) { 7678 int dexOptStatus = performDexOptTraced(packageName, 7679 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7680 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7681 } 7682 7683 @Override 7684 public boolean performDexOpt(String packageName, 7685 boolean checkProfiles, int compileReason, boolean force) { 7686 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7687 getCompilerFilterForReason(compileReason), force); 7688 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7689 } 7690 7691 @Override 7692 public boolean performDexOptMode(String packageName, 7693 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7694 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7695 targetCompilerFilter, force); 7696 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7697 } 7698 7699 private int performDexOptTraced(String packageName, 7700 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7701 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7702 try { 7703 return performDexOptInternal(packageName, checkProfiles, 7704 targetCompilerFilter, force); 7705 } finally { 7706 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7707 } 7708 } 7709 7710 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7711 // if the package can now be considered up to date for the given filter. 7712 private int performDexOptInternal(String packageName, 7713 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7714 PackageParser.Package p; 7715 synchronized (mPackages) { 7716 p = mPackages.get(packageName); 7717 if (p == null) { 7718 // Package could not be found. Report failure. 7719 return PackageDexOptimizer.DEX_OPT_FAILED; 7720 } 7721 mPackageUsage.maybeWriteAsync(mPackages); 7722 mCompilerStats.maybeWriteAsync(); 7723 } 7724 long callingId = Binder.clearCallingIdentity(); 7725 try { 7726 synchronized (mInstallLock) { 7727 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7728 targetCompilerFilter, force); 7729 } 7730 } finally { 7731 Binder.restoreCallingIdentity(callingId); 7732 } 7733 } 7734 7735 public ArraySet<String> getOptimizablePackages() { 7736 ArraySet<String> pkgs = new ArraySet<String>(); 7737 synchronized (mPackages) { 7738 for (PackageParser.Package p : mPackages.values()) { 7739 if (PackageDexOptimizer.canOptimizePackage(p)) { 7740 pkgs.add(p.packageName); 7741 } 7742 } 7743 } 7744 return pkgs; 7745 } 7746 7747 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7748 boolean checkProfiles, String targetCompilerFilter, 7749 boolean force) { 7750 // Select the dex optimizer based on the force parameter. 7751 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7752 // allocate an object here. 7753 PackageDexOptimizer pdo = force 7754 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7755 : mPackageDexOptimizer; 7756 7757 // Optimize all dependencies first. Note: we ignore the return value and march on 7758 // on errors. 7759 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7760 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7761 if (!deps.isEmpty()) { 7762 for (PackageParser.Package depPackage : deps) { 7763 // TODO: Analyze and investigate if we (should) profile libraries. 7764 // Currently this will do a full compilation of the library by default. 7765 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7766 false /* checkProfiles */, 7767 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7768 getOrCreateCompilerPackageStats(depPackage)); 7769 } 7770 } 7771 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7772 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7773 } 7774 7775 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7776 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7777 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7778 Set<String> collectedNames = new HashSet<>(); 7779 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7780 7781 retValue.remove(p); 7782 7783 return retValue; 7784 } else { 7785 return Collections.emptyList(); 7786 } 7787 } 7788 7789 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7790 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7791 if (!collectedNames.contains(p.packageName)) { 7792 collectedNames.add(p.packageName); 7793 collected.add(p); 7794 7795 if (p.usesLibraries != null) { 7796 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7797 } 7798 if (p.usesOptionalLibraries != null) { 7799 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7800 collectedNames); 7801 } 7802 } 7803 } 7804 7805 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7806 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7807 for (String libName : libs) { 7808 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7809 if (libPkg != null) { 7810 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7811 } 7812 } 7813 } 7814 7815 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7816 synchronized (mPackages) { 7817 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7818 if (lib != null && lib.apk != null) { 7819 return mPackages.get(lib.apk); 7820 } 7821 } 7822 return null; 7823 } 7824 7825 public void shutdown() { 7826 mPackageUsage.writeNow(mPackages); 7827 mCompilerStats.writeNow(); 7828 } 7829 7830 @Override 7831 public void dumpProfiles(String packageName) { 7832 PackageParser.Package pkg; 7833 synchronized (mPackages) { 7834 pkg = mPackages.get(packageName); 7835 if (pkg == null) { 7836 throw new IllegalArgumentException("Unknown package: " + packageName); 7837 } 7838 } 7839 /* Only the shell, root, or the app user should be able to dump profiles. */ 7840 int callingUid = Binder.getCallingUid(); 7841 if (callingUid != Process.SHELL_UID && 7842 callingUid != Process.ROOT_UID && 7843 callingUid != pkg.applicationInfo.uid) { 7844 throw new SecurityException("dumpProfiles"); 7845 } 7846 7847 synchronized (mInstallLock) { 7848 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7849 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7850 try { 7851 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7852 String codePaths = TextUtils.join(";", allCodePaths); 7853 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7854 } catch (InstallerException e) { 7855 Slog.w(TAG, "Failed to dump profiles", e); 7856 } 7857 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7858 } 7859 } 7860 7861 @Override 7862 public void forceDexOpt(String packageName) { 7863 enforceSystemOrRoot("forceDexOpt"); 7864 7865 PackageParser.Package pkg; 7866 synchronized (mPackages) { 7867 pkg = mPackages.get(packageName); 7868 if (pkg == null) { 7869 throw new IllegalArgumentException("Unknown package: " + packageName); 7870 } 7871 } 7872 7873 synchronized (mInstallLock) { 7874 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7875 7876 // Whoever is calling forceDexOpt wants a fully compiled package. 7877 // Don't use profiles since that may cause compilation to be skipped. 7878 final int res = performDexOptInternalWithDependenciesLI(pkg, 7879 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7880 true /* force */); 7881 7882 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7883 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7884 throw new IllegalStateException("Failed to dexopt: " + res); 7885 } 7886 } 7887 } 7888 7889 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7890 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7891 Slog.w(TAG, "Unable to update from " + oldPkg.name 7892 + " to " + newPkg.packageName 7893 + ": old package not in system partition"); 7894 return false; 7895 } else if (mPackages.get(oldPkg.name) != null) { 7896 Slog.w(TAG, "Unable to update from " + oldPkg.name 7897 + " to " + newPkg.packageName 7898 + ": old package still exists"); 7899 return false; 7900 } 7901 return true; 7902 } 7903 7904 void removeCodePathLI(File codePath) { 7905 if (codePath.isDirectory()) { 7906 try { 7907 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7908 } catch (InstallerException e) { 7909 Slog.w(TAG, "Failed to remove code path", e); 7910 } 7911 } else { 7912 codePath.delete(); 7913 } 7914 } 7915 7916 private int[] resolveUserIds(int userId) { 7917 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7918 } 7919 7920 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7921 if (pkg == null) { 7922 Slog.wtf(TAG, "Package was null!", new Throwable()); 7923 return; 7924 } 7925 clearAppDataLeafLIF(pkg, userId, flags); 7926 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7927 for (int i = 0; i < childCount; i++) { 7928 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7929 } 7930 } 7931 7932 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7933 final PackageSetting ps; 7934 synchronized (mPackages) { 7935 ps = mSettings.mPackages.get(pkg.packageName); 7936 } 7937 for (int realUserId : resolveUserIds(userId)) { 7938 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7939 try { 7940 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7941 ceDataInode); 7942 } catch (InstallerException e) { 7943 Slog.w(TAG, String.valueOf(e)); 7944 } 7945 } 7946 } 7947 7948 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7949 if (pkg == null) { 7950 Slog.wtf(TAG, "Package was null!", new Throwable()); 7951 return; 7952 } 7953 destroyAppDataLeafLIF(pkg, userId, flags); 7954 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7955 for (int i = 0; i < childCount; i++) { 7956 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7957 } 7958 } 7959 7960 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7961 final PackageSetting ps; 7962 synchronized (mPackages) { 7963 ps = mSettings.mPackages.get(pkg.packageName); 7964 } 7965 for (int realUserId : resolveUserIds(userId)) { 7966 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7967 try { 7968 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7969 ceDataInode); 7970 } catch (InstallerException e) { 7971 Slog.w(TAG, String.valueOf(e)); 7972 } 7973 } 7974 } 7975 7976 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7977 if (pkg == null) { 7978 Slog.wtf(TAG, "Package was null!", new Throwable()); 7979 return; 7980 } 7981 destroyAppProfilesLeafLIF(pkg); 7982 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7983 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7984 for (int i = 0; i < childCount; i++) { 7985 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7986 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7987 true /* removeBaseMarker */); 7988 } 7989 } 7990 7991 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7992 boolean removeBaseMarker) { 7993 if (pkg.isForwardLocked()) { 7994 return; 7995 } 7996 7997 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7998 try { 7999 path = PackageManagerServiceUtils.realpath(new File(path)); 8000 } catch (IOException e) { 8001 // TODO: Should we return early here ? 8002 Slog.w(TAG, "Failed to get canonical path", e); 8003 continue; 8004 } 8005 8006 final String useMarker = path.replace('/', '@'); 8007 for (int realUserId : resolveUserIds(userId)) { 8008 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8009 if (removeBaseMarker) { 8010 File foreignUseMark = new File(profileDir, useMarker); 8011 if (foreignUseMark.exists()) { 8012 if (!foreignUseMark.delete()) { 8013 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8014 + pkg.packageName); 8015 } 8016 } 8017 } 8018 8019 File[] markers = profileDir.listFiles(); 8020 if (markers != null) { 8021 final String searchString = "@" + pkg.packageName + "@"; 8022 // We also delete all markers that contain the package name we're 8023 // uninstalling. These are associated with secondary dex-files belonging 8024 // to the package. Reconstructing the path of these dex files is messy 8025 // in general. 8026 for (File marker : markers) { 8027 if (marker.getName().indexOf(searchString) > 0) { 8028 if (!marker.delete()) { 8029 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8030 + pkg.packageName); 8031 } 8032 } 8033 } 8034 } 8035 } 8036 } 8037 } 8038 8039 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8040 try { 8041 mInstaller.destroyAppProfiles(pkg.packageName); 8042 } catch (InstallerException e) { 8043 Slog.w(TAG, String.valueOf(e)); 8044 } 8045 } 8046 8047 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8048 if (pkg == null) { 8049 Slog.wtf(TAG, "Package was null!", new Throwable()); 8050 return; 8051 } 8052 clearAppProfilesLeafLIF(pkg); 8053 // We don't remove the base foreign use marker when clearing profiles because 8054 // we will rename it when the app is updated. Unlike the actual profile contents, 8055 // the foreign use marker is good across installs. 8056 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8057 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8058 for (int i = 0; i < childCount; i++) { 8059 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8060 } 8061 } 8062 8063 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8064 try { 8065 mInstaller.clearAppProfiles(pkg.packageName); 8066 } catch (InstallerException e) { 8067 Slog.w(TAG, String.valueOf(e)); 8068 } 8069 } 8070 8071 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8072 long lastUpdateTime) { 8073 // Set parent install/update time 8074 PackageSetting ps = (PackageSetting) pkg.mExtras; 8075 if (ps != null) { 8076 ps.firstInstallTime = firstInstallTime; 8077 ps.lastUpdateTime = lastUpdateTime; 8078 } 8079 // Set children install/update time 8080 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8081 for (int i = 0; i < childCount; i++) { 8082 PackageParser.Package childPkg = pkg.childPackages.get(i); 8083 ps = (PackageSetting) childPkg.mExtras; 8084 if (ps != null) { 8085 ps.firstInstallTime = firstInstallTime; 8086 ps.lastUpdateTime = lastUpdateTime; 8087 } 8088 } 8089 } 8090 8091 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8092 PackageParser.Package changingLib) { 8093 if (file.path != null) { 8094 usesLibraryFiles.add(file.path); 8095 return; 8096 } 8097 PackageParser.Package p = mPackages.get(file.apk); 8098 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8099 // If we are doing this while in the middle of updating a library apk, 8100 // then we need to make sure to use that new apk for determining the 8101 // dependencies here. (We haven't yet finished committing the new apk 8102 // to the package manager state.) 8103 if (p == null || p.packageName.equals(changingLib.packageName)) { 8104 p = changingLib; 8105 } 8106 } 8107 if (p != null) { 8108 usesLibraryFiles.addAll(p.getAllCodePaths()); 8109 } 8110 } 8111 8112 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8113 PackageParser.Package changingLib) throws PackageManagerException { 8114 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8115 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8116 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8117 for (int i=0; i<N; i++) { 8118 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8119 if (file == null) { 8120 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8121 "Package " + pkg.packageName + " requires unavailable shared library " 8122 + pkg.usesLibraries.get(i) + "; failing!"); 8123 } 8124 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8125 } 8126 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8127 for (int i=0; i<N; i++) { 8128 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8129 if (file == null) { 8130 Slog.w(TAG, "Package " + pkg.packageName 8131 + " desires unavailable shared library " 8132 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8133 } else { 8134 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8135 } 8136 } 8137 N = usesLibraryFiles.size(); 8138 if (N > 0) { 8139 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8140 } else { 8141 pkg.usesLibraryFiles = null; 8142 } 8143 } 8144 } 8145 8146 private static boolean hasString(List<String> list, List<String> which) { 8147 if (list == null) { 8148 return false; 8149 } 8150 for (int i=list.size()-1; i>=0; i--) { 8151 for (int j=which.size()-1; j>=0; j--) { 8152 if (which.get(j).equals(list.get(i))) { 8153 return true; 8154 } 8155 } 8156 } 8157 return false; 8158 } 8159 8160 private void updateAllSharedLibrariesLPw() { 8161 for (PackageParser.Package pkg : mPackages.values()) { 8162 try { 8163 updateSharedLibrariesLPr(pkg, null); 8164 } catch (PackageManagerException e) { 8165 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8166 } 8167 } 8168 } 8169 8170 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8171 PackageParser.Package changingPkg) { 8172 ArrayList<PackageParser.Package> res = null; 8173 for (PackageParser.Package pkg : mPackages.values()) { 8174 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8175 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8176 if (res == null) { 8177 res = new ArrayList<PackageParser.Package>(); 8178 } 8179 res.add(pkg); 8180 try { 8181 updateSharedLibrariesLPr(pkg, changingPkg); 8182 } catch (PackageManagerException e) { 8183 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8184 } 8185 } 8186 } 8187 return res; 8188 } 8189 8190 /** 8191 * Derive the value of the {@code cpuAbiOverride} based on the provided 8192 * value and an optional stored value from the package settings. 8193 */ 8194 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8195 String cpuAbiOverride = null; 8196 8197 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8198 cpuAbiOverride = null; 8199 } else if (abiOverride != null) { 8200 cpuAbiOverride = abiOverride; 8201 } else if (settings != null) { 8202 cpuAbiOverride = settings.cpuAbiOverrideString; 8203 } 8204 8205 return cpuAbiOverride; 8206 } 8207 8208 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8209 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8210 throws PackageManagerException { 8211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8212 // If the package has children and this is the first dive in the function 8213 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8214 // whether all packages (parent and children) would be successfully scanned 8215 // before the actual scan since scanning mutates internal state and we want 8216 // to atomically install the package and its children. 8217 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8218 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8219 scanFlags |= SCAN_CHECK_ONLY; 8220 } 8221 } else { 8222 scanFlags &= ~SCAN_CHECK_ONLY; 8223 } 8224 8225 final PackageParser.Package scannedPkg; 8226 try { 8227 // Scan the parent 8228 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8229 // Scan the children 8230 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8231 for (int i = 0; i < childCount; i++) { 8232 PackageParser.Package childPkg = pkg.childPackages.get(i); 8233 scanPackageLI(childPkg, policyFlags, 8234 scanFlags, currentTime, user); 8235 } 8236 } finally { 8237 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8238 } 8239 8240 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8241 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8242 } 8243 8244 return scannedPkg; 8245 } 8246 8247 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8248 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8249 boolean success = false; 8250 try { 8251 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8252 currentTime, user); 8253 success = true; 8254 return res; 8255 } finally { 8256 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8257 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8258 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8259 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8260 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8261 } 8262 } 8263 } 8264 8265 /** 8266 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8267 */ 8268 private static boolean apkHasCode(String fileName) { 8269 StrictJarFile jarFile = null; 8270 try { 8271 jarFile = new StrictJarFile(fileName, 8272 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8273 return jarFile.findEntry("classes.dex") != null; 8274 } catch (IOException ignore) { 8275 } finally { 8276 try { 8277 if (jarFile != null) { 8278 jarFile.close(); 8279 } 8280 } catch (IOException ignore) {} 8281 } 8282 return false; 8283 } 8284 8285 /** 8286 * Enforces code policy for the package. This ensures that if an APK has 8287 * declared hasCode="true" in its manifest that the APK actually contains 8288 * code. 8289 * 8290 * @throws PackageManagerException If bytecode could not be found when it should exist 8291 */ 8292 private static void assertCodePolicy(PackageParser.Package pkg) 8293 throws PackageManagerException { 8294 final boolean shouldHaveCode = 8295 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8296 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8297 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8298 "Package " + pkg.baseCodePath + " code is missing"); 8299 } 8300 8301 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8302 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8303 final boolean splitShouldHaveCode = 8304 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8305 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8306 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8307 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8308 } 8309 } 8310 } 8311 } 8312 8313 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8314 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8315 throws PackageManagerException { 8316 if (DEBUG_PACKAGE_SCANNING) { 8317 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8318 Log.d(TAG, "Scanning package " + pkg.packageName); 8319 } 8320 8321 applyPolicy(pkg, policyFlags); 8322 8323 assertPackageIsValid(pkg, policyFlags, scanFlags); 8324 8325 // Initialize package source and resource directories 8326 final File scanFile = new File(pkg.codePath); 8327 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8328 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8329 8330 SharedUserSetting suid = null; 8331 PackageSetting pkgSetting = null; 8332 8333 // Getting the package setting may have a side-effect, so if we 8334 // are only checking if scan would succeed, stash a copy of the 8335 // old setting to restore at the end. 8336 PackageSetting nonMutatedPs = null; 8337 8338 // We keep references to the derived CPU Abis from settings in oder to reuse 8339 // them in the case where we're not upgrading or booting for the first time. 8340 String primaryCpuAbiFromSettings = null; 8341 String secondaryCpuAbiFromSettings = null; 8342 8343 // writer 8344 synchronized (mPackages) { 8345 if (pkg.mSharedUserId != null) { 8346 // SIDE EFFECTS; may potentially allocate a new shared user 8347 suid = mSettings.getSharedUserLPw( 8348 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8349 if (DEBUG_PACKAGE_SCANNING) { 8350 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8351 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8352 + "): packages=" + suid.packages); 8353 } 8354 } 8355 8356 // Check if we are renaming from an original package name. 8357 PackageSetting origPackage = null; 8358 String realName = null; 8359 if (pkg.mOriginalPackages != null) { 8360 // This package may need to be renamed to a previously 8361 // installed name. Let's check on that... 8362 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8363 if (pkg.mOriginalPackages.contains(renamed)) { 8364 // This package had originally been installed as the 8365 // original name, and we have already taken care of 8366 // transitioning to the new one. Just update the new 8367 // one to continue using the old name. 8368 realName = pkg.mRealPackage; 8369 if (!pkg.packageName.equals(renamed)) { 8370 // Callers into this function may have already taken 8371 // care of renaming the package; only do it here if 8372 // it is not already done. 8373 pkg.setPackageName(renamed); 8374 } 8375 } else { 8376 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8377 if ((origPackage = mSettings.getPackageLPr( 8378 pkg.mOriginalPackages.get(i))) != null) { 8379 // We do have the package already installed under its 8380 // original name... should we use it? 8381 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8382 // New package is not compatible with original. 8383 origPackage = null; 8384 continue; 8385 } else if (origPackage.sharedUser != null) { 8386 // Make sure uid is compatible between packages. 8387 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8388 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8389 + " to " + pkg.packageName + ": old uid " 8390 + origPackage.sharedUser.name 8391 + " differs from " + pkg.mSharedUserId); 8392 origPackage = null; 8393 continue; 8394 } 8395 // TODO: Add case when shared user id is added [b/28144775] 8396 } else { 8397 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8398 + pkg.packageName + " to old name " + origPackage.name); 8399 } 8400 break; 8401 } 8402 } 8403 } 8404 } 8405 8406 if (mTransferedPackages.contains(pkg.packageName)) { 8407 Slog.w(TAG, "Package " + pkg.packageName 8408 + " was transferred to another, but its .apk remains"); 8409 } 8410 8411 // See comments in nonMutatedPs declaration 8412 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8413 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8414 if (foundPs != null) { 8415 nonMutatedPs = new PackageSetting(foundPs); 8416 } 8417 } 8418 8419 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8420 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8421 if (foundPs != null) { 8422 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8423 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8424 } 8425 } 8426 8427 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8428 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8429 PackageManagerService.reportSettingsProblem(Log.WARN, 8430 "Package " + pkg.packageName + " shared user changed from " 8431 + (pkgSetting.sharedUser != null 8432 ? pkgSetting.sharedUser.name : "<nothing>") 8433 + " to " 8434 + (suid != null ? suid.name : "<nothing>") 8435 + "; replacing with new"); 8436 pkgSetting = null; 8437 } 8438 final PackageSetting oldPkgSetting = 8439 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8440 final PackageSetting disabledPkgSetting = 8441 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8442 if (pkgSetting == null) { 8443 final String parentPackageName = (pkg.parentPackage != null) 8444 ? pkg.parentPackage.packageName : null; 8445 // REMOVE SharedUserSetting from method; update in a separate call 8446 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8447 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8448 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8449 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8450 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8451 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8452 UserManagerService.getInstance()); 8453 // SIDE EFFECTS; updates system state; move elsewhere 8454 if (origPackage != null) { 8455 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8456 } 8457 mSettings.addUserToSettingLPw(pkgSetting); 8458 } else { 8459 // REMOVE SharedUserSetting from method; update in a separate call. 8460 // 8461 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8462 // secondaryCpuAbi are not known at this point so we always update them 8463 // to null here, only to reset them at a later point. 8464 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8465 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8466 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8467 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8468 UserManagerService.getInstance()); 8469 } 8470 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8471 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8472 8473 // SIDE EFFECTS; modifies system state; move elsewhere 8474 if (pkgSetting.origPackage != null) { 8475 // If we are first transitioning from an original package, 8476 // fix up the new package's name now. We need to do this after 8477 // looking up the package under its new name, so getPackageLP 8478 // can take care of fiddling things correctly. 8479 pkg.setPackageName(origPackage.name); 8480 8481 // File a report about this. 8482 String msg = "New package " + pkgSetting.realName 8483 + " renamed to replace old package " + pkgSetting.name; 8484 reportSettingsProblem(Log.WARN, msg); 8485 8486 // Make a note of it. 8487 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8488 mTransferedPackages.add(origPackage.name); 8489 } 8490 8491 // No longer need to retain this. 8492 pkgSetting.origPackage = null; 8493 } 8494 8495 // SIDE EFFECTS; modifies system state; move elsewhere 8496 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8497 // Make a note of it. 8498 mTransferedPackages.add(pkg.packageName); 8499 } 8500 8501 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8502 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8503 } 8504 8505 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8506 // Check all shared libraries and map to their actual file path. 8507 // We only do this here for apps not on a system dir, because those 8508 // are the only ones that can fail an install due to this. We 8509 // will take care of the system apps by updating all of their 8510 // library paths after the scan is done. 8511 updateSharedLibrariesLPr(pkg, null); 8512 } 8513 8514 if (mFoundPolicyFile) { 8515 SELinuxMMAC.assignSeinfoValue(pkg); 8516 } 8517 8518 pkg.applicationInfo.uid = pkgSetting.appId; 8519 pkg.mExtras = pkgSetting; 8520 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8521 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8522 // We just determined the app is signed correctly, so bring 8523 // over the latest parsed certs. 8524 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8525 } else { 8526 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8527 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8528 "Package " + pkg.packageName + " upgrade keys do not match the " 8529 + "previously installed version"); 8530 } else { 8531 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8532 String msg = "System package " + pkg.packageName 8533 + " signature changed; retaining data."; 8534 reportSettingsProblem(Log.WARN, msg); 8535 } 8536 } 8537 } else { 8538 try { 8539 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8540 verifySignaturesLP(pkgSetting, pkg); 8541 // We just determined the app is signed correctly, so bring 8542 // over the latest parsed certs. 8543 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8544 } catch (PackageManagerException e) { 8545 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8546 throw e; 8547 } 8548 // The signature has changed, but this package is in the system 8549 // image... let's recover! 8550 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8551 // However... if this package is part of a shared user, but it 8552 // doesn't match the signature of the shared user, let's fail. 8553 // What this means is that you can't change the signatures 8554 // associated with an overall shared user, which doesn't seem all 8555 // that unreasonable. 8556 if (pkgSetting.sharedUser != null) { 8557 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8558 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8559 throw new PackageManagerException( 8560 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8561 "Signature mismatch for shared user: " 8562 + pkgSetting.sharedUser); 8563 } 8564 } 8565 // File a report about this. 8566 String msg = "System package " + pkg.packageName 8567 + " signature changed; retaining data."; 8568 reportSettingsProblem(Log.WARN, msg); 8569 } 8570 } 8571 8572 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8573 // This package wants to adopt ownership of permissions from 8574 // another package. 8575 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8576 final String origName = pkg.mAdoptPermissions.get(i); 8577 final PackageSetting orig = mSettings.getPackageLPr(origName); 8578 if (orig != null) { 8579 if (verifyPackageUpdateLPr(orig, pkg)) { 8580 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8581 + pkg.packageName); 8582 // SIDE EFFECTS; updates permissions system state; move elsewhere 8583 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8584 } 8585 } 8586 } 8587 } 8588 } 8589 8590 pkg.applicationInfo.processName = fixProcessName( 8591 pkg.applicationInfo.packageName, 8592 pkg.applicationInfo.processName); 8593 8594 if (pkg != mPlatformPackage) { 8595 // Get all of our default paths setup 8596 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8597 } 8598 8599 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8600 8601 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8602 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8603 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8604 derivePackageAbi( 8605 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8606 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8607 8608 // Some system apps still use directory structure for native libraries 8609 // in which case we might end up not detecting abi solely based on apk 8610 // structure. Try to detect abi based on directory structure. 8611 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8612 pkg.applicationInfo.primaryCpuAbi == null) { 8613 setBundledAppAbisAndRoots(pkg, pkgSetting); 8614 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8615 } 8616 } else { 8617 // This is not a first boot or an upgrade, don't bother deriving the 8618 // ABI during the scan. Instead, trust the value that was stored in the 8619 // package setting. 8620 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8621 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8622 8623 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8624 8625 if (DEBUG_ABI_SELECTION) { 8626 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8627 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8628 pkg.applicationInfo.secondaryCpuAbi); 8629 } 8630 } 8631 } else { 8632 if ((scanFlags & SCAN_MOVE) != 0) { 8633 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8634 // but we already have this packages package info in the PackageSetting. We just 8635 // use that and derive the native library path based on the new codepath. 8636 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8637 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8638 } 8639 8640 // Set native library paths again. For moves, the path will be updated based on the 8641 // ABIs we've determined above. For non-moves, the path will be updated based on the 8642 // ABIs we determined during compilation, but the path will depend on the final 8643 // package path (after the rename away from the stage path). 8644 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8645 } 8646 8647 // This is a special case for the "system" package, where the ABI is 8648 // dictated by the zygote configuration (and init.rc). We should keep track 8649 // of this ABI so that we can deal with "normal" applications that run under 8650 // the same UID correctly. 8651 if (mPlatformPackage == pkg) { 8652 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8653 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8654 } 8655 8656 // If there's a mismatch between the abi-override in the package setting 8657 // and the abiOverride specified for the install. Warn about this because we 8658 // would've already compiled the app without taking the package setting into 8659 // account. 8660 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8661 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8662 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8663 " for package " + pkg.packageName); 8664 } 8665 } 8666 8667 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8668 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8669 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8670 8671 // Copy the derived override back to the parsed package, so that we can 8672 // update the package settings accordingly. 8673 pkg.cpuAbiOverride = cpuAbiOverride; 8674 8675 if (DEBUG_ABI_SELECTION) { 8676 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8677 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8678 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8679 } 8680 8681 // Push the derived path down into PackageSettings so we know what to 8682 // clean up at uninstall time. 8683 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8684 8685 if (DEBUG_ABI_SELECTION) { 8686 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8687 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8688 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8689 } 8690 8691 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8692 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8693 // We don't do this here during boot because we can do it all 8694 // at once after scanning all existing packages. 8695 // 8696 // We also do this *before* we perform dexopt on this package, so that 8697 // we can avoid redundant dexopts, and also to make sure we've got the 8698 // code and package path correct. 8699 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8700 } 8701 8702 if (mFactoryTest && pkg.requestedPermissions.contains( 8703 android.Manifest.permission.FACTORY_TEST)) { 8704 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8705 } 8706 8707 if (isSystemApp(pkg)) { 8708 pkgSetting.isOrphaned = true; 8709 } 8710 8711 // Take care of first install / last update times. 8712 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8713 if (currentTime != 0) { 8714 if (pkgSetting.firstInstallTime == 0) { 8715 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8716 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8717 pkgSetting.lastUpdateTime = currentTime; 8718 } 8719 } else if (pkgSetting.firstInstallTime == 0) { 8720 // We need *something*. Take time time stamp of the file. 8721 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8722 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8723 if (scanFileTime != pkgSetting.timeStamp) { 8724 // A package on the system image has changed; consider this 8725 // to be an update. 8726 pkgSetting.lastUpdateTime = scanFileTime; 8727 } 8728 } 8729 pkgSetting.setTimeStamp(scanFileTime); 8730 8731 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8732 if (nonMutatedPs != null) { 8733 synchronized (mPackages) { 8734 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8735 } 8736 } 8737 } else { 8738 // Modify state for the given package setting 8739 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8740 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8741 } 8742 return pkg; 8743 } 8744 8745 /** 8746 * Applies policy to the parsed package based upon the given policy flags. 8747 * Ensures the package is in a good state. 8748 * <p> 8749 * Implementation detail: This method must NOT have any side effect. It would 8750 * ideally be static, but, it requires locks to read system state. 8751 */ 8752 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8753 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8754 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8755 if (pkg.applicationInfo.isDirectBootAware()) { 8756 // we're direct boot aware; set for all components 8757 for (PackageParser.Service s : pkg.services) { 8758 s.info.encryptionAware = s.info.directBootAware = true; 8759 } 8760 for (PackageParser.Provider p : pkg.providers) { 8761 p.info.encryptionAware = p.info.directBootAware = true; 8762 } 8763 for (PackageParser.Activity a : pkg.activities) { 8764 a.info.encryptionAware = a.info.directBootAware = true; 8765 } 8766 for (PackageParser.Activity r : pkg.receivers) { 8767 r.info.encryptionAware = r.info.directBootAware = true; 8768 } 8769 } 8770 } else { 8771 // Only allow system apps to be flagged as core apps. 8772 pkg.coreApp = false; 8773 // clear flags not applicable to regular apps 8774 pkg.applicationInfo.privateFlags &= 8775 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8776 pkg.applicationInfo.privateFlags &= 8777 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8778 } 8779 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8780 8781 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8782 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8783 } 8784 8785 if (!isSystemApp(pkg)) { 8786 // Only system apps can use these features. 8787 pkg.mOriginalPackages = null; 8788 pkg.mRealPackage = null; 8789 pkg.mAdoptPermissions = null; 8790 } 8791 } 8792 8793 /** 8794 * Asserts the parsed package is valid according to teh given policy. If the 8795 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8796 * <p> 8797 * Implementation detail: This method must NOT have any side effects. It would 8798 * ideally be static, but, it requires locks to read system state. 8799 * 8800 * @throws PackageManagerException If the package fails any of the validation checks 8801 */ 8802 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8803 throws PackageManagerException { 8804 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8805 assertCodePolicy(pkg); 8806 } 8807 8808 if (pkg.applicationInfo.getCodePath() == null || 8809 pkg.applicationInfo.getResourcePath() == null) { 8810 // Bail out. The resource and code paths haven't been set. 8811 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8812 "Code and resource paths haven't been set correctly"); 8813 } 8814 8815 // Make sure we're not adding any bogus keyset info 8816 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8817 ksms.assertScannedPackageValid(pkg); 8818 8819 synchronized (mPackages) { 8820 // The special "android" package can only be defined once 8821 if (pkg.packageName.equals("android")) { 8822 if (mAndroidApplication != null) { 8823 Slog.w(TAG, "*************************************************"); 8824 Slog.w(TAG, "Core android package being redefined. Skipping."); 8825 Slog.w(TAG, " codePath=" + pkg.codePath); 8826 Slog.w(TAG, "*************************************************"); 8827 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8828 "Core android package being redefined. Skipping."); 8829 } 8830 } 8831 8832 // A package name must be unique; don't allow duplicates 8833 if (mPackages.containsKey(pkg.packageName) 8834 || mSharedLibraries.containsKey(pkg.packageName)) { 8835 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8836 "Application package " + pkg.packageName 8837 + " already installed. Skipping duplicate."); 8838 } 8839 8840 // Only privileged apps and updated privileged apps can add child packages. 8841 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8842 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8843 throw new PackageManagerException("Only privileged apps can add child " 8844 + "packages. Ignoring package " + pkg.packageName); 8845 } 8846 final int childCount = pkg.childPackages.size(); 8847 for (int i = 0; i < childCount; i++) { 8848 PackageParser.Package childPkg = pkg.childPackages.get(i); 8849 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8850 childPkg.packageName)) { 8851 throw new PackageManagerException("Can't override child of " 8852 + "another disabled app. Ignoring package " + pkg.packageName); 8853 } 8854 } 8855 } 8856 8857 // If we're only installing presumed-existing packages, require that the 8858 // scanned APK is both already known and at the path previously established 8859 // for it. Previously unknown packages we pick up normally, but if we have an 8860 // a priori expectation about this package's install presence, enforce it. 8861 // With a singular exception for new system packages. When an OTA contains 8862 // a new system package, we allow the codepath to change from a system location 8863 // to the user-installed location. If we don't allow this change, any newer, 8864 // user-installed version of the application will be ignored. 8865 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8866 if (mExpectingBetter.containsKey(pkg.packageName)) { 8867 logCriticalInfo(Log.WARN, 8868 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8869 } else { 8870 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8871 if (known != null) { 8872 if (DEBUG_PACKAGE_SCANNING) { 8873 Log.d(TAG, "Examining " + pkg.codePath 8874 + " and requiring known paths " + known.codePathString 8875 + " & " + known.resourcePathString); 8876 } 8877 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8878 || !pkg.applicationInfo.getResourcePath().equals( 8879 known.resourcePathString)) { 8880 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8881 "Application package " + pkg.packageName 8882 + " found at " + pkg.applicationInfo.getCodePath() 8883 + " but expected at " + known.codePathString 8884 + "; ignoring."); 8885 } 8886 } 8887 } 8888 } 8889 8890 // Verify that this new package doesn't have any content providers 8891 // that conflict with existing packages. Only do this if the 8892 // package isn't already installed, since we don't want to break 8893 // things that are installed. 8894 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8895 final int N = pkg.providers.size(); 8896 int i; 8897 for (i=0; i<N; i++) { 8898 PackageParser.Provider p = pkg.providers.get(i); 8899 if (p.info.authority != null) { 8900 String names[] = p.info.authority.split(";"); 8901 for (int j = 0; j < names.length; j++) { 8902 if (mProvidersByAuthority.containsKey(names[j])) { 8903 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8904 final String otherPackageName = 8905 ((other != null && other.getComponentName() != null) ? 8906 other.getComponentName().getPackageName() : "?"); 8907 throw new PackageManagerException( 8908 INSTALL_FAILED_CONFLICTING_PROVIDER, 8909 "Can't install because provider name " + names[j] 8910 + " (in package " + pkg.applicationInfo.packageName 8911 + ") is already used by " + otherPackageName); 8912 } 8913 } 8914 } 8915 } 8916 } 8917 } 8918 } 8919 8920 /** 8921 * Adds a scanned package to the system. When this method is finished, the package will 8922 * be available for query, resolution, etc... 8923 */ 8924 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8925 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8926 final String pkgName = pkg.packageName; 8927 if (mCustomResolverComponentName != null && 8928 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8929 setUpCustomResolverActivity(pkg); 8930 } 8931 8932 if (pkg.packageName.equals("android")) { 8933 synchronized (mPackages) { 8934 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8935 // Set up information for our fall-back user intent resolution activity. 8936 mPlatformPackage = pkg; 8937 pkg.mVersionCode = mSdkVersion; 8938 mAndroidApplication = pkg.applicationInfo; 8939 8940 if (!mResolverReplaced) { 8941 mResolveActivity.applicationInfo = mAndroidApplication; 8942 mResolveActivity.name = ResolverActivity.class.getName(); 8943 mResolveActivity.packageName = mAndroidApplication.packageName; 8944 mResolveActivity.processName = "system:ui"; 8945 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8946 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8947 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8948 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8949 mResolveActivity.exported = true; 8950 mResolveActivity.enabled = true; 8951 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8952 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8953 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8954 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8955 | ActivityInfo.CONFIG_ORIENTATION 8956 | ActivityInfo.CONFIG_KEYBOARD 8957 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8958 mResolveInfo.activityInfo = mResolveActivity; 8959 mResolveInfo.priority = 0; 8960 mResolveInfo.preferredOrder = 0; 8961 mResolveInfo.match = 0; 8962 mResolveComponentName = new ComponentName( 8963 mAndroidApplication.packageName, mResolveActivity.name); 8964 } 8965 } 8966 } 8967 } 8968 8969 ArrayList<PackageParser.Package> clientLibPkgs = null; 8970 // writer 8971 synchronized (mPackages) { 8972 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8973 // Only system apps can add new shared libraries. 8974 if (pkg.libraryNames != null) { 8975 for (int i=0; i<pkg.libraryNames.size(); i++) { 8976 String name = pkg.libraryNames.get(i); 8977 boolean allowed = false; 8978 if (pkg.isUpdatedSystemApp()) { 8979 // New library entries can only be added through the 8980 // system image. This is important to get rid of a lot 8981 // of nasty edge cases: for example if we allowed a non- 8982 // system update of the app to add a library, then uninstalling 8983 // the update would make the library go away, and assumptions 8984 // we made such as through app install filtering would now 8985 // have allowed apps on the device which aren't compatible 8986 // with it. Better to just have the restriction here, be 8987 // conservative, and create many fewer cases that can negatively 8988 // impact the user experience. 8989 final PackageSetting sysPs = mSettings 8990 .getDisabledSystemPkgLPr(pkg.packageName); 8991 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8992 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8993 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8994 allowed = true; 8995 break; 8996 } 8997 } 8998 } 8999 } else { 9000 allowed = true; 9001 } 9002 if (allowed) { 9003 if (!mSharedLibraries.containsKey(name)) { 9004 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 9005 } else if (!name.equals(pkg.packageName)) { 9006 Slog.w(TAG, "Package " + pkg.packageName + " library " 9007 + name + " already exists; skipping"); 9008 } 9009 } else { 9010 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9011 + name + " that is not declared on system image; skipping"); 9012 } 9013 } 9014 if ((scanFlags & SCAN_BOOTING) == 0) { 9015 // If we are not booting, we need to update any applications 9016 // that are clients of our shared library. If we are booting, 9017 // this will all be done once the scan is complete. 9018 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9019 } 9020 } 9021 } 9022 } 9023 9024 if ((scanFlags & SCAN_BOOTING) != 0) { 9025 // No apps can run during boot scan, so they don't need to be frozen 9026 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9027 // Caller asked to not kill app, so it's probably not frozen 9028 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9029 // Caller asked us to ignore frozen check for some reason; they 9030 // probably didn't know the package name 9031 } else { 9032 // We're doing major surgery on this package, so it better be frozen 9033 // right now to keep it from launching 9034 checkPackageFrozen(pkgName); 9035 } 9036 9037 // Also need to kill any apps that are dependent on the library. 9038 if (clientLibPkgs != null) { 9039 for (int i=0; i<clientLibPkgs.size(); i++) { 9040 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9041 killApplication(clientPkg.applicationInfo.packageName, 9042 clientPkg.applicationInfo.uid, "update lib"); 9043 } 9044 } 9045 9046 // writer 9047 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9048 9049 boolean createIdmapFailed = false; 9050 synchronized (mPackages) { 9051 // We don't expect installation to fail beyond this point 9052 9053 if (pkgSetting.pkg != null) { 9054 // Note that |user| might be null during the initial boot scan. If a codePath 9055 // for an app has changed during a boot scan, it's due to an app update that's 9056 // part of the system partition and marker changes must be applied to all users. 9057 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9058 final int[] userIds = resolveUserIds(userId); 9059 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9060 } 9061 9062 // Add the new setting to mSettings 9063 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9064 // Add the new setting to mPackages 9065 mPackages.put(pkg.applicationInfo.packageName, pkg); 9066 // Make sure we don't accidentally delete its data. 9067 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9068 while (iter.hasNext()) { 9069 PackageCleanItem item = iter.next(); 9070 if (pkgName.equals(item.packageName)) { 9071 iter.remove(); 9072 } 9073 } 9074 9075 // Add the package's KeySets to the global KeySetManagerService 9076 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9077 ksms.addScannedPackageLPw(pkg); 9078 9079 int N = pkg.providers.size(); 9080 StringBuilder r = null; 9081 int i; 9082 for (i=0; i<N; i++) { 9083 PackageParser.Provider p = pkg.providers.get(i); 9084 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9085 p.info.processName); 9086 mProviders.addProvider(p); 9087 p.syncable = p.info.isSyncable; 9088 if (p.info.authority != null) { 9089 String names[] = p.info.authority.split(";"); 9090 p.info.authority = null; 9091 for (int j = 0; j < names.length; j++) { 9092 if (j == 1 && p.syncable) { 9093 // We only want the first authority for a provider to possibly be 9094 // syncable, so if we already added this provider using a different 9095 // authority clear the syncable flag. We copy the provider before 9096 // changing it because the mProviders object contains a reference 9097 // to a provider that we don't want to change. 9098 // Only do this for the second authority since the resulting provider 9099 // object can be the same for all future authorities for this provider. 9100 p = new PackageParser.Provider(p); 9101 p.syncable = false; 9102 } 9103 if (!mProvidersByAuthority.containsKey(names[j])) { 9104 mProvidersByAuthority.put(names[j], p); 9105 if (p.info.authority == null) { 9106 p.info.authority = names[j]; 9107 } else { 9108 p.info.authority = p.info.authority + ";" + names[j]; 9109 } 9110 if (DEBUG_PACKAGE_SCANNING) { 9111 if (chatty) 9112 Log.d(TAG, "Registered content provider: " + names[j] 9113 + ", className = " + p.info.name + ", isSyncable = " 9114 + p.info.isSyncable); 9115 } 9116 } else { 9117 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9118 Slog.w(TAG, "Skipping provider name " + names[j] + 9119 " (in package " + pkg.applicationInfo.packageName + 9120 "): name already used by " 9121 + ((other != null && other.getComponentName() != null) 9122 ? other.getComponentName().getPackageName() : "?")); 9123 } 9124 } 9125 } 9126 if (chatty) { 9127 if (r == null) { 9128 r = new StringBuilder(256); 9129 } else { 9130 r.append(' '); 9131 } 9132 r.append(p.info.name); 9133 } 9134 } 9135 if (r != null) { 9136 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9137 } 9138 9139 N = pkg.services.size(); 9140 r = null; 9141 for (i=0; i<N; i++) { 9142 PackageParser.Service s = pkg.services.get(i); 9143 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9144 s.info.processName); 9145 mServices.addService(s); 9146 if (chatty) { 9147 if (r == null) { 9148 r = new StringBuilder(256); 9149 } else { 9150 r.append(' '); 9151 } 9152 r.append(s.info.name); 9153 } 9154 } 9155 if (r != null) { 9156 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9157 } 9158 9159 N = pkg.receivers.size(); 9160 r = null; 9161 for (i=0; i<N; i++) { 9162 PackageParser.Activity a = pkg.receivers.get(i); 9163 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9164 a.info.processName); 9165 mReceivers.addActivity(a, "receiver"); 9166 if (chatty) { 9167 if (r == null) { 9168 r = new StringBuilder(256); 9169 } else { 9170 r.append(' '); 9171 } 9172 r.append(a.info.name); 9173 } 9174 } 9175 if (r != null) { 9176 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9177 } 9178 9179 N = pkg.activities.size(); 9180 r = null; 9181 for (i=0; i<N; i++) { 9182 PackageParser.Activity a = pkg.activities.get(i); 9183 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9184 a.info.processName); 9185 mActivities.addActivity(a, "activity"); 9186 if (chatty) { 9187 if (r == null) { 9188 r = new StringBuilder(256); 9189 } else { 9190 r.append(' '); 9191 } 9192 r.append(a.info.name); 9193 } 9194 } 9195 if (r != null) { 9196 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9197 } 9198 9199 N = pkg.permissionGroups.size(); 9200 r = null; 9201 for (i=0; i<N; i++) { 9202 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9203 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9204 final String curPackageName = cur == null ? null : cur.info.packageName; 9205 // Dont allow ephemeral apps to define new permission groups. 9206 if (pkg.applicationInfo.isEphemeralApp()) { 9207 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9208 + pg.info.packageName 9209 + " ignored: ephemeral apps cannot define new permission groups."); 9210 continue; 9211 } 9212 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9213 if (cur == null || isPackageUpdate) { 9214 mPermissionGroups.put(pg.info.name, pg); 9215 if (chatty) { 9216 if (r == null) { 9217 r = new StringBuilder(256); 9218 } else { 9219 r.append(' '); 9220 } 9221 if (isPackageUpdate) { 9222 r.append("UPD:"); 9223 } 9224 r.append(pg.info.name); 9225 } 9226 } else { 9227 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9228 + pg.info.packageName + " ignored: original from " 9229 + cur.info.packageName); 9230 if (chatty) { 9231 if (r == null) { 9232 r = new StringBuilder(256); 9233 } else { 9234 r.append(' '); 9235 } 9236 r.append("DUP:"); 9237 r.append(pg.info.name); 9238 } 9239 } 9240 } 9241 if (r != null) { 9242 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9243 } 9244 9245 N = pkg.permissions.size(); 9246 r = null; 9247 for (i=0; i<N; i++) { 9248 PackageParser.Permission p = pkg.permissions.get(i); 9249 9250 // Dont allow ephemeral apps to define new permissions. 9251 if (pkg.applicationInfo.isEphemeralApp()) { 9252 Slog.w(TAG, "Permission " + p.info.name + " from package " 9253 + p.info.packageName 9254 + " ignored: ephemeral apps cannot define new permissions."); 9255 continue; 9256 } 9257 9258 // Assume by default that we did not install this permission into the system. 9259 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9260 9261 // Now that permission groups have a special meaning, we ignore permission 9262 // groups for legacy apps to prevent unexpected behavior. In particular, 9263 // permissions for one app being granted to someone just becase they happen 9264 // to be in a group defined by another app (before this had no implications). 9265 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9266 p.group = mPermissionGroups.get(p.info.group); 9267 // Warn for a permission in an unknown group. 9268 if (p.info.group != null && p.group == null) { 9269 Slog.w(TAG, "Permission " + p.info.name + " from package " 9270 + p.info.packageName + " in an unknown group " + p.info.group); 9271 } 9272 } 9273 9274 ArrayMap<String, BasePermission> permissionMap = 9275 p.tree ? mSettings.mPermissionTrees 9276 : mSettings.mPermissions; 9277 BasePermission bp = permissionMap.get(p.info.name); 9278 9279 // Allow system apps to redefine non-system permissions 9280 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9281 final boolean currentOwnerIsSystem = (bp.perm != null 9282 && isSystemApp(bp.perm.owner)); 9283 if (isSystemApp(p.owner)) { 9284 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9285 // It's a built-in permission and no owner, take ownership now 9286 bp.packageSetting = pkgSetting; 9287 bp.perm = p; 9288 bp.uid = pkg.applicationInfo.uid; 9289 bp.sourcePackage = p.info.packageName; 9290 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9291 } else if (!currentOwnerIsSystem) { 9292 String msg = "New decl " + p.owner + " of permission " 9293 + p.info.name + " is system; overriding " + bp.sourcePackage; 9294 reportSettingsProblem(Log.WARN, msg); 9295 bp = null; 9296 } 9297 } 9298 } 9299 9300 if (bp == null) { 9301 bp = new BasePermission(p.info.name, p.info.packageName, 9302 BasePermission.TYPE_NORMAL); 9303 permissionMap.put(p.info.name, bp); 9304 } 9305 9306 if (bp.perm == null) { 9307 if (bp.sourcePackage == null 9308 || bp.sourcePackage.equals(p.info.packageName)) { 9309 BasePermission tree = findPermissionTreeLP(p.info.name); 9310 if (tree == null 9311 || tree.sourcePackage.equals(p.info.packageName)) { 9312 bp.packageSetting = pkgSetting; 9313 bp.perm = p; 9314 bp.uid = pkg.applicationInfo.uid; 9315 bp.sourcePackage = p.info.packageName; 9316 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9317 if (chatty) { 9318 if (r == null) { 9319 r = new StringBuilder(256); 9320 } else { 9321 r.append(' '); 9322 } 9323 r.append(p.info.name); 9324 } 9325 } else { 9326 Slog.w(TAG, "Permission " + p.info.name + " from package " 9327 + p.info.packageName + " ignored: base tree " 9328 + tree.name + " is from package " 9329 + tree.sourcePackage); 9330 } 9331 } else { 9332 Slog.w(TAG, "Permission " + p.info.name + " from package " 9333 + p.info.packageName + " ignored: original from " 9334 + bp.sourcePackage); 9335 } 9336 } else if (chatty) { 9337 if (r == null) { 9338 r = new StringBuilder(256); 9339 } else { 9340 r.append(' '); 9341 } 9342 r.append("DUP:"); 9343 r.append(p.info.name); 9344 } 9345 if (bp.perm == p) { 9346 bp.protectionLevel = p.info.protectionLevel; 9347 } 9348 } 9349 9350 if (r != null) { 9351 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9352 } 9353 9354 N = pkg.instrumentation.size(); 9355 r = null; 9356 for (i=0; i<N; i++) { 9357 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9358 a.info.packageName = pkg.applicationInfo.packageName; 9359 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9360 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9361 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9362 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9363 a.info.dataDir = pkg.applicationInfo.dataDir; 9364 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9365 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9366 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9367 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9368 mInstrumentation.put(a.getComponentName(), a); 9369 if (chatty) { 9370 if (r == null) { 9371 r = new StringBuilder(256); 9372 } else { 9373 r.append(' '); 9374 } 9375 r.append(a.info.name); 9376 } 9377 } 9378 if (r != null) { 9379 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9380 } 9381 9382 if (pkg.protectedBroadcasts != null) { 9383 N = pkg.protectedBroadcasts.size(); 9384 for (i=0; i<N; i++) { 9385 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9386 } 9387 } 9388 9389 // Create idmap files for pairs of (packages, overlay packages). 9390 // Note: "android", ie framework-res.apk, is handled by native layers. 9391 if (pkg.mOverlayTarget != null) { 9392 // This is an overlay package. 9393 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9394 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9395 mOverlays.put(pkg.mOverlayTarget, 9396 new ArrayMap<String, PackageParser.Package>()); 9397 } 9398 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9399 map.put(pkg.packageName, pkg); 9400 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9401 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9402 createIdmapFailed = true; 9403 } 9404 } 9405 } else if (mOverlays.containsKey(pkg.packageName) && 9406 !pkg.packageName.equals("android")) { 9407 // This is a regular package, with one or more known overlay packages. 9408 createIdmapsForPackageLI(pkg); 9409 } 9410 } 9411 9412 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9413 9414 if (createIdmapFailed) { 9415 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9416 "scanPackageLI failed to createIdmap"); 9417 } 9418 } 9419 9420 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9421 PackageParser.Package update, int[] userIds) { 9422 if (existing.applicationInfo == null || update.applicationInfo == null) { 9423 // This isn't due to an app installation. 9424 return; 9425 } 9426 9427 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9428 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9429 9430 // The codePath hasn't changed, so there's nothing for us to do. 9431 if (Objects.equals(oldCodePath, newCodePath)) { 9432 return; 9433 } 9434 9435 File canonicalNewCodePath; 9436 try { 9437 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9438 } catch (IOException e) { 9439 Slog.w(TAG, "Failed to get canonical path.", e); 9440 return; 9441 } 9442 9443 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9444 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9445 // that the last component of the path (i.e, the name) doesn't need canonicalization 9446 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9447 // but may change in the future. Hopefully this function won't exist at that point. 9448 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9449 oldCodePath.getName()); 9450 9451 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9452 // with "@". 9453 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9454 if (!oldMarkerPrefix.endsWith("@")) { 9455 oldMarkerPrefix += "@"; 9456 } 9457 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9458 if (!newMarkerPrefix.endsWith("@")) { 9459 newMarkerPrefix += "@"; 9460 } 9461 9462 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9463 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9464 for (String updatedPath : updatedPaths) { 9465 String updatedPathName = new File(updatedPath).getName(); 9466 markerSuffixes.add(updatedPathName.replace('/', '@')); 9467 } 9468 9469 for (int userId : userIds) { 9470 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9471 9472 for (String markerSuffix : markerSuffixes) { 9473 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9474 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9475 if (oldForeignUseMark.exists()) { 9476 try { 9477 Os.rename(oldForeignUseMark.getAbsolutePath(), 9478 newForeignUseMark.getAbsolutePath()); 9479 } catch (ErrnoException e) { 9480 Slog.w(TAG, "Failed to rename foreign use marker", e); 9481 oldForeignUseMark.delete(); 9482 } 9483 } 9484 } 9485 } 9486 } 9487 9488 /** 9489 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9490 * is derived purely on the basis of the contents of {@code scanFile} and 9491 * {@code cpuAbiOverride}. 9492 * 9493 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9494 */ 9495 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9496 String cpuAbiOverride, boolean extractLibs, 9497 File appLib32InstallDir) 9498 throws PackageManagerException { 9499 // Give ourselves some initial paths; we'll come back for another 9500 // pass once we've determined ABI below. 9501 setNativeLibraryPaths(pkg, appLib32InstallDir); 9502 9503 // We would never need to extract libs for forward-locked and external packages, 9504 // since the container service will do it for us. We shouldn't attempt to 9505 // extract libs from system app when it was not updated. 9506 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9507 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9508 extractLibs = false; 9509 } 9510 9511 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9512 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9513 9514 NativeLibraryHelper.Handle handle = null; 9515 try { 9516 handle = NativeLibraryHelper.Handle.create(pkg); 9517 // TODO(multiArch): This can be null for apps that didn't go through the 9518 // usual installation process. We can calculate it again, like we 9519 // do during install time. 9520 // 9521 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9522 // unnecessary. 9523 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9524 9525 // Null out the abis so that they can be recalculated. 9526 pkg.applicationInfo.primaryCpuAbi = null; 9527 pkg.applicationInfo.secondaryCpuAbi = null; 9528 if (isMultiArch(pkg.applicationInfo)) { 9529 // Warn if we've set an abiOverride for multi-lib packages.. 9530 // By definition, we need to copy both 32 and 64 bit libraries for 9531 // such packages. 9532 if (pkg.cpuAbiOverride != null 9533 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9534 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9535 } 9536 9537 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9538 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9539 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9540 if (extractLibs) { 9541 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9542 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9543 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9544 useIsaSpecificSubdirs); 9545 } else { 9546 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9547 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9548 } 9549 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9550 } 9551 9552 maybeThrowExceptionForMultiArchCopy( 9553 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9554 9555 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9556 if (extractLibs) { 9557 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9558 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9559 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9560 useIsaSpecificSubdirs); 9561 } else { 9562 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9563 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9564 } 9565 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9566 } 9567 9568 maybeThrowExceptionForMultiArchCopy( 9569 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9570 9571 if (abi64 >= 0) { 9572 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9573 } 9574 9575 if (abi32 >= 0) { 9576 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9577 if (abi64 >= 0) { 9578 if (pkg.use32bitAbi) { 9579 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9580 pkg.applicationInfo.primaryCpuAbi = abi; 9581 } else { 9582 pkg.applicationInfo.secondaryCpuAbi = abi; 9583 } 9584 } else { 9585 pkg.applicationInfo.primaryCpuAbi = abi; 9586 } 9587 } 9588 9589 } else { 9590 String[] abiList = (cpuAbiOverride != null) ? 9591 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9592 9593 // Enable gross and lame hacks for apps that are built with old 9594 // SDK tools. We must scan their APKs for renderscript bitcode and 9595 // not launch them if it's present. Don't bother checking on devices 9596 // that don't have 64 bit support. 9597 boolean needsRenderScriptOverride = false; 9598 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9599 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9600 abiList = Build.SUPPORTED_32_BIT_ABIS; 9601 needsRenderScriptOverride = true; 9602 } 9603 9604 final int copyRet; 9605 if (extractLibs) { 9606 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9607 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9608 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9609 } else { 9610 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9611 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9612 } 9613 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9614 9615 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9616 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9617 "Error unpackaging native libs for app, errorCode=" + copyRet); 9618 } 9619 9620 if (copyRet >= 0) { 9621 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9622 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9623 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9624 } else if (needsRenderScriptOverride) { 9625 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9626 } 9627 } 9628 } catch (IOException ioe) { 9629 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9630 } finally { 9631 IoUtils.closeQuietly(handle); 9632 } 9633 9634 // Now that we've calculated the ABIs and determined if it's an internal app, 9635 // we will go ahead and populate the nativeLibraryPath. 9636 setNativeLibraryPaths(pkg, appLib32InstallDir); 9637 } 9638 9639 /** 9640 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9641 * i.e, so that all packages can be run inside a single process if required. 9642 * 9643 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9644 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9645 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9646 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9647 * updating a package that belongs to a shared user. 9648 * 9649 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9650 * adds unnecessary complexity. 9651 */ 9652 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9653 PackageParser.Package scannedPackage) { 9654 String requiredInstructionSet = null; 9655 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9656 requiredInstructionSet = VMRuntime.getInstructionSet( 9657 scannedPackage.applicationInfo.primaryCpuAbi); 9658 } 9659 9660 PackageSetting requirer = null; 9661 for (PackageSetting ps : packagesForUser) { 9662 // If packagesForUser contains scannedPackage, we skip it. This will happen 9663 // when scannedPackage is an update of an existing package. Without this check, 9664 // we will never be able to change the ABI of any package belonging to a shared 9665 // user, even if it's compatible with other packages. 9666 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9667 if (ps.primaryCpuAbiString == null) { 9668 continue; 9669 } 9670 9671 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9672 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9673 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9674 // this but there's not much we can do. 9675 String errorMessage = "Instruction set mismatch, " 9676 + ((requirer == null) ? "[caller]" : requirer) 9677 + " requires " + requiredInstructionSet + " whereas " + ps 9678 + " requires " + instructionSet; 9679 Slog.w(TAG, errorMessage); 9680 } 9681 9682 if (requiredInstructionSet == null) { 9683 requiredInstructionSet = instructionSet; 9684 requirer = ps; 9685 } 9686 } 9687 } 9688 9689 if (requiredInstructionSet != null) { 9690 String adjustedAbi; 9691 if (requirer != null) { 9692 // requirer != null implies that either scannedPackage was null or that scannedPackage 9693 // did not require an ABI, in which case we have to adjust scannedPackage to match 9694 // the ABI of the set (which is the same as requirer's ABI) 9695 adjustedAbi = requirer.primaryCpuAbiString; 9696 if (scannedPackage != null) { 9697 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9698 } 9699 } else { 9700 // requirer == null implies that we're updating all ABIs in the set to 9701 // match scannedPackage. 9702 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9703 } 9704 9705 for (PackageSetting ps : packagesForUser) { 9706 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9707 if (ps.primaryCpuAbiString != null) { 9708 continue; 9709 } 9710 9711 ps.primaryCpuAbiString = adjustedAbi; 9712 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9713 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9714 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9715 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9716 + " (requirer=" 9717 + (requirer == null ? "null" : requirer.pkg.packageName) 9718 + ", scannedPackage=" 9719 + (scannedPackage != null ? scannedPackage.packageName : "null") 9720 + ")"); 9721 try { 9722 mInstaller.rmdex(ps.codePathString, 9723 getDexCodeInstructionSet(getPreferredInstructionSet())); 9724 } catch (InstallerException ignored) { 9725 } 9726 } 9727 } 9728 } 9729 } 9730 } 9731 9732 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9733 synchronized (mPackages) { 9734 mResolverReplaced = true; 9735 // Set up information for custom user intent resolution activity. 9736 mResolveActivity.applicationInfo = pkg.applicationInfo; 9737 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9738 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9739 mResolveActivity.processName = pkg.applicationInfo.packageName; 9740 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9741 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9742 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9743 mResolveActivity.theme = 0; 9744 mResolveActivity.exported = true; 9745 mResolveActivity.enabled = true; 9746 mResolveInfo.activityInfo = mResolveActivity; 9747 mResolveInfo.priority = 0; 9748 mResolveInfo.preferredOrder = 0; 9749 mResolveInfo.match = 0; 9750 mResolveComponentName = mCustomResolverComponentName; 9751 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9752 mResolveComponentName); 9753 } 9754 } 9755 9756 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9757 if (installerComponent == null) { 9758 if (DEBUG_EPHEMERAL) { 9759 Slog.d(TAG, "Clear ephemeral installer activity"); 9760 } 9761 mEphemeralInstallerActivity.applicationInfo = null; 9762 return; 9763 } 9764 9765 if (DEBUG_EPHEMERAL) { 9766 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9767 } 9768 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9769 // Set up information for ephemeral installer activity 9770 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9771 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9772 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9773 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9774 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9775 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9776 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9777 mEphemeralInstallerActivity.theme = 0; 9778 mEphemeralInstallerActivity.exported = true; 9779 mEphemeralInstallerActivity.enabled = true; 9780 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9781 mEphemeralInstallerInfo.priority = 0; 9782 mEphemeralInstallerInfo.preferredOrder = 1; 9783 mEphemeralInstallerInfo.isDefault = true; 9784 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9785 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9786 } 9787 9788 private static String calculateBundledApkRoot(final String codePathString) { 9789 final File codePath = new File(codePathString); 9790 final File codeRoot; 9791 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9792 codeRoot = Environment.getRootDirectory(); 9793 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9794 codeRoot = Environment.getOemDirectory(); 9795 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9796 codeRoot = Environment.getVendorDirectory(); 9797 } else { 9798 // Unrecognized code path; take its top real segment as the apk root: 9799 // e.g. /something/app/blah.apk => /something 9800 try { 9801 File f = codePath.getCanonicalFile(); 9802 File parent = f.getParentFile(); // non-null because codePath is a file 9803 File tmp; 9804 while ((tmp = parent.getParentFile()) != null) { 9805 f = parent; 9806 parent = tmp; 9807 } 9808 codeRoot = f; 9809 Slog.w(TAG, "Unrecognized code path " 9810 + codePath + " - using " + codeRoot); 9811 } catch (IOException e) { 9812 // Can't canonicalize the code path -- shenanigans? 9813 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9814 return Environment.getRootDirectory().getPath(); 9815 } 9816 } 9817 return codeRoot.getPath(); 9818 } 9819 9820 /** 9821 * Derive and set the location of native libraries for the given package, 9822 * which varies depending on where and how the package was installed. 9823 */ 9824 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9825 final ApplicationInfo info = pkg.applicationInfo; 9826 final String codePath = pkg.codePath; 9827 final File codeFile = new File(codePath); 9828 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9829 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9830 9831 info.nativeLibraryRootDir = null; 9832 info.nativeLibraryRootRequiresIsa = false; 9833 info.nativeLibraryDir = null; 9834 info.secondaryNativeLibraryDir = null; 9835 9836 if (isApkFile(codeFile)) { 9837 // Monolithic install 9838 if (bundledApp) { 9839 // If "/system/lib64/apkname" exists, assume that is the per-package 9840 // native library directory to use; otherwise use "/system/lib/apkname". 9841 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9842 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9843 getPrimaryInstructionSet(info)); 9844 9845 // This is a bundled system app so choose the path based on the ABI. 9846 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9847 // is just the default path. 9848 final String apkName = deriveCodePathName(codePath); 9849 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9850 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9851 apkName).getAbsolutePath(); 9852 9853 if (info.secondaryCpuAbi != null) { 9854 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9855 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9856 secondaryLibDir, apkName).getAbsolutePath(); 9857 } 9858 } else if (asecApp) { 9859 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9860 .getAbsolutePath(); 9861 } else { 9862 final String apkName = deriveCodePathName(codePath); 9863 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9864 .getAbsolutePath(); 9865 } 9866 9867 info.nativeLibraryRootRequiresIsa = false; 9868 info.nativeLibraryDir = info.nativeLibraryRootDir; 9869 } else { 9870 // Cluster install 9871 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9872 info.nativeLibraryRootRequiresIsa = true; 9873 9874 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9875 getPrimaryInstructionSet(info)).getAbsolutePath(); 9876 9877 if (info.secondaryCpuAbi != null) { 9878 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9879 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9880 } 9881 } 9882 } 9883 9884 /** 9885 * Calculate the abis and roots for a bundled app. These can uniquely 9886 * be determined from the contents of the system partition, i.e whether 9887 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9888 * of this information, and instead assume that the system was built 9889 * sensibly. 9890 */ 9891 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9892 PackageSetting pkgSetting) { 9893 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9894 9895 // If "/system/lib64/apkname" exists, assume that is the per-package 9896 // native library directory to use; otherwise use "/system/lib/apkname". 9897 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9898 setBundledAppAbi(pkg, apkRoot, apkName); 9899 // pkgSetting might be null during rescan following uninstall of updates 9900 // to a bundled app, so accommodate that possibility. The settings in 9901 // that case will be established later from the parsed package. 9902 // 9903 // If the settings aren't null, sync them up with what we've just derived. 9904 // note that apkRoot isn't stored in the package settings. 9905 if (pkgSetting != null) { 9906 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9907 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9908 } 9909 } 9910 9911 /** 9912 * Deduces the ABI of a bundled app and sets the relevant fields on the 9913 * parsed pkg object. 9914 * 9915 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9916 * under which system libraries are installed. 9917 * @param apkName the name of the installed package. 9918 */ 9919 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9920 final File codeFile = new File(pkg.codePath); 9921 9922 final boolean has64BitLibs; 9923 final boolean has32BitLibs; 9924 if (isApkFile(codeFile)) { 9925 // Monolithic install 9926 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9927 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9928 } else { 9929 // Cluster install 9930 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9931 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9932 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9933 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9934 has64BitLibs = (new File(rootDir, isa)).exists(); 9935 } else { 9936 has64BitLibs = false; 9937 } 9938 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9939 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9940 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9941 has32BitLibs = (new File(rootDir, isa)).exists(); 9942 } else { 9943 has32BitLibs = false; 9944 } 9945 } 9946 9947 if (has64BitLibs && !has32BitLibs) { 9948 // The package has 64 bit libs, but not 32 bit libs. Its primary 9949 // ABI should be 64 bit. We can safely assume here that the bundled 9950 // native libraries correspond to the most preferred ABI in the list. 9951 9952 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9953 pkg.applicationInfo.secondaryCpuAbi = null; 9954 } else if (has32BitLibs && !has64BitLibs) { 9955 // The package has 32 bit libs but not 64 bit libs. Its primary 9956 // ABI should be 32 bit. 9957 9958 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9959 pkg.applicationInfo.secondaryCpuAbi = null; 9960 } else if (has32BitLibs && has64BitLibs) { 9961 // The application has both 64 and 32 bit bundled libraries. We check 9962 // here that the app declares multiArch support, and warn if it doesn't. 9963 // 9964 // We will be lenient here and record both ABIs. The primary will be the 9965 // ABI that's higher on the list, i.e, a device that's configured to prefer 9966 // 64 bit apps will see a 64 bit primary ABI, 9967 9968 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9969 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9970 } 9971 9972 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9973 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9974 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9975 } else { 9976 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9977 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9978 } 9979 } else { 9980 pkg.applicationInfo.primaryCpuAbi = null; 9981 pkg.applicationInfo.secondaryCpuAbi = null; 9982 } 9983 } 9984 9985 private void killApplication(String pkgName, int appId, String reason) { 9986 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9987 } 9988 9989 private void killApplication(String pkgName, int appId, int userId, String reason) { 9990 // Request the ActivityManager to kill the process(only for existing packages) 9991 // so that we do not end up in a confused state while the user is still using the older 9992 // version of the application while the new one gets installed. 9993 final long token = Binder.clearCallingIdentity(); 9994 try { 9995 IActivityManager am = ActivityManager.getService(); 9996 if (am != null) { 9997 try { 9998 am.killApplication(pkgName, appId, userId, reason); 9999 } catch (RemoteException e) { 10000 } 10001 } 10002 } finally { 10003 Binder.restoreCallingIdentity(token); 10004 } 10005 } 10006 10007 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10008 // Remove the parent package setting 10009 PackageSetting ps = (PackageSetting) pkg.mExtras; 10010 if (ps != null) { 10011 removePackageLI(ps, chatty); 10012 } 10013 // Remove the child package setting 10014 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10015 for (int i = 0; i < childCount; i++) { 10016 PackageParser.Package childPkg = pkg.childPackages.get(i); 10017 ps = (PackageSetting) childPkg.mExtras; 10018 if (ps != null) { 10019 removePackageLI(ps, chatty); 10020 } 10021 } 10022 } 10023 10024 void removePackageLI(PackageSetting ps, boolean chatty) { 10025 if (DEBUG_INSTALL) { 10026 if (chatty) 10027 Log.d(TAG, "Removing package " + ps.name); 10028 } 10029 10030 // writer 10031 synchronized (mPackages) { 10032 mPackages.remove(ps.name); 10033 final PackageParser.Package pkg = ps.pkg; 10034 if (pkg != null) { 10035 cleanPackageDataStructuresLILPw(pkg, chatty); 10036 } 10037 } 10038 } 10039 10040 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10041 if (DEBUG_INSTALL) { 10042 if (chatty) 10043 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10044 } 10045 10046 // writer 10047 synchronized (mPackages) { 10048 // Remove the parent package 10049 mPackages.remove(pkg.applicationInfo.packageName); 10050 cleanPackageDataStructuresLILPw(pkg, chatty); 10051 10052 // Remove the child packages 10053 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10054 for (int i = 0; i < childCount; i++) { 10055 PackageParser.Package childPkg = pkg.childPackages.get(i); 10056 mPackages.remove(childPkg.applicationInfo.packageName); 10057 cleanPackageDataStructuresLILPw(childPkg, chatty); 10058 } 10059 } 10060 } 10061 10062 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10063 int N = pkg.providers.size(); 10064 StringBuilder r = null; 10065 int i; 10066 for (i=0; i<N; i++) { 10067 PackageParser.Provider p = pkg.providers.get(i); 10068 mProviders.removeProvider(p); 10069 if (p.info.authority == null) { 10070 10071 /* There was another ContentProvider with this authority when 10072 * this app was installed so this authority is null, 10073 * Ignore it as we don't have to unregister the provider. 10074 */ 10075 continue; 10076 } 10077 String names[] = p.info.authority.split(";"); 10078 for (int j = 0; j < names.length; j++) { 10079 if (mProvidersByAuthority.get(names[j]) == p) { 10080 mProvidersByAuthority.remove(names[j]); 10081 if (DEBUG_REMOVE) { 10082 if (chatty) 10083 Log.d(TAG, "Unregistered content provider: " + names[j] 10084 + ", className = " + p.info.name + ", isSyncable = " 10085 + p.info.isSyncable); 10086 } 10087 } 10088 } 10089 if (DEBUG_REMOVE && chatty) { 10090 if (r == null) { 10091 r = new StringBuilder(256); 10092 } else { 10093 r.append(' '); 10094 } 10095 r.append(p.info.name); 10096 } 10097 } 10098 if (r != null) { 10099 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10100 } 10101 10102 N = pkg.services.size(); 10103 r = null; 10104 for (i=0; i<N; i++) { 10105 PackageParser.Service s = pkg.services.get(i); 10106 mServices.removeService(s); 10107 if (chatty) { 10108 if (r == null) { 10109 r = new StringBuilder(256); 10110 } else { 10111 r.append(' '); 10112 } 10113 r.append(s.info.name); 10114 } 10115 } 10116 if (r != null) { 10117 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10118 } 10119 10120 N = pkg.receivers.size(); 10121 r = null; 10122 for (i=0; i<N; i++) { 10123 PackageParser.Activity a = pkg.receivers.get(i); 10124 mReceivers.removeActivity(a, "receiver"); 10125 if (DEBUG_REMOVE && chatty) { 10126 if (r == null) { 10127 r = new StringBuilder(256); 10128 } else { 10129 r.append(' '); 10130 } 10131 r.append(a.info.name); 10132 } 10133 } 10134 if (r != null) { 10135 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10136 } 10137 10138 N = pkg.activities.size(); 10139 r = null; 10140 for (i=0; i<N; i++) { 10141 PackageParser.Activity a = pkg.activities.get(i); 10142 mActivities.removeActivity(a, "activity"); 10143 if (DEBUG_REMOVE && chatty) { 10144 if (r == null) { 10145 r = new StringBuilder(256); 10146 } else { 10147 r.append(' '); 10148 } 10149 r.append(a.info.name); 10150 } 10151 } 10152 if (r != null) { 10153 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10154 } 10155 10156 N = pkg.permissions.size(); 10157 r = null; 10158 for (i=0; i<N; i++) { 10159 PackageParser.Permission p = pkg.permissions.get(i); 10160 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10161 if (bp == null) { 10162 bp = mSettings.mPermissionTrees.get(p.info.name); 10163 } 10164 if (bp != null && bp.perm == p) { 10165 bp.perm = null; 10166 if (DEBUG_REMOVE && chatty) { 10167 if (r == null) { 10168 r = new StringBuilder(256); 10169 } else { 10170 r.append(' '); 10171 } 10172 r.append(p.info.name); 10173 } 10174 } 10175 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10176 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10177 if (appOpPkgs != null) { 10178 appOpPkgs.remove(pkg.packageName); 10179 } 10180 } 10181 } 10182 if (r != null) { 10183 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10184 } 10185 10186 N = pkg.requestedPermissions.size(); 10187 r = null; 10188 for (i=0; i<N; i++) { 10189 String perm = pkg.requestedPermissions.get(i); 10190 BasePermission bp = mSettings.mPermissions.get(perm); 10191 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10192 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10193 if (appOpPkgs != null) { 10194 appOpPkgs.remove(pkg.packageName); 10195 if (appOpPkgs.isEmpty()) { 10196 mAppOpPermissionPackages.remove(perm); 10197 } 10198 } 10199 } 10200 } 10201 if (r != null) { 10202 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10203 } 10204 10205 N = pkg.instrumentation.size(); 10206 r = null; 10207 for (i=0; i<N; i++) { 10208 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10209 mInstrumentation.remove(a.getComponentName()); 10210 if (DEBUG_REMOVE && chatty) { 10211 if (r == null) { 10212 r = new StringBuilder(256); 10213 } else { 10214 r.append(' '); 10215 } 10216 r.append(a.info.name); 10217 } 10218 } 10219 if (r != null) { 10220 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10221 } 10222 10223 r = null; 10224 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10225 // Only system apps can hold shared libraries. 10226 if (pkg.libraryNames != null) { 10227 for (i=0; i<pkg.libraryNames.size(); i++) { 10228 String name = pkg.libraryNames.get(i); 10229 SharedLibraryEntry cur = mSharedLibraries.get(name); 10230 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10231 mSharedLibraries.remove(name); 10232 if (DEBUG_REMOVE && chatty) { 10233 if (r == null) { 10234 r = new StringBuilder(256); 10235 } else { 10236 r.append(' '); 10237 } 10238 r.append(name); 10239 } 10240 } 10241 } 10242 } 10243 } 10244 if (r != null) { 10245 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10246 } 10247 } 10248 10249 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10250 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10251 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10252 return true; 10253 } 10254 } 10255 return false; 10256 } 10257 10258 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10259 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10260 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10261 10262 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10263 // Update the parent permissions 10264 updatePermissionsLPw(pkg.packageName, pkg, flags); 10265 // Update the child permissions 10266 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10267 for (int i = 0; i < childCount; i++) { 10268 PackageParser.Package childPkg = pkg.childPackages.get(i); 10269 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10270 } 10271 } 10272 10273 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10274 int flags) { 10275 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10276 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10277 } 10278 10279 private void updatePermissionsLPw(String changingPkg, 10280 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10281 // Make sure there are no dangling permission trees. 10282 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10283 while (it.hasNext()) { 10284 final BasePermission bp = it.next(); 10285 if (bp.packageSetting == null) { 10286 // We may not yet have parsed the package, so just see if 10287 // we still know about its settings. 10288 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10289 } 10290 if (bp.packageSetting == null) { 10291 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10292 + " from package " + bp.sourcePackage); 10293 it.remove(); 10294 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10295 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10296 Slog.i(TAG, "Removing old permission tree: " + bp.name 10297 + " from package " + bp.sourcePackage); 10298 flags |= UPDATE_PERMISSIONS_ALL; 10299 it.remove(); 10300 } 10301 } 10302 } 10303 10304 // Make sure all dynamic permissions have been assigned to a package, 10305 // and make sure there are no dangling permissions. 10306 it = mSettings.mPermissions.values().iterator(); 10307 while (it.hasNext()) { 10308 final BasePermission bp = it.next(); 10309 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10310 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10311 + bp.name + " pkg=" + bp.sourcePackage 10312 + " info=" + bp.pendingInfo); 10313 if (bp.packageSetting == null && bp.pendingInfo != null) { 10314 final BasePermission tree = findPermissionTreeLP(bp.name); 10315 if (tree != null && tree.perm != null) { 10316 bp.packageSetting = tree.packageSetting; 10317 bp.perm = new PackageParser.Permission(tree.perm.owner, 10318 new PermissionInfo(bp.pendingInfo)); 10319 bp.perm.info.packageName = tree.perm.info.packageName; 10320 bp.perm.info.name = bp.name; 10321 bp.uid = tree.uid; 10322 } 10323 } 10324 } 10325 if (bp.packageSetting == null) { 10326 // We may not yet have parsed the package, so just see if 10327 // we still know about its settings. 10328 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10329 } 10330 if (bp.packageSetting == null) { 10331 Slog.w(TAG, "Removing dangling permission: " + bp.name 10332 + " from package " + bp.sourcePackage); 10333 it.remove(); 10334 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10335 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10336 Slog.i(TAG, "Removing old permission: " + bp.name 10337 + " from package " + bp.sourcePackage); 10338 flags |= UPDATE_PERMISSIONS_ALL; 10339 it.remove(); 10340 } 10341 } 10342 } 10343 10344 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10345 // Now update the permissions for all packages, in particular 10346 // replace the granted permissions of the system packages. 10347 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10348 for (PackageParser.Package pkg : mPackages.values()) { 10349 if (pkg != pkgInfo) { 10350 // Only replace for packages on requested volume 10351 final String volumeUuid = getVolumeUuidForPackage(pkg); 10352 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10353 && Objects.equals(replaceVolumeUuid, volumeUuid); 10354 grantPermissionsLPw(pkg, replace, changingPkg); 10355 } 10356 } 10357 } 10358 10359 if (pkgInfo != null) { 10360 // Only replace for packages on requested volume 10361 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10362 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10363 && Objects.equals(replaceVolumeUuid, volumeUuid); 10364 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10365 } 10366 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10367 } 10368 10369 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10370 String packageOfInterest) { 10371 // IMPORTANT: There are two types of permissions: install and runtime. 10372 // Install time permissions are granted when the app is installed to 10373 // all device users and users added in the future. Runtime permissions 10374 // are granted at runtime explicitly to specific users. Normal and signature 10375 // protected permissions are install time permissions. Dangerous permissions 10376 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10377 // otherwise they are runtime permissions. This function does not manage 10378 // runtime permissions except for the case an app targeting Lollipop MR1 10379 // being upgraded to target a newer SDK, in which case dangerous permissions 10380 // are transformed from install time to runtime ones. 10381 10382 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10383 if (ps == null) { 10384 return; 10385 } 10386 10387 PermissionsState permissionsState = ps.getPermissionsState(); 10388 PermissionsState origPermissions = permissionsState; 10389 10390 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10391 10392 boolean runtimePermissionsRevoked = false; 10393 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10394 10395 boolean changedInstallPermission = false; 10396 10397 if (replace) { 10398 ps.installPermissionsFixed = false; 10399 if (!ps.isSharedUser()) { 10400 origPermissions = new PermissionsState(permissionsState); 10401 permissionsState.reset(); 10402 } else { 10403 // We need to know only about runtime permission changes since the 10404 // calling code always writes the install permissions state but 10405 // the runtime ones are written only if changed. The only cases of 10406 // changed runtime permissions here are promotion of an install to 10407 // runtime and revocation of a runtime from a shared user. 10408 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10409 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10410 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10411 runtimePermissionsRevoked = true; 10412 } 10413 } 10414 } 10415 10416 permissionsState.setGlobalGids(mGlobalGids); 10417 10418 final int N = pkg.requestedPermissions.size(); 10419 for (int i=0; i<N; i++) { 10420 final String name = pkg.requestedPermissions.get(i); 10421 final BasePermission bp = mSettings.mPermissions.get(name); 10422 10423 if (DEBUG_INSTALL) { 10424 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10425 } 10426 10427 if (bp == null || bp.packageSetting == null) { 10428 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10429 Slog.w(TAG, "Unknown permission " + name 10430 + " in package " + pkg.packageName); 10431 } 10432 continue; 10433 } 10434 10435 10436 // Limit ephemeral apps to ephemeral allowed permissions. 10437 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10438 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10439 + pkg.packageName); 10440 continue; 10441 } 10442 10443 final String perm = bp.name; 10444 boolean allowedSig = false; 10445 int grant = GRANT_DENIED; 10446 10447 // Keep track of app op permissions. 10448 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10449 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10450 if (pkgs == null) { 10451 pkgs = new ArraySet<>(); 10452 mAppOpPermissionPackages.put(bp.name, pkgs); 10453 } 10454 pkgs.add(pkg.packageName); 10455 } 10456 10457 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10458 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10459 >= Build.VERSION_CODES.M; 10460 switch (level) { 10461 case PermissionInfo.PROTECTION_NORMAL: { 10462 // For all apps normal permissions are install time ones. 10463 grant = GRANT_INSTALL; 10464 } break; 10465 10466 case PermissionInfo.PROTECTION_DANGEROUS: { 10467 // If a permission review is required for legacy apps we represent 10468 // their permissions as always granted runtime ones since we need 10469 // to keep the review required permission flag per user while an 10470 // install permission's state is shared across all users. 10471 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10472 // For legacy apps dangerous permissions are install time ones. 10473 grant = GRANT_INSTALL; 10474 } else if (origPermissions.hasInstallPermission(bp.name)) { 10475 // For legacy apps that became modern, install becomes runtime. 10476 grant = GRANT_UPGRADE; 10477 } else if (mPromoteSystemApps 10478 && isSystemApp(ps) 10479 && mExistingSystemPackages.contains(ps.name)) { 10480 // For legacy system apps, install becomes runtime. 10481 // We cannot check hasInstallPermission() for system apps since those 10482 // permissions were granted implicitly and not persisted pre-M. 10483 grant = GRANT_UPGRADE; 10484 } else { 10485 // For modern apps keep runtime permissions unchanged. 10486 grant = GRANT_RUNTIME; 10487 } 10488 } break; 10489 10490 case PermissionInfo.PROTECTION_SIGNATURE: { 10491 // For all apps signature permissions are install time ones. 10492 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10493 if (allowedSig) { 10494 grant = GRANT_INSTALL; 10495 } 10496 } break; 10497 } 10498 10499 if (DEBUG_INSTALL) { 10500 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10501 } 10502 10503 if (grant != GRANT_DENIED) { 10504 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10505 // If this is an existing, non-system package, then 10506 // we can't add any new permissions to it. 10507 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10508 // Except... if this is a permission that was added 10509 // to the platform (note: need to only do this when 10510 // updating the platform). 10511 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10512 grant = GRANT_DENIED; 10513 } 10514 } 10515 } 10516 10517 switch (grant) { 10518 case GRANT_INSTALL: { 10519 // Revoke this as runtime permission to handle the case of 10520 // a runtime permission being downgraded to an install one. 10521 // Also in permission review mode we keep dangerous permissions 10522 // for legacy apps 10523 for (int userId : UserManagerService.getInstance().getUserIds()) { 10524 if (origPermissions.getRuntimePermissionState( 10525 bp.name, userId) != null) { 10526 // Revoke the runtime permission and clear the flags. 10527 origPermissions.revokeRuntimePermission(bp, userId); 10528 origPermissions.updatePermissionFlags(bp, userId, 10529 PackageManager.MASK_PERMISSION_FLAGS, 0); 10530 // If we revoked a permission permission, we have to write. 10531 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10532 changedRuntimePermissionUserIds, userId); 10533 } 10534 } 10535 // Grant an install permission. 10536 if (permissionsState.grantInstallPermission(bp) != 10537 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10538 changedInstallPermission = true; 10539 } 10540 } break; 10541 10542 case GRANT_RUNTIME: { 10543 // Grant previously granted runtime permissions. 10544 for (int userId : UserManagerService.getInstance().getUserIds()) { 10545 PermissionState permissionState = origPermissions 10546 .getRuntimePermissionState(bp.name, userId); 10547 int flags = permissionState != null 10548 ? permissionState.getFlags() : 0; 10549 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10550 if (permissionsState.grantRuntimePermission(bp, userId) == 10551 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10552 // If we cannot put the permission as it was, we have to write. 10553 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10554 changedRuntimePermissionUserIds, userId); 10555 } 10556 // If the app supports runtime permissions no need for a review. 10557 if (mPermissionReviewRequired 10558 && appSupportsRuntimePermissions 10559 && (flags & PackageManager 10560 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10561 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10562 // Since we changed the flags, we have to write. 10563 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10564 changedRuntimePermissionUserIds, userId); 10565 } 10566 } else if (mPermissionReviewRequired 10567 && !appSupportsRuntimePermissions) { 10568 // For legacy apps that need a permission review, every new 10569 // runtime permission is granted but it is pending a review. 10570 // We also need to review only platform defined runtime 10571 // permissions as these are the only ones the platform knows 10572 // how to disable the API to simulate revocation as legacy 10573 // apps don't expect to run with revoked permissions. 10574 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10575 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10576 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10577 // We changed the flags, hence have to write. 10578 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10579 changedRuntimePermissionUserIds, userId); 10580 } 10581 } 10582 if (permissionsState.grantRuntimePermission(bp, userId) 10583 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10584 // We changed the permission, hence have to write. 10585 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10586 changedRuntimePermissionUserIds, userId); 10587 } 10588 } 10589 // Propagate the permission flags. 10590 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10591 } 10592 } break; 10593 10594 case GRANT_UPGRADE: { 10595 // Grant runtime permissions for a previously held install permission. 10596 PermissionState permissionState = origPermissions 10597 .getInstallPermissionState(bp.name); 10598 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10599 10600 if (origPermissions.revokeInstallPermission(bp) 10601 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10602 // We will be transferring the permission flags, so clear them. 10603 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10604 PackageManager.MASK_PERMISSION_FLAGS, 0); 10605 changedInstallPermission = true; 10606 } 10607 10608 // If the permission is not to be promoted to runtime we ignore it and 10609 // also its other flags as they are not applicable to install permissions. 10610 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10611 for (int userId : currentUserIds) { 10612 if (permissionsState.grantRuntimePermission(bp, userId) != 10613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10614 // Transfer the permission flags. 10615 permissionsState.updatePermissionFlags(bp, userId, 10616 flags, flags); 10617 // If we granted the permission, we have to write. 10618 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10619 changedRuntimePermissionUserIds, userId); 10620 } 10621 } 10622 } 10623 } break; 10624 10625 default: { 10626 if (packageOfInterest == null 10627 || packageOfInterest.equals(pkg.packageName)) { 10628 Slog.w(TAG, "Not granting permission " + perm 10629 + " to package " + pkg.packageName 10630 + " because it was previously installed without"); 10631 } 10632 } break; 10633 } 10634 } else { 10635 if (permissionsState.revokeInstallPermission(bp) != 10636 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10637 // Also drop the permission flags. 10638 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10639 PackageManager.MASK_PERMISSION_FLAGS, 0); 10640 changedInstallPermission = true; 10641 Slog.i(TAG, "Un-granting permission " + perm 10642 + " from package " + pkg.packageName 10643 + " (protectionLevel=" + bp.protectionLevel 10644 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10645 + ")"); 10646 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10647 // Don't print warning for app op permissions, since it is fine for them 10648 // not to be granted, there is a UI for the user to decide. 10649 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10650 Slog.w(TAG, "Not granting permission " + perm 10651 + " to package " + pkg.packageName 10652 + " (protectionLevel=" + bp.protectionLevel 10653 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10654 + ")"); 10655 } 10656 } 10657 } 10658 } 10659 10660 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10661 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10662 // This is the first that we have heard about this package, so the 10663 // permissions we have now selected are fixed until explicitly 10664 // changed. 10665 ps.installPermissionsFixed = true; 10666 } 10667 10668 // Persist the runtime permissions state for users with changes. If permissions 10669 // were revoked because no app in the shared user declares them we have to 10670 // write synchronously to avoid losing runtime permissions state. 10671 for (int userId : changedRuntimePermissionUserIds) { 10672 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10673 } 10674 } 10675 10676 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10677 boolean allowed = false; 10678 final int NP = PackageParser.NEW_PERMISSIONS.length; 10679 for (int ip=0; ip<NP; ip++) { 10680 final PackageParser.NewPermissionInfo npi 10681 = PackageParser.NEW_PERMISSIONS[ip]; 10682 if (npi.name.equals(perm) 10683 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10684 allowed = true; 10685 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10686 + pkg.packageName); 10687 break; 10688 } 10689 } 10690 return allowed; 10691 } 10692 10693 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10694 BasePermission bp, PermissionsState origPermissions) { 10695 boolean privilegedPermission = (bp.protectionLevel 10696 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10697 boolean privappPermissionsDisable = 10698 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10699 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10700 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10701 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10702 && !platformPackage && platformPermission) { 10703 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10704 .getPrivAppPermissions(pkg.packageName); 10705 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10706 if (!whitelisted) { 10707 Slog.w(TAG, "Privileged permission " + perm + " for package " 10708 + pkg.packageName + " - not in privapp-permissions whitelist"); 10709 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10710 return false; 10711 } 10712 } 10713 } 10714 boolean allowed = (compareSignatures( 10715 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10716 == PackageManager.SIGNATURE_MATCH) 10717 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10718 == PackageManager.SIGNATURE_MATCH); 10719 if (!allowed && privilegedPermission) { 10720 if (isSystemApp(pkg)) { 10721 // For updated system applications, a system permission 10722 // is granted only if it had been defined by the original application. 10723 if (pkg.isUpdatedSystemApp()) { 10724 final PackageSetting sysPs = mSettings 10725 .getDisabledSystemPkgLPr(pkg.packageName); 10726 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10727 // If the original was granted this permission, we take 10728 // that grant decision as read and propagate it to the 10729 // update. 10730 if (sysPs.isPrivileged()) { 10731 allowed = true; 10732 } 10733 } else { 10734 // The system apk may have been updated with an older 10735 // version of the one on the data partition, but which 10736 // granted a new system permission that it didn't have 10737 // before. In this case we do want to allow the app to 10738 // now get the new permission if the ancestral apk is 10739 // privileged to get it. 10740 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10741 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10742 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10743 allowed = true; 10744 break; 10745 } 10746 } 10747 } 10748 // Also if a privileged parent package on the system image or any of 10749 // its children requested a privileged permission, the updated child 10750 // packages can also get the permission. 10751 if (pkg.parentPackage != null) { 10752 final PackageSetting disabledSysParentPs = mSettings 10753 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10754 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10755 && disabledSysParentPs.isPrivileged()) { 10756 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10757 allowed = true; 10758 } else if (disabledSysParentPs.pkg.childPackages != null) { 10759 final int count = disabledSysParentPs.pkg.childPackages.size(); 10760 for (int i = 0; i < count; i++) { 10761 PackageParser.Package disabledSysChildPkg = 10762 disabledSysParentPs.pkg.childPackages.get(i); 10763 if (isPackageRequestingPermission(disabledSysChildPkg, 10764 perm)) { 10765 allowed = true; 10766 break; 10767 } 10768 } 10769 } 10770 } 10771 } 10772 } 10773 } else { 10774 allowed = isPrivilegedApp(pkg); 10775 } 10776 } 10777 } 10778 if (!allowed) { 10779 if (!allowed && (bp.protectionLevel 10780 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10781 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10782 // If this was a previously normal/dangerous permission that got moved 10783 // to a system permission as part of the runtime permission redesign, then 10784 // we still want to blindly grant it to old apps. 10785 allowed = true; 10786 } 10787 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10788 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10789 // If this permission is to be granted to the system installer and 10790 // this app is an installer, then it gets the permission. 10791 allowed = true; 10792 } 10793 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10794 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10795 // If this permission is to be granted to the system verifier and 10796 // this app is a verifier, then it gets the permission. 10797 allowed = true; 10798 } 10799 if (!allowed && (bp.protectionLevel 10800 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10801 && isSystemApp(pkg)) { 10802 // Any pre-installed system app is allowed to get this permission. 10803 allowed = true; 10804 } 10805 if (!allowed && (bp.protectionLevel 10806 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10807 // For development permissions, a development permission 10808 // is granted only if it was already granted. 10809 allowed = origPermissions.hasInstallPermission(perm); 10810 } 10811 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10812 && pkg.packageName.equals(mSetupWizardPackage)) { 10813 // If this permission is to be granted to the system setup wizard and 10814 // this app is a setup wizard, then it gets the permission. 10815 allowed = true; 10816 } 10817 } 10818 return allowed; 10819 } 10820 10821 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10822 final int permCount = pkg.requestedPermissions.size(); 10823 for (int j = 0; j < permCount; j++) { 10824 String requestedPermission = pkg.requestedPermissions.get(j); 10825 if (permission.equals(requestedPermission)) { 10826 return true; 10827 } 10828 } 10829 return false; 10830 } 10831 10832 final class ActivityIntentResolver 10833 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10834 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10835 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 10836 if (!sUserManager.exists(userId)) return null; 10837 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 10838 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 10839 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 10840 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 10841 isEphemeral, userId); 10842 } 10843 10844 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10845 int userId) { 10846 if (!sUserManager.exists(userId)) return null; 10847 mFlags = flags; 10848 return super.queryIntent(intent, resolvedType, 10849 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 10850 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 10851 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 10852 } 10853 10854 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10855 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10856 if (!sUserManager.exists(userId)) return null; 10857 if (packageActivities == null) { 10858 return null; 10859 } 10860 mFlags = flags; 10861 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10862 final boolean vislbleToEphemeral = 10863 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 10864 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 10865 final int N = packageActivities.size(); 10866 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10867 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10868 10869 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10870 for (int i = 0; i < N; ++i) { 10871 intentFilters = packageActivities.get(i).intents; 10872 if (intentFilters != null && intentFilters.size() > 0) { 10873 PackageParser.ActivityIntentInfo[] array = 10874 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10875 intentFilters.toArray(array); 10876 listCut.add(array); 10877 } 10878 } 10879 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 10880 vislbleToEphemeral, isEphemeral, listCut, userId); 10881 } 10882 10883 /** 10884 * Finds a privileged activity that matches the specified activity names. 10885 */ 10886 private PackageParser.Activity findMatchingActivity( 10887 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10888 for (PackageParser.Activity sysActivity : activityList) { 10889 if (sysActivity.info.name.equals(activityInfo.name)) { 10890 return sysActivity; 10891 } 10892 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10893 return sysActivity; 10894 } 10895 if (sysActivity.info.targetActivity != null) { 10896 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10897 return sysActivity; 10898 } 10899 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10900 return sysActivity; 10901 } 10902 } 10903 } 10904 return null; 10905 } 10906 10907 public class IterGenerator<E> { 10908 public Iterator<E> generate(ActivityIntentInfo info) { 10909 return null; 10910 } 10911 } 10912 10913 public class ActionIterGenerator extends IterGenerator<String> { 10914 @Override 10915 public Iterator<String> generate(ActivityIntentInfo info) { 10916 return info.actionsIterator(); 10917 } 10918 } 10919 10920 public class CategoriesIterGenerator extends IterGenerator<String> { 10921 @Override 10922 public Iterator<String> generate(ActivityIntentInfo info) { 10923 return info.categoriesIterator(); 10924 } 10925 } 10926 10927 public class SchemesIterGenerator extends IterGenerator<String> { 10928 @Override 10929 public Iterator<String> generate(ActivityIntentInfo info) { 10930 return info.schemesIterator(); 10931 } 10932 } 10933 10934 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10935 @Override 10936 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10937 return info.authoritiesIterator(); 10938 } 10939 } 10940 10941 /** 10942 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10943 * MODIFIED. Do not pass in a list that should not be changed. 10944 */ 10945 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10946 IterGenerator<T> generator, Iterator<T> searchIterator) { 10947 // loop through the set of actions; every one must be found in the intent filter 10948 while (searchIterator.hasNext()) { 10949 // we must have at least one filter in the list to consider a match 10950 if (intentList.size() == 0) { 10951 break; 10952 } 10953 10954 final T searchAction = searchIterator.next(); 10955 10956 // loop through the set of intent filters 10957 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10958 while (intentIter.hasNext()) { 10959 final ActivityIntentInfo intentInfo = intentIter.next(); 10960 boolean selectionFound = false; 10961 10962 // loop through the intent filter's selection criteria; at least one 10963 // of them must match the searched criteria 10964 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10965 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10966 final T intentSelection = intentSelectionIter.next(); 10967 if (intentSelection != null && intentSelection.equals(searchAction)) { 10968 selectionFound = true; 10969 break; 10970 } 10971 } 10972 10973 // the selection criteria wasn't found in this filter's set; this filter 10974 // is not a potential match 10975 if (!selectionFound) { 10976 intentIter.remove(); 10977 } 10978 } 10979 } 10980 } 10981 10982 private boolean isProtectedAction(ActivityIntentInfo filter) { 10983 final Iterator<String> actionsIter = filter.actionsIterator(); 10984 while (actionsIter != null && actionsIter.hasNext()) { 10985 final String filterAction = actionsIter.next(); 10986 if (PROTECTED_ACTIONS.contains(filterAction)) { 10987 return true; 10988 } 10989 } 10990 return false; 10991 } 10992 10993 /** 10994 * Adjusts the priority of the given intent filter according to policy. 10995 * <p> 10996 * <ul> 10997 * <li>The priority for non privileged applications is capped to '0'</li> 10998 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10999 * <li>The priority for unbundled updates to privileged applications is capped to the 11000 * priority defined on the system partition</li> 11001 * </ul> 11002 * <p> 11003 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11004 * allowed to obtain any priority on any action. 11005 */ 11006 private void adjustPriority( 11007 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11008 // nothing to do; priority is fine as-is 11009 if (intent.getPriority() <= 0) { 11010 return; 11011 } 11012 11013 final ActivityInfo activityInfo = intent.activity.info; 11014 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11015 11016 final boolean privilegedApp = 11017 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11018 if (!privilegedApp) { 11019 // non-privileged applications can never define a priority >0 11020 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11021 + " package: " + applicationInfo.packageName 11022 + " activity: " + intent.activity.className 11023 + " origPrio: " + intent.getPriority()); 11024 intent.setPriority(0); 11025 return; 11026 } 11027 11028 if (systemActivities == null) { 11029 // the system package is not disabled; we're parsing the system partition 11030 if (isProtectedAction(intent)) { 11031 if (mDeferProtectedFilters) { 11032 // We can't deal with these just yet. No component should ever obtain a 11033 // >0 priority for a protected actions, with ONE exception -- the setup 11034 // wizard. The setup wizard, however, cannot be known until we're able to 11035 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11036 // until all intent filters have been processed. Chicken, meet egg. 11037 // Let the filter temporarily have a high priority and rectify the 11038 // priorities after all system packages have been scanned. 11039 mProtectedFilters.add(intent); 11040 if (DEBUG_FILTERS) { 11041 Slog.i(TAG, "Protected action; save for later;" 11042 + " package: " + applicationInfo.packageName 11043 + " activity: " + intent.activity.className 11044 + " origPrio: " + intent.getPriority()); 11045 } 11046 return; 11047 } else { 11048 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11049 Slog.i(TAG, "No setup wizard;" 11050 + " All protected intents capped to priority 0"); 11051 } 11052 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11053 if (DEBUG_FILTERS) { 11054 Slog.i(TAG, "Found setup wizard;" 11055 + " allow priority " + intent.getPriority() + ";" 11056 + " package: " + intent.activity.info.packageName 11057 + " activity: " + intent.activity.className 11058 + " priority: " + intent.getPriority()); 11059 } 11060 // setup wizard gets whatever it wants 11061 return; 11062 } 11063 Slog.w(TAG, "Protected action; cap priority to 0;" 11064 + " package: " + intent.activity.info.packageName 11065 + " activity: " + intent.activity.className 11066 + " origPrio: " + intent.getPriority()); 11067 intent.setPriority(0); 11068 return; 11069 } 11070 } 11071 // privileged apps on the system image get whatever priority they request 11072 return; 11073 } 11074 11075 // privileged app unbundled update ... try to find the same activity 11076 final PackageParser.Activity foundActivity = 11077 findMatchingActivity(systemActivities, activityInfo); 11078 if (foundActivity == null) { 11079 // this is a new activity; it cannot obtain >0 priority 11080 if (DEBUG_FILTERS) { 11081 Slog.i(TAG, "New activity; cap priority to 0;" 11082 + " package: " + applicationInfo.packageName 11083 + " activity: " + intent.activity.className 11084 + " origPrio: " + intent.getPriority()); 11085 } 11086 intent.setPriority(0); 11087 return; 11088 } 11089 11090 // found activity, now check for filter equivalence 11091 11092 // a shallow copy is enough; we modify the list, not its contents 11093 final List<ActivityIntentInfo> intentListCopy = 11094 new ArrayList<>(foundActivity.intents); 11095 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11096 11097 // find matching action subsets 11098 final Iterator<String> actionsIterator = intent.actionsIterator(); 11099 if (actionsIterator != null) { 11100 getIntentListSubset( 11101 intentListCopy, new ActionIterGenerator(), actionsIterator); 11102 if (intentListCopy.size() == 0) { 11103 // no more intents to match; we're not equivalent 11104 if (DEBUG_FILTERS) { 11105 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11106 + " package: " + applicationInfo.packageName 11107 + " activity: " + intent.activity.className 11108 + " origPrio: " + intent.getPriority()); 11109 } 11110 intent.setPriority(0); 11111 return; 11112 } 11113 } 11114 11115 // find matching category subsets 11116 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11117 if (categoriesIterator != null) { 11118 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11119 categoriesIterator); 11120 if (intentListCopy.size() == 0) { 11121 // no more intents to match; we're not equivalent 11122 if (DEBUG_FILTERS) { 11123 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11124 + " package: " + applicationInfo.packageName 11125 + " activity: " + intent.activity.className 11126 + " origPrio: " + intent.getPriority()); 11127 } 11128 intent.setPriority(0); 11129 return; 11130 } 11131 } 11132 11133 // find matching schemes subsets 11134 final Iterator<String> schemesIterator = intent.schemesIterator(); 11135 if (schemesIterator != null) { 11136 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11137 schemesIterator); 11138 if (intentListCopy.size() == 0) { 11139 // no more intents to match; we're not equivalent 11140 if (DEBUG_FILTERS) { 11141 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11142 + " package: " + applicationInfo.packageName 11143 + " activity: " + intent.activity.className 11144 + " origPrio: " + intent.getPriority()); 11145 } 11146 intent.setPriority(0); 11147 return; 11148 } 11149 } 11150 11151 // find matching authorities subsets 11152 final Iterator<IntentFilter.AuthorityEntry> 11153 authoritiesIterator = intent.authoritiesIterator(); 11154 if (authoritiesIterator != null) { 11155 getIntentListSubset(intentListCopy, 11156 new AuthoritiesIterGenerator(), 11157 authoritiesIterator); 11158 if (intentListCopy.size() == 0) { 11159 // no more intents to match; we're not equivalent 11160 if (DEBUG_FILTERS) { 11161 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11162 + " package: " + applicationInfo.packageName 11163 + " activity: " + intent.activity.className 11164 + " origPrio: " + intent.getPriority()); 11165 } 11166 intent.setPriority(0); 11167 return; 11168 } 11169 } 11170 11171 // we found matching filter(s); app gets the max priority of all intents 11172 int cappedPriority = 0; 11173 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11174 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11175 } 11176 if (intent.getPriority() > cappedPriority) { 11177 if (DEBUG_FILTERS) { 11178 Slog.i(TAG, "Found matching filter(s);" 11179 + " cap priority to " + cappedPriority + ";" 11180 + " package: " + applicationInfo.packageName 11181 + " activity: " + intent.activity.className 11182 + " origPrio: " + intent.getPriority()); 11183 } 11184 intent.setPriority(cappedPriority); 11185 return; 11186 } 11187 // all this for nothing; the requested priority was <= what was on the system 11188 } 11189 11190 public final void addActivity(PackageParser.Activity a, String type) { 11191 mActivities.put(a.getComponentName(), a); 11192 if (DEBUG_SHOW_INFO) 11193 Log.v( 11194 TAG, " " + type + " " + 11195 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11196 if (DEBUG_SHOW_INFO) 11197 Log.v(TAG, " Class=" + a.info.name); 11198 final int NI = a.intents.size(); 11199 for (int j=0; j<NI; j++) { 11200 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11201 if ("activity".equals(type)) { 11202 final PackageSetting ps = 11203 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11204 final List<PackageParser.Activity> systemActivities = 11205 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11206 adjustPriority(systemActivities, intent); 11207 } 11208 if (DEBUG_SHOW_INFO) { 11209 Log.v(TAG, " IntentFilter:"); 11210 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11211 } 11212 if (!intent.debugCheck()) { 11213 Log.w(TAG, "==> For Activity " + a.info.name); 11214 } 11215 addFilter(intent); 11216 } 11217 } 11218 11219 public final void removeActivity(PackageParser.Activity a, String type) { 11220 mActivities.remove(a.getComponentName()); 11221 if (DEBUG_SHOW_INFO) { 11222 Log.v(TAG, " " + type + " " 11223 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11224 : a.info.name) + ":"); 11225 Log.v(TAG, " Class=" + a.info.name); 11226 } 11227 final int NI = a.intents.size(); 11228 for (int j=0; j<NI; j++) { 11229 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11230 if (DEBUG_SHOW_INFO) { 11231 Log.v(TAG, " IntentFilter:"); 11232 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11233 } 11234 removeFilter(intent); 11235 } 11236 } 11237 11238 @Override 11239 protected boolean allowFilterResult( 11240 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11241 ActivityInfo filterAi = filter.activity.info; 11242 for (int i=dest.size()-1; i>=0; i--) { 11243 ActivityInfo destAi = dest.get(i).activityInfo; 11244 if (destAi.name == filterAi.name 11245 && destAi.packageName == filterAi.packageName) { 11246 return false; 11247 } 11248 } 11249 return true; 11250 } 11251 11252 @Override 11253 protected ActivityIntentInfo[] newArray(int size) { 11254 return new ActivityIntentInfo[size]; 11255 } 11256 11257 @Override 11258 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11259 if (!sUserManager.exists(userId)) return true; 11260 PackageParser.Package p = filter.activity.owner; 11261 if (p != null) { 11262 PackageSetting ps = (PackageSetting)p.mExtras; 11263 if (ps != null) { 11264 // System apps are never considered stopped for purposes of 11265 // filtering, because there may be no way for the user to 11266 // actually re-launch them. 11267 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11268 && ps.getStopped(userId); 11269 } 11270 } 11271 return false; 11272 } 11273 11274 @Override 11275 protected boolean isPackageForFilter(String packageName, 11276 PackageParser.ActivityIntentInfo info) { 11277 return packageName.equals(info.activity.owner.packageName); 11278 } 11279 11280 @Override 11281 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11282 int match, int userId) { 11283 if (!sUserManager.exists(userId)) return null; 11284 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11285 return null; 11286 } 11287 final PackageParser.Activity activity = info.activity; 11288 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11289 if (ps == null) { 11290 return null; 11291 } 11292 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11293 ps.readUserState(userId), userId); 11294 if (ai == null) { 11295 return null; 11296 } 11297 final ResolveInfo res = new ResolveInfo(); 11298 res.activityInfo = ai; 11299 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11300 res.filter = info; 11301 } 11302 if (info != null) { 11303 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11304 } 11305 res.priority = info.getPriority(); 11306 res.preferredOrder = activity.owner.mPreferredOrder; 11307 //System.out.println("Result: " + res.activityInfo.className + 11308 // " = " + res.priority); 11309 res.match = match; 11310 res.isDefault = info.hasDefault; 11311 res.labelRes = info.labelRes; 11312 res.nonLocalizedLabel = info.nonLocalizedLabel; 11313 if (userNeedsBadging(userId)) { 11314 res.noResourceId = true; 11315 } else { 11316 res.icon = info.icon; 11317 } 11318 res.iconResourceId = info.icon; 11319 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11320 return res; 11321 } 11322 11323 @Override 11324 protected void sortResults(List<ResolveInfo> results) { 11325 Collections.sort(results, mResolvePrioritySorter); 11326 } 11327 11328 @Override 11329 protected void dumpFilter(PrintWriter out, String prefix, 11330 PackageParser.ActivityIntentInfo filter) { 11331 out.print(prefix); out.print( 11332 Integer.toHexString(System.identityHashCode(filter.activity))); 11333 out.print(' '); 11334 filter.activity.printComponentShortName(out); 11335 out.print(" filter "); 11336 out.println(Integer.toHexString(System.identityHashCode(filter))); 11337 } 11338 11339 @Override 11340 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11341 return filter.activity; 11342 } 11343 11344 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11345 PackageParser.Activity activity = (PackageParser.Activity)label; 11346 out.print(prefix); out.print( 11347 Integer.toHexString(System.identityHashCode(activity))); 11348 out.print(' '); 11349 activity.printComponentShortName(out); 11350 if (count > 1) { 11351 out.print(" ("); out.print(count); out.print(" filters)"); 11352 } 11353 out.println(); 11354 } 11355 11356 // Keys are String (activity class name), values are Activity. 11357 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11358 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11359 private int mFlags; 11360 } 11361 11362 private final class ServiceIntentResolver 11363 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11364 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11365 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11366 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11367 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11368 isEphemeral, userId); 11369 } 11370 11371 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11372 int userId) { 11373 if (!sUserManager.exists(userId)) return null; 11374 mFlags = flags; 11375 return super.queryIntent(intent, resolvedType, 11376 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11377 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11378 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11379 } 11380 11381 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11382 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11383 if (!sUserManager.exists(userId)) return null; 11384 if (packageServices == null) { 11385 return null; 11386 } 11387 mFlags = flags; 11388 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11389 final boolean vislbleToEphemeral = 11390 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11391 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11392 final int N = packageServices.size(); 11393 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11394 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11395 11396 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11397 for (int i = 0; i < N; ++i) { 11398 intentFilters = packageServices.get(i).intents; 11399 if (intentFilters != null && intentFilters.size() > 0) { 11400 PackageParser.ServiceIntentInfo[] array = 11401 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11402 intentFilters.toArray(array); 11403 listCut.add(array); 11404 } 11405 } 11406 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11407 vislbleToEphemeral, isEphemeral, listCut, userId); 11408 } 11409 11410 public final void addService(PackageParser.Service s) { 11411 mServices.put(s.getComponentName(), s); 11412 if (DEBUG_SHOW_INFO) { 11413 Log.v(TAG, " " 11414 + (s.info.nonLocalizedLabel != null 11415 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11416 Log.v(TAG, " Class=" + s.info.name); 11417 } 11418 final int NI = s.intents.size(); 11419 int j; 11420 for (j=0; j<NI; j++) { 11421 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11422 if (DEBUG_SHOW_INFO) { 11423 Log.v(TAG, " IntentFilter:"); 11424 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11425 } 11426 if (!intent.debugCheck()) { 11427 Log.w(TAG, "==> For Service " + s.info.name); 11428 } 11429 addFilter(intent); 11430 } 11431 } 11432 11433 public final void removeService(PackageParser.Service s) { 11434 mServices.remove(s.getComponentName()); 11435 if (DEBUG_SHOW_INFO) { 11436 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11437 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11438 Log.v(TAG, " Class=" + s.info.name); 11439 } 11440 final int NI = s.intents.size(); 11441 int j; 11442 for (j=0; j<NI; j++) { 11443 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11444 if (DEBUG_SHOW_INFO) { 11445 Log.v(TAG, " IntentFilter:"); 11446 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11447 } 11448 removeFilter(intent); 11449 } 11450 } 11451 11452 @Override 11453 protected boolean allowFilterResult( 11454 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11455 ServiceInfo filterSi = filter.service.info; 11456 for (int i=dest.size()-1; i>=0; i--) { 11457 ServiceInfo destAi = dest.get(i).serviceInfo; 11458 if (destAi.name == filterSi.name 11459 && destAi.packageName == filterSi.packageName) { 11460 return false; 11461 } 11462 } 11463 return true; 11464 } 11465 11466 @Override 11467 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11468 return new PackageParser.ServiceIntentInfo[size]; 11469 } 11470 11471 @Override 11472 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11473 if (!sUserManager.exists(userId)) return true; 11474 PackageParser.Package p = filter.service.owner; 11475 if (p != null) { 11476 PackageSetting ps = (PackageSetting)p.mExtras; 11477 if (ps != null) { 11478 // System apps are never considered stopped for purposes of 11479 // filtering, because there may be no way for the user to 11480 // actually re-launch them. 11481 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11482 && ps.getStopped(userId); 11483 } 11484 } 11485 return false; 11486 } 11487 11488 @Override 11489 protected boolean isPackageForFilter(String packageName, 11490 PackageParser.ServiceIntentInfo info) { 11491 return packageName.equals(info.service.owner.packageName); 11492 } 11493 11494 @Override 11495 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11496 int match, int userId) { 11497 if (!sUserManager.exists(userId)) return null; 11498 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11499 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11500 return null; 11501 } 11502 final PackageParser.Service service = info.service; 11503 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11504 if (ps == null) { 11505 return null; 11506 } 11507 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11508 ps.readUserState(userId), userId); 11509 if (si == null) { 11510 return null; 11511 } 11512 final ResolveInfo res = new ResolveInfo(); 11513 res.serviceInfo = si; 11514 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11515 res.filter = filter; 11516 } 11517 res.priority = info.getPriority(); 11518 res.preferredOrder = service.owner.mPreferredOrder; 11519 res.match = match; 11520 res.isDefault = info.hasDefault; 11521 res.labelRes = info.labelRes; 11522 res.nonLocalizedLabel = info.nonLocalizedLabel; 11523 res.icon = info.icon; 11524 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11525 return res; 11526 } 11527 11528 @Override 11529 protected void sortResults(List<ResolveInfo> results) { 11530 Collections.sort(results, mResolvePrioritySorter); 11531 } 11532 11533 @Override 11534 protected void dumpFilter(PrintWriter out, String prefix, 11535 PackageParser.ServiceIntentInfo filter) { 11536 out.print(prefix); out.print( 11537 Integer.toHexString(System.identityHashCode(filter.service))); 11538 out.print(' '); 11539 filter.service.printComponentShortName(out); 11540 out.print(" filter "); 11541 out.println(Integer.toHexString(System.identityHashCode(filter))); 11542 } 11543 11544 @Override 11545 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11546 return filter.service; 11547 } 11548 11549 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11550 PackageParser.Service service = (PackageParser.Service)label; 11551 out.print(prefix); out.print( 11552 Integer.toHexString(System.identityHashCode(service))); 11553 out.print(' '); 11554 service.printComponentShortName(out); 11555 if (count > 1) { 11556 out.print(" ("); out.print(count); out.print(" filters)"); 11557 } 11558 out.println(); 11559 } 11560 11561// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11562// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11563// final List<ResolveInfo> retList = Lists.newArrayList(); 11564// while (i.hasNext()) { 11565// final ResolveInfo resolveInfo = (ResolveInfo) i; 11566// if (isEnabledLP(resolveInfo.serviceInfo)) { 11567// retList.add(resolveInfo); 11568// } 11569// } 11570// return retList; 11571// } 11572 11573 // Keys are String (activity class name), values are Activity. 11574 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11575 = new ArrayMap<ComponentName, PackageParser.Service>(); 11576 private int mFlags; 11577 } 11578 11579 private final class ProviderIntentResolver 11580 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11581 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11582 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11583 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11584 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11585 isEphemeral, userId); 11586 } 11587 11588 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11589 int userId) { 11590 if (!sUserManager.exists(userId)) 11591 return null; 11592 mFlags = flags; 11593 return super.queryIntent(intent, resolvedType, 11594 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11595 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11596 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11597 } 11598 11599 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11600 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11601 if (!sUserManager.exists(userId)) 11602 return null; 11603 if (packageProviders == null) { 11604 return null; 11605 } 11606 mFlags = flags; 11607 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11608 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11609 final boolean vislbleToEphemeral = 11610 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11611 final int N = packageProviders.size(); 11612 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11613 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11614 11615 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11616 for (int i = 0; i < N; ++i) { 11617 intentFilters = packageProviders.get(i).intents; 11618 if (intentFilters != null && intentFilters.size() > 0) { 11619 PackageParser.ProviderIntentInfo[] array = 11620 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11621 intentFilters.toArray(array); 11622 listCut.add(array); 11623 } 11624 } 11625 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11626 vislbleToEphemeral, isEphemeral, listCut, userId); 11627 } 11628 11629 public final void addProvider(PackageParser.Provider p) { 11630 if (mProviders.containsKey(p.getComponentName())) { 11631 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11632 return; 11633 } 11634 11635 mProviders.put(p.getComponentName(), p); 11636 if (DEBUG_SHOW_INFO) { 11637 Log.v(TAG, " " 11638 + (p.info.nonLocalizedLabel != null 11639 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11640 Log.v(TAG, " Class=" + p.info.name); 11641 } 11642 final int NI = p.intents.size(); 11643 int j; 11644 for (j = 0; j < NI; j++) { 11645 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11646 if (DEBUG_SHOW_INFO) { 11647 Log.v(TAG, " IntentFilter:"); 11648 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11649 } 11650 if (!intent.debugCheck()) { 11651 Log.w(TAG, "==> For Provider " + p.info.name); 11652 } 11653 addFilter(intent); 11654 } 11655 } 11656 11657 public final void removeProvider(PackageParser.Provider p) { 11658 mProviders.remove(p.getComponentName()); 11659 if (DEBUG_SHOW_INFO) { 11660 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11661 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11662 Log.v(TAG, " Class=" + p.info.name); 11663 } 11664 final int NI = p.intents.size(); 11665 int j; 11666 for (j = 0; j < NI; j++) { 11667 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11668 if (DEBUG_SHOW_INFO) { 11669 Log.v(TAG, " IntentFilter:"); 11670 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11671 } 11672 removeFilter(intent); 11673 } 11674 } 11675 11676 @Override 11677 protected boolean allowFilterResult( 11678 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11679 ProviderInfo filterPi = filter.provider.info; 11680 for (int i = dest.size() - 1; i >= 0; i--) { 11681 ProviderInfo destPi = dest.get(i).providerInfo; 11682 if (destPi.name == filterPi.name 11683 && destPi.packageName == filterPi.packageName) { 11684 return false; 11685 } 11686 } 11687 return true; 11688 } 11689 11690 @Override 11691 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11692 return new PackageParser.ProviderIntentInfo[size]; 11693 } 11694 11695 @Override 11696 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11697 if (!sUserManager.exists(userId)) 11698 return true; 11699 PackageParser.Package p = filter.provider.owner; 11700 if (p != null) { 11701 PackageSetting ps = (PackageSetting) p.mExtras; 11702 if (ps != null) { 11703 // System apps are never considered stopped for purposes of 11704 // filtering, because there may be no way for the user to 11705 // actually re-launch them. 11706 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11707 && ps.getStopped(userId); 11708 } 11709 } 11710 return false; 11711 } 11712 11713 @Override 11714 protected boolean isPackageForFilter(String packageName, 11715 PackageParser.ProviderIntentInfo info) { 11716 return packageName.equals(info.provider.owner.packageName); 11717 } 11718 11719 @Override 11720 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11721 int match, int userId) { 11722 if (!sUserManager.exists(userId)) 11723 return null; 11724 final PackageParser.ProviderIntentInfo info = filter; 11725 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11726 return null; 11727 } 11728 final PackageParser.Provider provider = info.provider; 11729 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11730 if (ps == null) { 11731 return null; 11732 } 11733 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11734 ps.readUserState(userId), userId); 11735 if (pi == null) { 11736 return null; 11737 } 11738 final ResolveInfo res = new ResolveInfo(); 11739 res.providerInfo = pi; 11740 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11741 res.filter = filter; 11742 } 11743 res.priority = info.getPriority(); 11744 res.preferredOrder = provider.owner.mPreferredOrder; 11745 res.match = match; 11746 res.isDefault = info.hasDefault; 11747 res.labelRes = info.labelRes; 11748 res.nonLocalizedLabel = info.nonLocalizedLabel; 11749 res.icon = info.icon; 11750 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11751 return res; 11752 } 11753 11754 @Override 11755 protected void sortResults(List<ResolveInfo> results) { 11756 Collections.sort(results, mResolvePrioritySorter); 11757 } 11758 11759 @Override 11760 protected void dumpFilter(PrintWriter out, String prefix, 11761 PackageParser.ProviderIntentInfo filter) { 11762 out.print(prefix); 11763 out.print( 11764 Integer.toHexString(System.identityHashCode(filter.provider))); 11765 out.print(' '); 11766 filter.provider.printComponentShortName(out); 11767 out.print(" filter "); 11768 out.println(Integer.toHexString(System.identityHashCode(filter))); 11769 } 11770 11771 @Override 11772 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11773 return filter.provider; 11774 } 11775 11776 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11777 PackageParser.Provider provider = (PackageParser.Provider)label; 11778 out.print(prefix); out.print( 11779 Integer.toHexString(System.identityHashCode(provider))); 11780 out.print(' '); 11781 provider.printComponentShortName(out); 11782 if (count > 1) { 11783 out.print(" ("); out.print(count); out.print(" filters)"); 11784 } 11785 out.println(); 11786 } 11787 11788 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11789 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11790 private int mFlags; 11791 } 11792 11793 static final class EphemeralIntentResolver 11794 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11795 /** 11796 * The result that has the highest defined order. Ordering applies on a 11797 * per-package basis. Mapping is from package name to Pair of order and 11798 * EphemeralResolveInfo. 11799 * <p> 11800 * NOTE: This is implemented as a field variable for convenience and efficiency. 11801 * By having a field variable, we're able to track filter ordering as soon as 11802 * a non-zero order is defined. Otherwise, multiple loops across the result set 11803 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11804 * this needs to be contained entirely within {@link #filterResults()}. 11805 */ 11806 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11807 11808 @Override 11809 protected EphemeralResponse[] newArray(int size) { 11810 return new EphemeralResponse[size]; 11811 } 11812 11813 @Override 11814 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11815 return true; 11816 } 11817 11818 @Override 11819 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11820 int userId) { 11821 if (!sUserManager.exists(userId)) { 11822 return null; 11823 } 11824 final String packageName = responseObj.resolveInfo.getPackageName(); 11825 final Integer order = responseObj.getOrder(); 11826 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11827 mOrderResult.get(packageName); 11828 // ordering is enabled and this item's order isn't high enough 11829 if (lastOrderResult != null && lastOrderResult.first >= order) { 11830 return null; 11831 } 11832 final EphemeralResolveInfo res = responseObj.resolveInfo; 11833 if (order > 0) { 11834 // non-zero order, enable ordering 11835 mOrderResult.put(packageName, new Pair<>(order, res)); 11836 } 11837 return responseObj; 11838 } 11839 11840 @Override 11841 protected void filterResults(List<EphemeralResponse> results) { 11842 // only do work if ordering is enabled [most of the time it won't be] 11843 if (mOrderResult.size() == 0) { 11844 return; 11845 } 11846 int resultSize = results.size(); 11847 for (int i = 0; i < resultSize; i++) { 11848 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11849 final String packageName = info.getPackageName(); 11850 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11851 if (savedInfo == null) { 11852 // package doesn't having ordering 11853 continue; 11854 } 11855 if (savedInfo.second == info) { 11856 // circled back to the highest ordered item; remove from order list 11857 mOrderResult.remove(savedInfo); 11858 if (mOrderResult.size() == 0) { 11859 // no more ordered items 11860 break; 11861 } 11862 continue; 11863 } 11864 // item has a worse order, remove it from the result list 11865 results.remove(i); 11866 resultSize--; 11867 i--; 11868 } 11869 } 11870 } 11871 11872 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11873 new Comparator<ResolveInfo>() { 11874 public int compare(ResolveInfo r1, ResolveInfo r2) { 11875 int v1 = r1.priority; 11876 int v2 = r2.priority; 11877 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11878 if (v1 != v2) { 11879 return (v1 > v2) ? -1 : 1; 11880 } 11881 v1 = r1.preferredOrder; 11882 v2 = r2.preferredOrder; 11883 if (v1 != v2) { 11884 return (v1 > v2) ? -1 : 1; 11885 } 11886 if (r1.isDefault != r2.isDefault) { 11887 return r1.isDefault ? -1 : 1; 11888 } 11889 v1 = r1.match; 11890 v2 = r2.match; 11891 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11892 if (v1 != v2) { 11893 return (v1 > v2) ? -1 : 1; 11894 } 11895 if (r1.system != r2.system) { 11896 return r1.system ? -1 : 1; 11897 } 11898 if (r1.activityInfo != null) { 11899 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11900 } 11901 if (r1.serviceInfo != null) { 11902 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11903 } 11904 if (r1.providerInfo != null) { 11905 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11906 } 11907 return 0; 11908 } 11909 }; 11910 11911 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11912 new Comparator<ProviderInfo>() { 11913 public int compare(ProviderInfo p1, ProviderInfo p2) { 11914 final int v1 = p1.initOrder; 11915 final int v2 = p2.initOrder; 11916 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11917 } 11918 }; 11919 11920 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11921 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11922 final int[] userIds) { 11923 mHandler.post(new Runnable() { 11924 @Override 11925 public void run() { 11926 try { 11927 final IActivityManager am = ActivityManager.getService(); 11928 if (am == null) return; 11929 final int[] resolvedUserIds; 11930 if (userIds == null) { 11931 resolvedUserIds = am.getRunningUserIds(); 11932 } else { 11933 resolvedUserIds = userIds; 11934 } 11935 for (int id : resolvedUserIds) { 11936 final Intent intent = new Intent(action, 11937 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11938 if (extras != null) { 11939 intent.putExtras(extras); 11940 } 11941 if (targetPkg != null) { 11942 intent.setPackage(targetPkg); 11943 } 11944 // Modify the UID when posting to other users 11945 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11946 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11947 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11948 intent.putExtra(Intent.EXTRA_UID, uid); 11949 } 11950 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11951 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11952 if (DEBUG_BROADCASTS) { 11953 RuntimeException here = new RuntimeException("here"); 11954 here.fillInStackTrace(); 11955 Slog.d(TAG, "Sending to user " + id + ": " 11956 + intent.toShortString(false, true, false, false) 11957 + " " + intent.getExtras(), here); 11958 } 11959 am.broadcastIntent(null, intent, null, finishedReceiver, 11960 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11961 null, finishedReceiver != null, false, id); 11962 } 11963 } catch (RemoteException ex) { 11964 } 11965 } 11966 }); 11967 } 11968 11969 /** 11970 * Check if the external storage media is available. This is true if there 11971 * is a mounted external storage medium or if the external storage is 11972 * emulated. 11973 */ 11974 private boolean isExternalMediaAvailable() { 11975 return mMediaMounted || Environment.isExternalStorageEmulated(); 11976 } 11977 11978 @Override 11979 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11980 // writer 11981 synchronized (mPackages) { 11982 if (!isExternalMediaAvailable()) { 11983 // If the external storage is no longer mounted at this point, 11984 // the caller may not have been able to delete all of this 11985 // packages files and can not delete any more. Bail. 11986 return null; 11987 } 11988 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11989 if (lastPackage != null) { 11990 pkgs.remove(lastPackage); 11991 } 11992 if (pkgs.size() > 0) { 11993 return pkgs.get(0); 11994 } 11995 } 11996 return null; 11997 } 11998 11999 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12000 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12001 userId, andCode ? 1 : 0, packageName); 12002 if (mSystemReady) { 12003 msg.sendToTarget(); 12004 } else { 12005 if (mPostSystemReadyMessages == null) { 12006 mPostSystemReadyMessages = new ArrayList<>(); 12007 } 12008 mPostSystemReadyMessages.add(msg); 12009 } 12010 } 12011 12012 void startCleaningPackages() { 12013 // reader 12014 if (!isExternalMediaAvailable()) { 12015 return; 12016 } 12017 synchronized (mPackages) { 12018 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12019 return; 12020 } 12021 } 12022 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12023 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12024 IActivityManager am = ActivityManager.getService(); 12025 if (am != null) { 12026 try { 12027 am.startService(null, intent, null, mContext.getOpPackageName(), 12028 UserHandle.USER_SYSTEM); 12029 } catch (RemoteException e) { 12030 } 12031 } 12032 } 12033 12034 @Override 12035 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12036 int installFlags, String installerPackageName, int userId) { 12037 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12038 12039 final int callingUid = Binder.getCallingUid(); 12040 enforceCrossUserPermission(callingUid, userId, 12041 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12042 12043 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12044 try { 12045 if (observer != null) { 12046 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12047 } 12048 } catch (RemoteException re) { 12049 } 12050 return; 12051 } 12052 12053 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12054 installFlags |= PackageManager.INSTALL_FROM_ADB; 12055 12056 } else { 12057 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12058 // about installerPackageName. 12059 12060 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12061 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12062 } 12063 12064 UserHandle user; 12065 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12066 user = UserHandle.ALL; 12067 } else { 12068 user = new UserHandle(userId); 12069 } 12070 12071 // Only system components can circumvent runtime permissions when installing. 12072 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12073 && mContext.checkCallingOrSelfPermission(Manifest.permission 12074 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12075 throw new SecurityException("You need the " 12076 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12077 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12078 } 12079 12080 final File originFile = new File(originPath); 12081 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12082 12083 final Message msg = mHandler.obtainMessage(INIT_COPY); 12084 final VerificationInfo verificationInfo = new VerificationInfo( 12085 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12086 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12087 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12088 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12089 null /*certificates*/); 12090 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12091 msg.obj = params; 12092 12093 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12094 System.identityHashCode(msg.obj)); 12095 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12096 System.identityHashCode(msg.obj)); 12097 12098 mHandler.sendMessage(msg); 12099 } 12100 12101 void installStage(String packageName, File stagedDir, String stagedCid, 12102 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12103 String installerPackageName, int installerUid, UserHandle user, 12104 Certificate[][] certificates) { 12105 if (DEBUG_EPHEMERAL) { 12106 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12107 Slog.d(TAG, "Ephemeral install of " + packageName); 12108 } 12109 } 12110 final VerificationInfo verificationInfo = new VerificationInfo( 12111 sessionParams.originatingUri, sessionParams.referrerUri, 12112 sessionParams.originatingUid, installerUid); 12113 12114 final OriginInfo origin; 12115 if (stagedDir != null) { 12116 origin = OriginInfo.fromStagedFile(stagedDir); 12117 } else { 12118 origin = OriginInfo.fromStagedContainer(stagedCid); 12119 } 12120 12121 final Message msg = mHandler.obtainMessage(INIT_COPY); 12122 final InstallParams params = new InstallParams(origin, null, observer, 12123 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12124 verificationInfo, user, sessionParams.abiOverride, 12125 sessionParams.grantedRuntimePermissions, certificates); 12126 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12127 msg.obj = params; 12128 12129 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12130 System.identityHashCode(msg.obj)); 12131 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12132 System.identityHashCode(msg.obj)); 12133 12134 mHandler.sendMessage(msg); 12135 } 12136 12137 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12138 int userId) { 12139 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12140 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12141 } 12142 12143 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12144 int appId, int... userIds) { 12145 if (ArrayUtils.isEmpty(userIds)) { 12146 return; 12147 } 12148 Bundle extras = new Bundle(1); 12149 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12150 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12151 12152 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12153 packageName, extras, 0, null, null, userIds); 12154 if (isSystem) { 12155 mHandler.post(() -> { 12156 for (int userId : userIds) { 12157 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12158 } 12159 } 12160 ); 12161 } 12162 } 12163 12164 /** 12165 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12166 * automatically without needing an explicit launch. 12167 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12168 */ 12169 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12170 // If user is not running, the app didn't miss any broadcast 12171 if (!mUserManagerInternal.isUserRunning(userId)) { 12172 return; 12173 } 12174 final IActivityManager am = ActivityManager.getService(); 12175 try { 12176 // Deliver LOCKED_BOOT_COMPLETED first 12177 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12178 .setPackage(packageName); 12179 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12180 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12181 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12182 12183 // Deliver BOOT_COMPLETED only if user is unlocked 12184 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12185 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12186 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12187 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12188 } 12189 } catch (RemoteException e) { 12190 throw e.rethrowFromSystemServer(); 12191 } 12192 } 12193 12194 @Override 12195 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12196 int userId) { 12197 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12198 PackageSetting pkgSetting; 12199 final int uid = Binder.getCallingUid(); 12200 enforceCrossUserPermission(uid, userId, 12201 true /* requireFullPermission */, true /* checkShell */, 12202 "setApplicationHiddenSetting for user " + userId); 12203 12204 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12205 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12206 return false; 12207 } 12208 12209 long callingId = Binder.clearCallingIdentity(); 12210 try { 12211 boolean sendAdded = false; 12212 boolean sendRemoved = false; 12213 // writer 12214 synchronized (mPackages) { 12215 pkgSetting = mSettings.mPackages.get(packageName); 12216 if (pkgSetting == null) { 12217 return false; 12218 } 12219 // Do not allow "android" is being disabled 12220 if ("android".equals(packageName)) { 12221 Slog.w(TAG, "Cannot hide package: android"); 12222 return false; 12223 } 12224 // Only allow protected packages to hide themselves. 12225 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12226 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12227 Slog.w(TAG, "Not hiding protected package: " + packageName); 12228 return false; 12229 } 12230 12231 if (pkgSetting.getHidden(userId) != hidden) { 12232 pkgSetting.setHidden(hidden, userId); 12233 mSettings.writePackageRestrictionsLPr(userId); 12234 if (hidden) { 12235 sendRemoved = true; 12236 } else { 12237 sendAdded = true; 12238 } 12239 } 12240 } 12241 if (sendAdded) { 12242 sendPackageAddedForUser(packageName, pkgSetting, userId); 12243 return true; 12244 } 12245 if (sendRemoved) { 12246 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12247 "hiding pkg"); 12248 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12249 return true; 12250 } 12251 } finally { 12252 Binder.restoreCallingIdentity(callingId); 12253 } 12254 return false; 12255 } 12256 12257 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12258 int userId) { 12259 final PackageRemovedInfo info = new PackageRemovedInfo(); 12260 info.removedPackage = packageName; 12261 info.removedUsers = new int[] {userId}; 12262 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12263 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12264 } 12265 12266 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12267 if (pkgList.length > 0) { 12268 Bundle extras = new Bundle(1); 12269 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12270 12271 sendPackageBroadcast( 12272 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12273 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12274 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12275 new int[] {userId}); 12276 } 12277 } 12278 12279 /** 12280 * Returns true if application is not found or there was an error. Otherwise it returns 12281 * the hidden state of the package for the given user. 12282 */ 12283 @Override 12284 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12285 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12286 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12287 true /* requireFullPermission */, false /* checkShell */, 12288 "getApplicationHidden for user " + userId); 12289 PackageSetting pkgSetting; 12290 long callingId = Binder.clearCallingIdentity(); 12291 try { 12292 // writer 12293 synchronized (mPackages) { 12294 pkgSetting = mSettings.mPackages.get(packageName); 12295 if (pkgSetting == null) { 12296 return true; 12297 } 12298 return pkgSetting.getHidden(userId); 12299 } 12300 } finally { 12301 Binder.restoreCallingIdentity(callingId); 12302 } 12303 } 12304 12305 /** 12306 * @hide 12307 */ 12308 @Override 12309 public int installExistingPackageAsUser(String packageName, int userId) { 12310 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12311 null); 12312 PackageSetting pkgSetting; 12313 final int uid = Binder.getCallingUid(); 12314 enforceCrossUserPermission(uid, userId, 12315 true /* requireFullPermission */, true /* checkShell */, 12316 "installExistingPackage for user " + userId); 12317 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12318 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12319 } 12320 12321 long callingId = Binder.clearCallingIdentity(); 12322 try { 12323 boolean installed = false; 12324 12325 // writer 12326 synchronized (mPackages) { 12327 pkgSetting = mSettings.mPackages.get(packageName); 12328 if (pkgSetting == null) { 12329 return PackageManager.INSTALL_FAILED_INVALID_URI; 12330 } 12331 if (!pkgSetting.getInstalled(userId)) { 12332 pkgSetting.setInstalled(true, userId); 12333 pkgSetting.setHidden(false, userId); 12334 mSettings.writePackageRestrictionsLPr(userId); 12335 installed = true; 12336 } 12337 } 12338 12339 if (installed) { 12340 if (pkgSetting.pkg != null) { 12341 synchronized (mInstallLock) { 12342 // We don't need to freeze for a brand new install 12343 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12344 } 12345 } 12346 sendPackageAddedForUser(packageName, pkgSetting, userId); 12347 } 12348 } finally { 12349 Binder.restoreCallingIdentity(callingId); 12350 } 12351 12352 return PackageManager.INSTALL_SUCCEEDED; 12353 } 12354 12355 boolean isUserRestricted(int userId, String restrictionKey) { 12356 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12357 if (restrictions.getBoolean(restrictionKey, false)) { 12358 Log.w(TAG, "User is restricted: " + restrictionKey); 12359 return true; 12360 } 12361 return false; 12362 } 12363 12364 @Override 12365 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12366 int userId) { 12367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12368 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12369 true /* requireFullPermission */, true /* checkShell */, 12370 "setPackagesSuspended for user " + userId); 12371 12372 if (ArrayUtils.isEmpty(packageNames)) { 12373 return packageNames; 12374 } 12375 12376 // List of package names for whom the suspended state has changed. 12377 List<String> changedPackages = new ArrayList<>(packageNames.length); 12378 // List of package names for whom the suspended state is not set as requested in this 12379 // method. 12380 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12381 long callingId = Binder.clearCallingIdentity(); 12382 try { 12383 for (int i = 0; i < packageNames.length; i++) { 12384 String packageName = packageNames[i]; 12385 boolean changed = false; 12386 final int appId; 12387 synchronized (mPackages) { 12388 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12389 if (pkgSetting == null) { 12390 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12391 + "\". Skipping suspending/un-suspending."); 12392 unactionedPackages.add(packageName); 12393 continue; 12394 } 12395 appId = pkgSetting.appId; 12396 if (pkgSetting.getSuspended(userId) != suspended) { 12397 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12398 unactionedPackages.add(packageName); 12399 continue; 12400 } 12401 pkgSetting.setSuspended(suspended, userId); 12402 mSettings.writePackageRestrictionsLPr(userId); 12403 changed = true; 12404 changedPackages.add(packageName); 12405 } 12406 } 12407 12408 if (changed && suspended) { 12409 killApplication(packageName, UserHandle.getUid(userId, appId), 12410 "suspending package"); 12411 } 12412 } 12413 } finally { 12414 Binder.restoreCallingIdentity(callingId); 12415 } 12416 12417 if (!changedPackages.isEmpty()) { 12418 sendPackagesSuspendedForUser(changedPackages.toArray( 12419 new String[changedPackages.size()]), userId, suspended); 12420 } 12421 12422 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12423 } 12424 12425 @Override 12426 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12427 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12428 true /* requireFullPermission */, false /* checkShell */, 12429 "isPackageSuspendedForUser for user " + userId); 12430 synchronized (mPackages) { 12431 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12432 if (pkgSetting == null) { 12433 throw new IllegalArgumentException("Unknown target package: " + packageName); 12434 } 12435 return pkgSetting.getSuspended(userId); 12436 } 12437 } 12438 12439 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12440 if (isPackageDeviceAdmin(packageName, userId)) { 12441 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12442 + "\": has an active device admin"); 12443 return false; 12444 } 12445 12446 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12447 if (packageName.equals(activeLauncherPackageName)) { 12448 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12449 + "\": contains the active launcher"); 12450 return false; 12451 } 12452 12453 if (packageName.equals(mRequiredInstallerPackage)) { 12454 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12455 + "\": required for package installation"); 12456 return false; 12457 } 12458 12459 if (packageName.equals(mRequiredUninstallerPackage)) { 12460 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12461 + "\": required for package uninstallation"); 12462 return false; 12463 } 12464 12465 if (packageName.equals(mRequiredVerifierPackage)) { 12466 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12467 + "\": required for package verification"); 12468 return false; 12469 } 12470 12471 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12472 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12473 + "\": is the default dialer"); 12474 return false; 12475 } 12476 12477 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12478 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12479 + "\": protected package"); 12480 return false; 12481 } 12482 12483 return true; 12484 } 12485 12486 private String getActiveLauncherPackageName(int userId) { 12487 Intent intent = new Intent(Intent.ACTION_MAIN); 12488 intent.addCategory(Intent.CATEGORY_HOME); 12489 ResolveInfo resolveInfo = resolveIntent( 12490 intent, 12491 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12492 PackageManager.MATCH_DEFAULT_ONLY, 12493 userId); 12494 12495 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12496 } 12497 12498 private String getDefaultDialerPackageName(int userId) { 12499 synchronized (mPackages) { 12500 return mSettings.getDefaultDialerPackageNameLPw(userId); 12501 } 12502 } 12503 12504 @Override 12505 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12506 mContext.enforceCallingOrSelfPermission( 12507 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12508 "Only package verification agents can verify applications"); 12509 12510 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12511 final PackageVerificationResponse response = new PackageVerificationResponse( 12512 verificationCode, Binder.getCallingUid()); 12513 msg.arg1 = id; 12514 msg.obj = response; 12515 mHandler.sendMessage(msg); 12516 } 12517 12518 @Override 12519 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12520 long millisecondsToDelay) { 12521 mContext.enforceCallingOrSelfPermission( 12522 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12523 "Only package verification agents can extend verification timeouts"); 12524 12525 final PackageVerificationState state = mPendingVerification.get(id); 12526 final PackageVerificationResponse response = new PackageVerificationResponse( 12527 verificationCodeAtTimeout, Binder.getCallingUid()); 12528 12529 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12530 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12531 } 12532 if (millisecondsToDelay < 0) { 12533 millisecondsToDelay = 0; 12534 } 12535 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12536 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12537 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12538 } 12539 12540 if ((state != null) && !state.timeoutExtended()) { 12541 state.extendTimeout(); 12542 12543 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12544 msg.arg1 = id; 12545 msg.obj = response; 12546 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12547 } 12548 } 12549 12550 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12551 int verificationCode, UserHandle user) { 12552 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12553 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12554 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12555 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12556 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12557 12558 mContext.sendBroadcastAsUser(intent, user, 12559 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12560 } 12561 12562 private ComponentName matchComponentForVerifier(String packageName, 12563 List<ResolveInfo> receivers) { 12564 ActivityInfo targetReceiver = null; 12565 12566 final int NR = receivers.size(); 12567 for (int i = 0; i < NR; i++) { 12568 final ResolveInfo info = receivers.get(i); 12569 if (info.activityInfo == null) { 12570 continue; 12571 } 12572 12573 if (packageName.equals(info.activityInfo.packageName)) { 12574 targetReceiver = info.activityInfo; 12575 break; 12576 } 12577 } 12578 12579 if (targetReceiver == null) { 12580 return null; 12581 } 12582 12583 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12584 } 12585 12586 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12587 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12588 if (pkgInfo.verifiers.length == 0) { 12589 return null; 12590 } 12591 12592 final int N = pkgInfo.verifiers.length; 12593 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12594 for (int i = 0; i < N; i++) { 12595 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12596 12597 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12598 receivers); 12599 if (comp == null) { 12600 continue; 12601 } 12602 12603 final int verifierUid = getUidForVerifier(verifierInfo); 12604 if (verifierUid == -1) { 12605 continue; 12606 } 12607 12608 if (DEBUG_VERIFY) { 12609 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12610 + " with the correct signature"); 12611 } 12612 sufficientVerifiers.add(comp); 12613 verificationState.addSufficientVerifier(verifierUid); 12614 } 12615 12616 return sufficientVerifiers; 12617 } 12618 12619 private int getUidForVerifier(VerifierInfo verifierInfo) { 12620 synchronized (mPackages) { 12621 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12622 if (pkg == null) { 12623 return -1; 12624 } else if (pkg.mSignatures.length != 1) { 12625 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12626 + " has more than one signature; ignoring"); 12627 return -1; 12628 } 12629 12630 /* 12631 * If the public key of the package's signature does not match 12632 * our expected public key, then this is a different package and 12633 * we should skip. 12634 */ 12635 12636 final byte[] expectedPublicKey; 12637 try { 12638 final Signature verifierSig = pkg.mSignatures[0]; 12639 final PublicKey publicKey = verifierSig.getPublicKey(); 12640 expectedPublicKey = publicKey.getEncoded(); 12641 } catch (CertificateException e) { 12642 return -1; 12643 } 12644 12645 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12646 12647 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12648 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12649 + " does not have the expected public key; ignoring"); 12650 return -1; 12651 } 12652 12653 return pkg.applicationInfo.uid; 12654 } 12655 } 12656 12657 @Override 12658 public void finishPackageInstall(int token, boolean didLaunch) { 12659 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12660 12661 if (DEBUG_INSTALL) { 12662 Slog.v(TAG, "BM finishing package install for " + token); 12663 } 12664 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12665 12666 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12667 mHandler.sendMessage(msg); 12668 } 12669 12670 /** 12671 * Get the verification agent timeout. 12672 * 12673 * @return verification timeout in milliseconds 12674 */ 12675 private long getVerificationTimeout() { 12676 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12677 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12678 DEFAULT_VERIFICATION_TIMEOUT); 12679 } 12680 12681 /** 12682 * Get the default verification agent response code. 12683 * 12684 * @return default verification response code 12685 */ 12686 private int getDefaultVerificationResponse() { 12687 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12688 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12689 DEFAULT_VERIFICATION_RESPONSE); 12690 } 12691 12692 /** 12693 * Check whether or not package verification has been enabled. 12694 * 12695 * @return true if verification should be performed 12696 */ 12697 private boolean isVerificationEnabled(int userId, int installFlags) { 12698 if (!DEFAULT_VERIFY_ENABLE) { 12699 return false; 12700 } 12701 // Ephemeral apps don't get the full verification treatment 12702 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12703 if (DEBUG_EPHEMERAL) { 12704 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12705 } 12706 return false; 12707 } 12708 12709 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12710 12711 // Check if installing from ADB 12712 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12713 // Do not run verification in a test harness environment 12714 if (ActivityManager.isRunningInTestHarness()) { 12715 return false; 12716 } 12717 if (ensureVerifyAppsEnabled) { 12718 return true; 12719 } 12720 // Check if the developer does not want package verification for ADB installs 12721 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12722 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12723 return false; 12724 } 12725 } 12726 12727 if (ensureVerifyAppsEnabled) { 12728 return true; 12729 } 12730 12731 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12732 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12733 } 12734 12735 @Override 12736 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12737 throws RemoteException { 12738 mContext.enforceCallingOrSelfPermission( 12739 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12740 "Only intentfilter verification agents can verify applications"); 12741 12742 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12743 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12744 Binder.getCallingUid(), verificationCode, failedDomains); 12745 msg.arg1 = id; 12746 msg.obj = response; 12747 mHandler.sendMessage(msg); 12748 } 12749 12750 @Override 12751 public int getIntentVerificationStatus(String packageName, int userId) { 12752 synchronized (mPackages) { 12753 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12754 } 12755 } 12756 12757 @Override 12758 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12759 mContext.enforceCallingOrSelfPermission( 12760 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12761 12762 boolean result = false; 12763 synchronized (mPackages) { 12764 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12765 } 12766 if (result) { 12767 scheduleWritePackageRestrictionsLocked(userId); 12768 } 12769 return result; 12770 } 12771 12772 @Override 12773 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12774 String packageName) { 12775 synchronized (mPackages) { 12776 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12777 } 12778 } 12779 12780 @Override 12781 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12782 if (TextUtils.isEmpty(packageName)) { 12783 return ParceledListSlice.emptyList(); 12784 } 12785 synchronized (mPackages) { 12786 PackageParser.Package pkg = mPackages.get(packageName); 12787 if (pkg == null || pkg.activities == null) { 12788 return ParceledListSlice.emptyList(); 12789 } 12790 final int count = pkg.activities.size(); 12791 ArrayList<IntentFilter> result = new ArrayList<>(); 12792 for (int n=0; n<count; n++) { 12793 PackageParser.Activity activity = pkg.activities.get(n); 12794 if (activity.intents != null && activity.intents.size() > 0) { 12795 result.addAll(activity.intents); 12796 } 12797 } 12798 return new ParceledListSlice<>(result); 12799 } 12800 } 12801 12802 @Override 12803 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12804 mContext.enforceCallingOrSelfPermission( 12805 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12806 12807 synchronized (mPackages) { 12808 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12809 if (packageName != null) { 12810 result |= updateIntentVerificationStatus(packageName, 12811 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12812 userId); 12813 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12814 packageName, userId); 12815 } 12816 return result; 12817 } 12818 } 12819 12820 @Override 12821 public String getDefaultBrowserPackageName(int userId) { 12822 synchronized (mPackages) { 12823 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12824 } 12825 } 12826 12827 /** 12828 * Get the "allow unknown sources" setting. 12829 * 12830 * @return the current "allow unknown sources" setting 12831 */ 12832 private int getUnknownSourcesSettings() { 12833 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12834 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12835 -1); 12836 } 12837 12838 @Override 12839 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12840 final int uid = Binder.getCallingUid(); 12841 // writer 12842 synchronized (mPackages) { 12843 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12844 if (targetPackageSetting == null) { 12845 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12846 } 12847 12848 PackageSetting installerPackageSetting; 12849 if (installerPackageName != null) { 12850 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12851 if (installerPackageSetting == null) { 12852 throw new IllegalArgumentException("Unknown installer package: " 12853 + installerPackageName); 12854 } 12855 } else { 12856 installerPackageSetting = null; 12857 } 12858 12859 Signature[] callerSignature; 12860 Object obj = mSettings.getUserIdLPr(uid); 12861 if (obj != null) { 12862 if (obj instanceof SharedUserSetting) { 12863 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12864 } else if (obj instanceof PackageSetting) { 12865 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12866 } else { 12867 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12868 } 12869 } else { 12870 throw new SecurityException("Unknown calling UID: " + uid); 12871 } 12872 12873 // Verify: can't set installerPackageName to a package that is 12874 // not signed with the same cert as the caller. 12875 if (installerPackageSetting != null) { 12876 if (compareSignatures(callerSignature, 12877 installerPackageSetting.signatures.mSignatures) 12878 != PackageManager.SIGNATURE_MATCH) { 12879 throw new SecurityException( 12880 "Caller does not have same cert as new installer package " 12881 + installerPackageName); 12882 } 12883 } 12884 12885 // Verify: if target already has an installer package, it must 12886 // be signed with the same cert as the caller. 12887 if (targetPackageSetting.installerPackageName != null) { 12888 PackageSetting setting = mSettings.mPackages.get( 12889 targetPackageSetting.installerPackageName); 12890 // If the currently set package isn't valid, then it's always 12891 // okay to change it. 12892 if (setting != null) { 12893 if (compareSignatures(callerSignature, 12894 setting.signatures.mSignatures) 12895 != PackageManager.SIGNATURE_MATCH) { 12896 throw new SecurityException( 12897 "Caller does not have same cert as old installer package " 12898 + targetPackageSetting.installerPackageName); 12899 } 12900 } 12901 } 12902 12903 // Okay! 12904 targetPackageSetting.installerPackageName = installerPackageName; 12905 if (installerPackageName != null) { 12906 mSettings.mInstallerPackages.add(installerPackageName); 12907 } 12908 scheduleWriteSettingsLocked(); 12909 } 12910 } 12911 12912 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12913 // Queue up an async operation since the package installation may take a little while. 12914 mHandler.post(new Runnable() { 12915 public void run() { 12916 mHandler.removeCallbacks(this); 12917 // Result object to be returned 12918 PackageInstalledInfo res = new PackageInstalledInfo(); 12919 res.setReturnCode(currentStatus); 12920 res.uid = -1; 12921 res.pkg = null; 12922 res.removedInfo = null; 12923 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12924 args.doPreInstall(res.returnCode); 12925 synchronized (mInstallLock) { 12926 installPackageTracedLI(args, res); 12927 } 12928 args.doPostInstall(res.returnCode, res.uid); 12929 } 12930 12931 // A restore should be performed at this point if (a) the install 12932 // succeeded, (b) the operation is not an update, and (c) the new 12933 // package has not opted out of backup participation. 12934 final boolean update = res.removedInfo != null 12935 && res.removedInfo.removedPackage != null; 12936 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12937 boolean doRestore = !update 12938 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12939 12940 // Set up the post-install work request bookkeeping. This will be used 12941 // and cleaned up by the post-install event handling regardless of whether 12942 // there's a restore pass performed. Token values are >= 1. 12943 int token; 12944 if (mNextInstallToken < 0) mNextInstallToken = 1; 12945 token = mNextInstallToken++; 12946 12947 PostInstallData data = new PostInstallData(args, res); 12948 mRunningInstalls.put(token, data); 12949 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12950 12951 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12952 // Pass responsibility to the Backup Manager. It will perform a 12953 // restore if appropriate, then pass responsibility back to the 12954 // Package Manager to run the post-install observer callbacks 12955 // and broadcasts. 12956 IBackupManager bm = IBackupManager.Stub.asInterface( 12957 ServiceManager.getService(Context.BACKUP_SERVICE)); 12958 if (bm != null) { 12959 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12960 + " to BM for possible restore"); 12961 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12962 try { 12963 // TODO: http://b/22388012 12964 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12965 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12966 } else { 12967 doRestore = false; 12968 } 12969 } catch (RemoteException e) { 12970 // can't happen; the backup manager is local 12971 } catch (Exception e) { 12972 Slog.e(TAG, "Exception trying to enqueue restore", e); 12973 doRestore = false; 12974 } 12975 } else { 12976 Slog.e(TAG, "Backup Manager not found!"); 12977 doRestore = false; 12978 } 12979 } 12980 12981 if (!doRestore) { 12982 // No restore possible, or the Backup Manager was mysteriously not 12983 // available -- just fire the post-install work request directly. 12984 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12985 12986 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12987 12988 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12989 mHandler.sendMessage(msg); 12990 } 12991 } 12992 }); 12993 } 12994 12995 /** 12996 * Callback from PackageSettings whenever an app is first transitioned out of the 12997 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12998 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12999 * here whether the app is the target of an ongoing install, and only send the 13000 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13001 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13002 * handling. 13003 */ 13004 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13005 // Serialize this with the rest of the install-process message chain. In the 13006 // restore-at-install case, this Runnable will necessarily run before the 13007 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13008 // are coherent. In the non-restore case, the app has already completed install 13009 // and been launched through some other means, so it is not in a problematic 13010 // state for observers to see the FIRST_LAUNCH signal. 13011 mHandler.post(new Runnable() { 13012 @Override 13013 public void run() { 13014 for (int i = 0; i < mRunningInstalls.size(); i++) { 13015 final PostInstallData data = mRunningInstalls.valueAt(i); 13016 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13017 continue; 13018 } 13019 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13020 // right package; but is it for the right user? 13021 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13022 if (userId == data.res.newUsers[uIndex]) { 13023 if (DEBUG_BACKUP) { 13024 Slog.i(TAG, "Package " + pkgName 13025 + " being restored so deferring FIRST_LAUNCH"); 13026 } 13027 return; 13028 } 13029 } 13030 } 13031 } 13032 // didn't find it, so not being restored 13033 if (DEBUG_BACKUP) { 13034 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13035 } 13036 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13037 } 13038 }); 13039 } 13040 13041 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13042 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13043 installerPkg, null, userIds); 13044 } 13045 13046 private abstract class HandlerParams { 13047 private static final int MAX_RETRIES = 4; 13048 13049 /** 13050 * Number of times startCopy() has been attempted and had a non-fatal 13051 * error. 13052 */ 13053 private int mRetries = 0; 13054 13055 /** User handle for the user requesting the information or installation. */ 13056 private final UserHandle mUser; 13057 String traceMethod; 13058 int traceCookie; 13059 13060 HandlerParams(UserHandle user) { 13061 mUser = user; 13062 } 13063 13064 UserHandle getUser() { 13065 return mUser; 13066 } 13067 13068 HandlerParams setTraceMethod(String traceMethod) { 13069 this.traceMethod = traceMethod; 13070 return this; 13071 } 13072 13073 HandlerParams setTraceCookie(int traceCookie) { 13074 this.traceCookie = traceCookie; 13075 return this; 13076 } 13077 13078 final boolean startCopy() { 13079 boolean res; 13080 try { 13081 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13082 13083 if (++mRetries > MAX_RETRIES) { 13084 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13085 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13086 handleServiceError(); 13087 return false; 13088 } else { 13089 handleStartCopy(); 13090 res = true; 13091 } 13092 } catch (RemoteException e) { 13093 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13094 mHandler.sendEmptyMessage(MCS_RECONNECT); 13095 res = false; 13096 } 13097 handleReturnCode(); 13098 return res; 13099 } 13100 13101 final void serviceError() { 13102 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13103 handleServiceError(); 13104 handleReturnCode(); 13105 } 13106 13107 abstract void handleStartCopy() throws RemoteException; 13108 abstract void handleServiceError(); 13109 abstract void handleReturnCode(); 13110 } 13111 13112 class MeasureParams extends HandlerParams { 13113 private final PackageStats mStats; 13114 private boolean mSuccess; 13115 13116 private final IPackageStatsObserver mObserver; 13117 13118 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 13119 super(new UserHandle(stats.userHandle)); 13120 mObserver = observer; 13121 mStats = stats; 13122 } 13123 13124 @Override 13125 public String toString() { 13126 return "MeasureParams{" 13127 + Integer.toHexString(System.identityHashCode(this)) 13128 + " " + mStats.packageName + "}"; 13129 } 13130 13131 @Override 13132 void handleStartCopy() throws RemoteException { 13133 synchronized (mInstallLock) { 13134 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 13135 } 13136 13137 if (mSuccess) { 13138 boolean mounted = false; 13139 try { 13140 final String status = Environment.getExternalStorageState(); 13141 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13142 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13143 } catch (Exception e) { 13144 } 13145 13146 if (mounted) { 13147 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13148 13149 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13150 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13151 13152 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13153 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13154 13155 // Always subtract cache size, since it's a subdirectory 13156 mStats.externalDataSize -= mStats.externalCacheSize; 13157 13158 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13159 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13160 13161 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13162 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13163 } 13164 } 13165 } 13166 13167 @Override 13168 void handleReturnCode() { 13169 if (mObserver != null) { 13170 try { 13171 mObserver.onGetStatsCompleted(mStats, mSuccess); 13172 } catch (RemoteException e) { 13173 Slog.i(TAG, "Observer no longer exists."); 13174 } 13175 } 13176 } 13177 13178 @Override 13179 void handleServiceError() { 13180 Slog.e(TAG, "Could not measure application " + mStats.packageName 13181 + " external storage"); 13182 } 13183 } 13184 13185 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13186 throws RemoteException { 13187 long result = 0; 13188 for (File path : paths) { 13189 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13190 } 13191 return result; 13192 } 13193 13194 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13195 for (File path : paths) { 13196 try { 13197 mcs.clearDirectory(path.getAbsolutePath()); 13198 } catch (RemoteException e) { 13199 } 13200 } 13201 } 13202 13203 static class OriginInfo { 13204 /** 13205 * Location where install is coming from, before it has been 13206 * copied/renamed into place. This could be a single monolithic APK 13207 * file, or a cluster directory. This location may be untrusted. 13208 */ 13209 final File file; 13210 final String cid; 13211 13212 /** 13213 * Flag indicating that {@link #file} or {@link #cid} has already been 13214 * staged, meaning downstream users don't need to defensively copy the 13215 * contents. 13216 */ 13217 final boolean staged; 13218 13219 /** 13220 * Flag indicating that {@link #file} or {@link #cid} is an already 13221 * installed app that is being moved. 13222 */ 13223 final boolean existing; 13224 13225 final String resolvedPath; 13226 final File resolvedFile; 13227 13228 static OriginInfo fromNothing() { 13229 return new OriginInfo(null, null, false, false); 13230 } 13231 13232 static OriginInfo fromUntrustedFile(File file) { 13233 return new OriginInfo(file, null, false, false); 13234 } 13235 13236 static OriginInfo fromExistingFile(File file) { 13237 return new OriginInfo(file, null, false, true); 13238 } 13239 13240 static OriginInfo fromStagedFile(File file) { 13241 return new OriginInfo(file, null, true, false); 13242 } 13243 13244 static OriginInfo fromStagedContainer(String cid) { 13245 return new OriginInfo(null, cid, true, false); 13246 } 13247 13248 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13249 this.file = file; 13250 this.cid = cid; 13251 this.staged = staged; 13252 this.existing = existing; 13253 13254 if (cid != null) { 13255 resolvedPath = PackageHelper.getSdDir(cid); 13256 resolvedFile = new File(resolvedPath); 13257 } else if (file != null) { 13258 resolvedPath = file.getAbsolutePath(); 13259 resolvedFile = file; 13260 } else { 13261 resolvedPath = null; 13262 resolvedFile = null; 13263 } 13264 } 13265 } 13266 13267 static class MoveInfo { 13268 final int moveId; 13269 final String fromUuid; 13270 final String toUuid; 13271 final String packageName; 13272 final String dataAppName; 13273 final int appId; 13274 final String seinfo; 13275 final int targetSdkVersion; 13276 13277 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13278 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13279 this.moveId = moveId; 13280 this.fromUuid = fromUuid; 13281 this.toUuid = toUuid; 13282 this.packageName = packageName; 13283 this.dataAppName = dataAppName; 13284 this.appId = appId; 13285 this.seinfo = seinfo; 13286 this.targetSdkVersion = targetSdkVersion; 13287 } 13288 } 13289 13290 static class VerificationInfo { 13291 /** A constant used to indicate that a uid value is not present. */ 13292 public static final int NO_UID = -1; 13293 13294 /** URI referencing where the package was downloaded from. */ 13295 final Uri originatingUri; 13296 13297 /** HTTP referrer URI associated with the originatingURI. */ 13298 final Uri referrer; 13299 13300 /** UID of the application that the install request originated from. */ 13301 final int originatingUid; 13302 13303 /** UID of application requesting the install */ 13304 final int installerUid; 13305 13306 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13307 this.originatingUri = originatingUri; 13308 this.referrer = referrer; 13309 this.originatingUid = originatingUid; 13310 this.installerUid = installerUid; 13311 } 13312 } 13313 13314 class InstallParams extends HandlerParams { 13315 final OriginInfo origin; 13316 final MoveInfo move; 13317 final IPackageInstallObserver2 observer; 13318 int installFlags; 13319 final String installerPackageName; 13320 final String volumeUuid; 13321 private InstallArgs mArgs; 13322 private int mRet; 13323 final String packageAbiOverride; 13324 final String[] grantedRuntimePermissions; 13325 final VerificationInfo verificationInfo; 13326 final Certificate[][] certificates; 13327 13328 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13329 int installFlags, String installerPackageName, String volumeUuid, 13330 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13331 String[] grantedPermissions, Certificate[][] certificates) { 13332 super(user); 13333 this.origin = origin; 13334 this.move = move; 13335 this.observer = observer; 13336 this.installFlags = installFlags; 13337 this.installerPackageName = installerPackageName; 13338 this.volumeUuid = volumeUuid; 13339 this.verificationInfo = verificationInfo; 13340 this.packageAbiOverride = packageAbiOverride; 13341 this.grantedRuntimePermissions = grantedPermissions; 13342 this.certificates = certificates; 13343 } 13344 13345 @Override 13346 public String toString() { 13347 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13348 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13349 } 13350 13351 private int installLocationPolicy(PackageInfoLite pkgLite) { 13352 String packageName = pkgLite.packageName; 13353 int installLocation = pkgLite.installLocation; 13354 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13355 // reader 13356 synchronized (mPackages) { 13357 // Currently installed package which the new package is attempting to replace or 13358 // null if no such package is installed. 13359 PackageParser.Package installedPkg = mPackages.get(packageName); 13360 // Package which currently owns the data which the new package will own if installed. 13361 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13362 // will be null whereas dataOwnerPkg will contain information about the package 13363 // which was uninstalled while keeping its data. 13364 PackageParser.Package dataOwnerPkg = installedPkg; 13365 if (dataOwnerPkg == null) { 13366 PackageSetting ps = mSettings.mPackages.get(packageName); 13367 if (ps != null) { 13368 dataOwnerPkg = ps.pkg; 13369 } 13370 } 13371 13372 if (dataOwnerPkg != null) { 13373 // If installed, the package will get access to data left on the device by its 13374 // predecessor. As a security measure, this is permited only if this is not a 13375 // version downgrade or if the predecessor package is marked as debuggable and 13376 // a downgrade is explicitly requested. 13377 // 13378 // On debuggable platform builds, downgrades are permitted even for 13379 // non-debuggable packages to make testing easier. Debuggable platform builds do 13380 // not offer security guarantees and thus it's OK to disable some security 13381 // mechanisms to make debugging/testing easier on those builds. However, even on 13382 // debuggable builds downgrades of packages are permitted only if requested via 13383 // installFlags. This is because we aim to keep the behavior of debuggable 13384 // platform builds as close as possible to the behavior of non-debuggable 13385 // platform builds. 13386 final boolean downgradeRequested = 13387 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13388 final boolean packageDebuggable = 13389 (dataOwnerPkg.applicationInfo.flags 13390 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13391 final boolean downgradePermitted = 13392 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13393 if (!downgradePermitted) { 13394 try { 13395 checkDowngrade(dataOwnerPkg, pkgLite); 13396 } catch (PackageManagerException e) { 13397 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13398 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13399 } 13400 } 13401 } 13402 13403 if (installedPkg != null) { 13404 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13405 // Check for updated system application. 13406 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13407 if (onSd) { 13408 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13409 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13410 } 13411 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13412 } else { 13413 if (onSd) { 13414 // Install flag overrides everything. 13415 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13416 } 13417 // If current upgrade specifies particular preference 13418 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13419 // Application explicitly specified internal. 13420 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13421 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13422 // App explictly prefers external. Let policy decide 13423 } else { 13424 // Prefer previous location 13425 if (isExternal(installedPkg)) { 13426 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13427 } 13428 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13429 } 13430 } 13431 } else { 13432 // Invalid install. Return error code 13433 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13434 } 13435 } 13436 } 13437 // All the special cases have been taken care of. 13438 // Return result based on recommended install location. 13439 if (onSd) { 13440 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13441 } 13442 return pkgLite.recommendedInstallLocation; 13443 } 13444 13445 /* 13446 * Invoke remote method to get package information and install 13447 * location values. Override install location based on default 13448 * policy if needed and then create install arguments based 13449 * on the install location. 13450 */ 13451 public void handleStartCopy() throws RemoteException { 13452 int ret = PackageManager.INSTALL_SUCCEEDED; 13453 13454 // If we're already staged, we've firmly committed to an install location 13455 if (origin.staged) { 13456 if (origin.file != null) { 13457 installFlags |= PackageManager.INSTALL_INTERNAL; 13458 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13459 } else if (origin.cid != null) { 13460 installFlags |= PackageManager.INSTALL_EXTERNAL; 13461 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13462 } else { 13463 throw new IllegalStateException("Invalid stage location"); 13464 } 13465 } 13466 13467 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13468 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13469 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13470 PackageInfoLite pkgLite = null; 13471 13472 if (onInt && onSd) { 13473 // Check if both bits are set. 13474 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13475 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13476 } else if (onSd && ephemeral) { 13477 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13478 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13479 } else { 13480 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13481 packageAbiOverride); 13482 13483 if (DEBUG_EPHEMERAL && ephemeral) { 13484 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13485 } 13486 13487 /* 13488 * If we have too little free space, try to free cache 13489 * before giving up. 13490 */ 13491 if (!origin.staged && pkgLite.recommendedInstallLocation 13492 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13493 // TODO: focus freeing disk space on the target device 13494 final StorageManager storage = StorageManager.from(mContext); 13495 final long lowThreshold = storage.getStorageLowBytes( 13496 Environment.getDataDirectory()); 13497 13498 final long sizeBytes = mContainerService.calculateInstalledSize( 13499 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13500 13501 try { 13502 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13503 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13504 installFlags, packageAbiOverride); 13505 } catch (InstallerException e) { 13506 Slog.w(TAG, "Failed to free cache", e); 13507 } 13508 13509 /* 13510 * The cache free must have deleted the file we 13511 * downloaded to install. 13512 * 13513 * TODO: fix the "freeCache" call to not delete 13514 * the file we care about. 13515 */ 13516 if (pkgLite.recommendedInstallLocation 13517 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13518 pkgLite.recommendedInstallLocation 13519 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13520 } 13521 } 13522 } 13523 13524 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13525 int loc = pkgLite.recommendedInstallLocation; 13526 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13527 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13528 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13529 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13530 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13531 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13532 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13533 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13534 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13535 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13536 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13537 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13538 } else { 13539 // Override with defaults if needed. 13540 loc = installLocationPolicy(pkgLite); 13541 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13542 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13543 } else if (!onSd && !onInt) { 13544 // Override install location with flags 13545 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13546 // Set the flag to install on external media. 13547 installFlags |= PackageManager.INSTALL_EXTERNAL; 13548 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13549 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13550 if (DEBUG_EPHEMERAL) { 13551 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13552 } 13553 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13554 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13555 |PackageManager.INSTALL_INTERNAL); 13556 } else { 13557 // Make sure the flag for installing on external 13558 // media is unset 13559 installFlags |= PackageManager.INSTALL_INTERNAL; 13560 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13561 } 13562 } 13563 } 13564 } 13565 13566 final InstallArgs args = createInstallArgs(this); 13567 mArgs = args; 13568 13569 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13570 // TODO: http://b/22976637 13571 // Apps installed for "all" users use the device owner to verify the app 13572 UserHandle verifierUser = getUser(); 13573 if (verifierUser == UserHandle.ALL) { 13574 verifierUser = UserHandle.SYSTEM; 13575 } 13576 13577 /* 13578 * Determine if we have any installed package verifiers. If we 13579 * do, then we'll defer to them to verify the packages. 13580 */ 13581 final int requiredUid = mRequiredVerifierPackage == null ? -1 13582 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13583 verifierUser.getIdentifier()); 13584 if (!origin.existing && requiredUid != -1 13585 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13586 final Intent verification = new Intent( 13587 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13588 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13589 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13590 PACKAGE_MIME_TYPE); 13591 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13592 13593 // Query all live verifiers based on current user state 13594 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13595 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13596 13597 if (DEBUG_VERIFY) { 13598 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13599 + verification.toString() + " with " + pkgLite.verifiers.length 13600 + " optional verifiers"); 13601 } 13602 13603 final int verificationId = mPendingVerificationToken++; 13604 13605 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13606 13607 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13608 installerPackageName); 13609 13610 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13611 installFlags); 13612 13613 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13614 pkgLite.packageName); 13615 13616 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13617 pkgLite.versionCode); 13618 13619 if (verificationInfo != null) { 13620 if (verificationInfo.originatingUri != null) { 13621 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13622 verificationInfo.originatingUri); 13623 } 13624 if (verificationInfo.referrer != null) { 13625 verification.putExtra(Intent.EXTRA_REFERRER, 13626 verificationInfo.referrer); 13627 } 13628 if (verificationInfo.originatingUid >= 0) { 13629 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13630 verificationInfo.originatingUid); 13631 } 13632 if (verificationInfo.installerUid >= 0) { 13633 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13634 verificationInfo.installerUid); 13635 } 13636 } 13637 13638 final PackageVerificationState verificationState = new PackageVerificationState( 13639 requiredUid, args); 13640 13641 mPendingVerification.append(verificationId, verificationState); 13642 13643 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13644 receivers, verificationState); 13645 13646 /* 13647 * If any sufficient verifiers were listed in the package 13648 * manifest, attempt to ask them. 13649 */ 13650 if (sufficientVerifiers != null) { 13651 final int N = sufficientVerifiers.size(); 13652 if (N == 0) { 13653 Slog.i(TAG, "Additional verifiers required, but none installed."); 13654 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13655 } else { 13656 for (int i = 0; i < N; i++) { 13657 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13658 13659 final Intent sufficientIntent = new Intent(verification); 13660 sufficientIntent.setComponent(verifierComponent); 13661 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13662 } 13663 } 13664 } 13665 13666 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13667 mRequiredVerifierPackage, receivers); 13668 if (ret == PackageManager.INSTALL_SUCCEEDED 13669 && mRequiredVerifierPackage != null) { 13670 Trace.asyncTraceBegin( 13671 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13672 /* 13673 * Send the intent to the required verification agent, 13674 * but only start the verification timeout after the 13675 * target BroadcastReceivers have run. 13676 */ 13677 verification.setComponent(requiredVerifierComponent); 13678 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13679 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13680 new BroadcastReceiver() { 13681 @Override 13682 public void onReceive(Context context, Intent intent) { 13683 final Message msg = mHandler 13684 .obtainMessage(CHECK_PENDING_VERIFICATION); 13685 msg.arg1 = verificationId; 13686 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13687 } 13688 }, null, 0, null, null); 13689 13690 /* 13691 * We don't want the copy to proceed until verification 13692 * succeeds, so null out this field. 13693 */ 13694 mArgs = null; 13695 } 13696 } else { 13697 /* 13698 * No package verification is enabled, so immediately start 13699 * the remote call to initiate copy using temporary file. 13700 */ 13701 ret = args.copyApk(mContainerService, true); 13702 } 13703 } 13704 13705 mRet = ret; 13706 } 13707 13708 @Override 13709 void handleReturnCode() { 13710 // If mArgs is null, then MCS couldn't be reached. When it 13711 // reconnects, it will try again to install. At that point, this 13712 // will succeed. 13713 if (mArgs != null) { 13714 processPendingInstall(mArgs, mRet); 13715 } 13716 } 13717 13718 @Override 13719 void handleServiceError() { 13720 mArgs = createInstallArgs(this); 13721 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13722 } 13723 13724 public boolean isForwardLocked() { 13725 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13726 } 13727 } 13728 13729 /** 13730 * Used during creation of InstallArgs 13731 * 13732 * @param installFlags package installation flags 13733 * @return true if should be installed on external storage 13734 */ 13735 private static boolean installOnExternalAsec(int installFlags) { 13736 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13737 return false; 13738 } 13739 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13740 return true; 13741 } 13742 return false; 13743 } 13744 13745 /** 13746 * Used during creation of InstallArgs 13747 * 13748 * @param installFlags package installation flags 13749 * @return true if should be installed as forward locked 13750 */ 13751 private static boolean installForwardLocked(int installFlags) { 13752 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13753 } 13754 13755 private InstallArgs createInstallArgs(InstallParams params) { 13756 if (params.move != null) { 13757 return new MoveInstallArgs(params); 13758 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13759 return new AsecInstallArgs(params); 13760 } else { 13761 return new FileInstallArgs(params); 13762 } 13763 } 13764 13765 /** 13766 * Create args that describe an existing installed package. Typically used 13767 * when cleaning up old installs, or used as a move source. 13768 */ 13769 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13770 String resourcePath, String[] instructionSets) { 13771 final boolean isInAsec; 13772 if (installOnExternalAsec(installFlags)) { 13773 /* Apps on SD card are always in ASEC containers. */ 13774 isInAsec = true; 13775 } else if (installForwardLocked(installFlags) 13776 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13777 /* 13778 * Forward-locked apps are only in ASEC containers if they're the 13779 * new style 13780 */ 13781 isInAsec = true; 13782 } else { 13783 isInAsec = false; 13784 } 13785 13786 if (isInAsec) { 13787 return new AsecInstallArgs(codePath, instructionSets, 13788 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13789 } else { 13790 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13791 } 13792 } 13793 13794 static abstract class InstallArgs { 13795 /** @see InstallParams#origin */ 13796 final OriginInfo origin; 13797 /** @see InstallParams#move */ 13798 final MoveInfo move; 13799 13800 final IPackageInstallObserver2 observer; 13801 // Always refers to PackageManager flags only 13802 final int installFlags; 13803 final String installerPackageName; 13804 final String volumeUuid; 13805 final UserHandle user; 13806 final String abiOverride; 13807 final String[] installGrantPermissions; 13808 /** If non-null, drop an async trace when the install completes */ 13809 final String traceMethod; 13810 final int traceCookie; 13811 final Certificate[][] certificates; 13812 13813 // The list of instruction sets supported by this app. This is currently 13814 // only used during the rmdex() phase to clean up resources. We can get rid of this 13815 // if we move dex files under the common app path. 13816 /* nullable */ String[] instructionSets; 13817 13818 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13819 int installFlags, String installerPackageName, String volumeUuid, 13820 UserHandle user, String[] instructionSets, 13821 String abiOverride, String[] installGrantPermissions, 13822 String traceMethod, int traceCookie, Certificate[][] certificates) { 13823 this.origin = origin; 13824 this.move = move; 13825 this.installFlags = installFlags; 13826 this.observer = observer; 13827 this.installerPackageName = installerPackageName; 13828 this.volumeUuid = volumeUuid; 13829 this.user = user; 13830 this.instructionSets = instructionSets; 13831 this.abiOverride = abiOverride; 13832 this.installGrantPermissions = installGrantPermissions; 13833 this.traceMethod = traceMethod; 13834 this.traceCookie = traceCookie; 13835 this.certificates = certificates; 13836 } 13837 13838 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13839 abstract int doPreInstall(int status); 13840 13841 /** 13842 * Rename package into final resting place. All paths on the given 13843 * scanned package should be updated to reflect the rename. 13844 */ 13845 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13846 abstract int doPostInstall(int status, int uid); 13847 13848 /** @see PackageSettingBase#codePathString */ 13849 abstract String getCodePath(); 13850 /** @see PackageSettingBase#resourcePathString */ 13851 abstract String getResourcePath(); 13852 13853 // Need installer lock especially for dex file removal. 13854 abstract void cleanUpResourcesLI(); 13855 abstract boolean doPostDeleteLI(boolean delete); 13856 13857 /** 13858 * Called before the source arguments are copied. This is used mostly 13859 * for MoveParams when it needs to read the source file to put it in the 13860 * destination. 13861 */ 13862 int doPreCopy() { 13863 return PackageManager.INSTALL_SUCCEEDED; 13864 } 13865 13866 /** 13867 * Called after the source arguments are copied. This is used mostly for 13868 * MoveParams when it needs to read the source file to put it in the 13869 * destination. 13870 */ 13871 int doPostCopy(int uid) { 13872 return PackageManager.INSTALL_SUCCEEDED; 13873 } 13874 13875 protected boolean isFwdLocked() { 13876 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13877 } 13878 13879 protected boolean isExternalAsec() { 13880 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13881 } 13882 13883 protected boolean isEphemeral() { 13884 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13885 } 13886 13887 UserHandle getUser() { 13888 return user; 13889 } 13890 } 13891 13892 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13893 if (!allCodePaths.isEmpty()) { 13894 if (instructionSets == null) { 13895 throw new IllegalStateException("instructionSet == null"); 13896 } 13897 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13898 for (String codePath : allCodePaths) { 13899 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13900 try { 13901 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13902 } catch (InstallerException ignored) { 13903 } 13904 } 13905 } 13906 } 13907 } 13908 13909 /** 13910 * Logic to handle installation of non-ASEC applications, including copying 13911 * and renaming logic. 13912 */ 13913 class FileInstallArgs extends InstallArgs { 13914 private File codeFile; 13915 private File resourceFile; 13916 13917 // Example topology: 13918 // /data/app/com.example/base.apk 13919 // /data/app/com.example/split_foo.apk 13920 // /data/app/com.example/lib/arm/libfoo.so 13921 // /data/app/com.example/lib/arm64/libfoo.so 13922 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13923 13924 /** New install */ 13925 FileInstallArgs(InstallParams params) { 13926 super(params.origin, params.move, params.observer, params.installFlags, 13927 params.installerPackageName, params.volumeUuid, 13928 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13929 params.grantedRuntimePermissions, 13930 params.traceMethod, params.traceCookie, params.certificates); 13931 if (isFwdLocked()) { 13932 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13933 } 13934 } 13935 13936 /** Existing install */ 13937 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13938 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13939 null, null, null, 0, null /*certificates*/); 13940 this.codeFile = (codePath != null) ? new File(codePath) : null; 13941 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13942 } 13943 13944 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13945 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13946 try { 13947 return doCopyApk(imcs, temp); 13948 } finally { 13949 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13950 } 13951 } 13952 13953 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13954 if (origin.staged) { 13955 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13956 codeFile = origin.file; 13957 resourceFile = origin.file; 13958 return PackageManager.INSTALL_SUCCEEDED; 13959 } 13960 13961 try { 13962 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13963 final File tempDir = 13964 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13965 codeFile = tempDir; 13966 resourceFile = tempDir; 13967 } catch (IOException e) { 13968 Slog.w(TAG, "Failed to create copy file: " + e); 13969 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13970 } 13971 13972 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13973 @Override 13974 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13975 if (!FileUtils.isValidExtFilename(name)) { 13976 throw new IllegalArgumentException("Invalid filename: " + name); 13977 } 13978 try { 13979 final File file = new File(codeFile, name); 13980 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13981 O_RDWR | O_CREAT, 0644); 13982 Os.chmod(file.getAbsolutePath(), 0644); 13983 return new ParcelFileDescriptor(fd); 13984 } catch (ErrnoException e) { 13985 throw new RemoteException("Failed to open: " + e.getMessage()); 13986 } 13987 } 13988 }; 13989 13990 int ret = PackageManager.INSTALL_SUCCEEDED; 13991 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13992 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13993 Slog.e(TAG, "Failed to copy package"); 13994 return ret; 13995 } 13996 13997 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13998 NativeLibraryHelper.Handle handle = null; 13999 try { 14000 handle = NativeLibraryHelper.Handle.create(codeFile); 14001 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14002 abiOverride); 14003 } catch (IOException e) { 14004 Slog.e(TAG, "Copying native libraries failed", e); 14005 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14006 } finally { 14007 IoUtils.closeQuietly(handle); 14008 } 14009 14010 return ret; 14011 } 14012 14013 int doPreInstall(int status) { 14014 if (status != PackageManager.INSTALL_SUCCEEDED) { 14015 cleanUp(); 14016 } 14017 return status; 14018 } 14019 14020 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14021 if (status != PackageManager.INSTALL_SUCCEEDED) { 14022 cleanUp(); 14023 return false; 14024 } 14025 14026 final File targetDir = codeFile.getParentFile(); 14027 final File beforeCodeFile = codeFile; 14028 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14029 14030 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14031 try { 14032 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14033 } catch (ErrnoException e) { 14034 Slog.w(TAG, "Failed to rename", e); 14035 return false; 14036 } 14037 14038 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14039 Slog.w(TAG, "Failed to restorecon"); 14040 return false; 14041 } 14042 14043 // Reflect the rename internally 14044 codeFile = afterCodeFile; 14045 resourceFile = afterCodeFile; 14046 14047 // Reflect the rename in scanned details 14048 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14049 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14050 afterCodeFile, pkg.baseCodePath)); 14051 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14052 afterCodeFile, pkg.splitCodePaths)); 14053 14054 // Reflect the rename in app info 14055 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14056 pkg.setApplicationInfoCodePath(pkg.codePath); 14057 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14058 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14059 pkg.setApplicationInfoResourcePath(pkg.codePath); 14060 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14061 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14062 14063 return true; 14064 } 14065 14066 int doPostInstall(int status, int uid) { 14067 if (status != PackageManager.INSTALL_SUCCEEDED) { 14068 cleanUp(); 14069 } 14070 return status; 14071 } 14072 14073 @Override 14074 String getCodePath() { 14075 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14076 } 14077 14078 @Override 14079 String getResourcePath() { 14080 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14081 } 14082 14083 private boolean cleanUp() { 14084 if (codeFile == null || !codeFile.exists()) { 14085 return false; 14086 } 14087 14088 removeCodePathLI(codeFile); 14089 14090 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14091 resourceFile.delete(); 14092 } 14093 14094 return true; 14095 } 14096 14097 void cleanUpResourcesLI() { 14098 // Try enumerating all code paths before deleting 14099 List<String> allCodePaths = Collections.EMPTY_LIST; 14100 if (codeFile != null && codeFile.exists()) { 14101 try { 14102 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14103 allCodePaths = pkg.getAllCodePaths(); 14104 } catch (PackageParserException e) { 14105 // Ignored; we tried our best 14106 } 14107 } 14108 14109 cleanUp(); 14110 removeDexFiles(allCodePaths, instructionSets); 14111 } 14112 14113 boolean doPostDeleteLI(boolean delete) { 14114 // XXX err, shouldn't we respect the delete flag? 14115 cleanUpResourcesLI(); 14116 return true; 14117 } 14118 } 14119 14120 private boolean isAsecExternal(String cid) { 14121 final String asecPath = PackageHelper.getSdFilesystem(cid); 14122 return !asecPath.startsWith(mAsecInternalPath); 14123 } 14124 14125 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 14126 PackageManagerException { 14127 if (copyRet < 0) { 14128 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 14129 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 14130 throw new PackageManagerException(copyRet, message); 14131 } 14132 } 14133 } 14134 14135 /** 14136 * Extract the StorageManagerService "container ID" from the full code path of an 14137 * .apk. 14138 */ 14139 static String cidFromCodePath(String fullCodePath) { 14140 int eidx = fullCodePath.lastIndexOf("/"); 14141 String subStr1 = fullCodePath.substring(0, eidx); 14142 int sidx = subStr1.lastIndexOf("/"); 14143 return subStr1.substring(sidx+1, eidx); 14144 } 14145 14146 /** 14147 * Logic to handle installation of ASEC applications, including copying and 14148 * renaming logic. 14149 */ 14150 class AsecInstallArgs extends InstallArgs { 14151 static final String RES_FILE_NAME = "pkg.apk"; 14152 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14153 14154 String cid; 14155 String packagePath; 14156 String resourcePath; 14157 14158 /** New install */ 14159 AsecInstallArgs(InstallParams params) { 14160 super(params.origin, params.move, params.observer, params.installFlags, 14161 params.installerPackageName, params.volumeUuid, 14162 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14163 params.grantedRuntimePermissions, 14164 params.traceMethod, params.traceCookie, params.certificates); 14165 } 14166 14167 /** Existing install */ 14168 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14169 boolean isExternal, boolean isForwardLocked) { 14170 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14171 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14172 instructionSets, null, null, null, 0, null /*certificates*/); 14173 // Hackily pretend we're still looking at a full code path 14174 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14175 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14176 } 14177 14178 // Extract cid from fullCodePath 14179 int eidx = fullCodePath.lastIndexOf("/"); 14180 String subStr1 = fullCodePath.substring(0, eidx); 14181 int sidx = subStr1.lastIndexOf("/"); 14182 cid = subStr1.substring(sidx+1, eidx); 14183 setMountPath(subStr1); 14184 } 14185 14186 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14187 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14188 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14189 instructionSets, null, null, null, 0, null /*certificates*/); 14190 this.cid = cid; 14191 setMountPath(PackageHelper.getSdDir(cid)); 14192 } 14193 14194 void createCopyFile() { 14195 cid = mInstallerService.allocateExternalStageCidLegacy(); 14196 } 14197 14198 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14199 if (origin.staged && origin.cid != null) { 14200 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14201 cid = origin.cid; 14202 setMountPath(PackageHelper.getSdDir(cid)); 14203 return PackageManager.INSTALL_SUCCEEDED; 14204 } 14205 14206 if (temp) { 14207 createCopyFile(); 14208 } else { 14209 /* 14210 * Pre-emptively destroy the container since it's destroyed if 14211 * copying fails due to it existing anyway. 14212 */ 14213 PackageHelper.destroySdDir(cid); 14214 } 14215 14216 final String newMountPath = imcs.copyPackageToContainer( 14217 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14218 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14219 14220 if (newMountPath != null) { 14221 setMountPath(newMountPath); 14222 return PackageManager.INSTALL_SUCCEEDED; 14223 } else { 14224 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14225 } 14226 } 14227 14228 @Override 14229 String getCodePath() { 14230 return packagePath; 14231 } 14232 14233 @Override 14234 String getResourcePath() { 14235 return resourcePath; 14236 } 14237 14238 int doPreInstall(int status) { 14239 if (status != PackageManager.INSTALL_SUCCEEDED) { 14240 // Destroy container 14241 PackageHelper.destroySdDir(cid); 14242 } else { 14243 boolean mounted = PackageHelper.isContainerMounted(cid); 14244 if (!mounted) { 14245 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14246 Process.SYSTEM_UID); 14247 if (newMountPath != null) { 14248 setMountPath(newMountPath); 14249 } else { 14250 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14251 } 14252 } 14253 } 14254 return status; 14255 } 14256 14257 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14258 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14259 String newMountPath = null; 14260 if (PackageHelper.isContainerMounted(cid)) { 14261 // Unmount the container 14262 if (!PackageHelper.unMountSdDir(cid)) { 14263 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14264 return false; 14265 } 14266 } 14267 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14268 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14269 " which might be stale. Will try to clean up."); 14270 // Clean up the stale container and proceed to recreate. 14271 if (!PackageHelper.destroySdDir(newCacheId)) { 14272 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14273 return false; 14274 } 14275 // Successfully cleaned up stale container. Try to rename again. 14276 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14277 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14278 + " inspite of cleaning it up."); 14279 return false; 14280 } 14281 } 14282 if (!PackageHelper.isContainerMounted(newCacheId)) { 14283 Slog.w(TAG, "Mounting container " + newCacheId); 14284 newMountPath = PackageHelper.mountSdDir(newCacheId, 14285 getEncryptKey(), Process.SYSTEM_UID); 14286 } else { 14287 newMountPath = PackageHelper.getSdDir(newCacheId); 14288 } 14289 if (newMountPath == null) { 14290 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14291 return false; 14292 } 14293 Log.i(TAG, "Succesfully renamed " + cid + 14294 " to " + newCacheId + 14295 " at new path: " + newMountPath); 14296 cid = newCacheId; 14297 14298 final File beforeCodeFile = new File(packagePath); 14299 setMountPath(newMountPath); 14300 final File afterCodeFile = new File(packagePath); 14301 14302 // Reflect the rename in scanned details 14303 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14304 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14305 afterCodeFile, pkg.baseCodePath)); 14306 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14307 afterCodeFile, pkg.splitCodePaths)); 14308 14309 // Reflect the rename in app info 14310 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14311 pkg.setApplicationInfoCodePath(pkg.codePath); 14312 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14313 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14314 pkg.setApplicationInfoResourcePath(pkg.codePath); 14315 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14316 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14317 14318 return true; 14319 } 14320 14321 private void setMountPath(String mountPath) { 14322 final File mountFile = new File(mountPath); 14323 14324 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14325 if (monolithicFile.exists()) { 14326 packagePath = monolithicFile.getAbsolutePath(); 14327 if (isFwdLocked()) { 14328 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14329 } else { 14330 resourcePath = packagePath; 14331 } 14332 } else { 14333 packagePath = mountFile.getAbsolutePath(); 14334 resourcePath = packagePath; 14335 } 14336 } 14337 14338 int doPostInstall(int status, int uid) { 14339 if (status != PackageManager.INSTALL_SUCCEEDED) { 14340 cleanUp(); 14341 } else { 14342 final int groupOwner; 14343 final String protectedFile; 14344 if (isFwdLocked()) { 14345 groupOwner = UserHandle.getSharedAppGid(uid); 14346 protectedFile = RES_FILE_NAME; 14347 } else { 14348 groupOwner = -1; 14349 protectedFile = null; 14350 } 14351 14352 if (uid < Process.FIRST_APPLICATION_UID 14353 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14354 Slog.e(TAG, "Failed to finalize " + cid); 14355 PackageHelper.destroySdDir(cid); 14356 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14357 } 14358 14359 boolean mounted = PackageHelper.isContainerMounted(cid); 14360 if (!mounted) { 14361 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14362 } 14363 } 14364 return status; 14365 } 14366 14367 private void cleanUp() { 14368 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14369 14370 // Destroy secure container 14371 PackageHelper.destroySdDir(cid); 14372 } 14373 14374 private List<String> getAllCodePaths() { 14375 final File codeFile = new File(getCodePath()); 14376 if (codeFile != null && codeFile.exists()) { 14377 try { 14378 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14379 return pkg.getAllCodePaths(); 14380 } catch (PackageParserException e) { 14381 // Ignored; we tried our best 14382 } 14383 } 14384 return Collections.EMPTY_LIST; 14385 } 14386 14387 void cleanUpResourcesLI() { 14388 // Enumerate all code paths before deleting 14389 cleanUpResourcesLI(getAllCodePaths()); 14390 } 14391 14392 private void cleanUpResourcesLI(List<String> allCodePaths) { 14393 cleanUp(); 14394 removeDexFiles(allCodePaths, instructionSets); 14395 } 14396 14397 String getPackageName() { 14398 return getAsecPackageName(cid); 14399 } 14400 14401 boolean doPostDeleteLI(boolean delete) { 14402 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14403 final List<String> allCodePaths = getAllCodePaths(); 14404 boolean mounted = PackageHelper.isContainerMounted(cid); 14405 if (mounted) { 14406 // Unmount first 14407 if (PackageHelper.unMountSdDir(cid)) { 14408 mounted = false; 14409 } 14410 } 14411 if (!mounted && delete) { 14412 cleanUpResourcesLI(allCodePaths); 14413 } 14414 return !mounted; 14415 } 14416 14417 @Override 14418 int doPreCopy() { 14419 if (isFwdLocked()) { 14420 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14421 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14422 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14423 } 14424 } 14425 14426 return PackageManager.INSTALL_SUCCEEDED; 14427 } 14428 14429 @Override 14430 int doPostCopy(int uid) { 14431 if (isFwdLocked()) { 14432 if (uid < Process.FIRST_APPLICATION_UID 14433 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14434 RES_FILE_NAME)) { 14435 Slog.e(TAG, "Failed to finalize " + cid); 14436 PackageHelper.destroySdDir(cid); 14437 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14438 } 14439 } 14440 14441 return PackageManager.INSTALL_SUCCEEDED; 14442 } 14443 } 14444 14445 /** 14446 * Logic to handle movement of existing installed applications. 14447 */ 14448 class MoveInstallArgs extends InstallArgs { 14449 private File codeFile; 14450 private File resourceFile; 14451 14452 /** New install */ 14453 MoveInstallArgs(InstallParams params) { 14454 super(params.origin, params.move, params.observer, params.installFlags, 14455 params.installerPackageName, params.volumeUuid, 14456 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14457 params.grantedRuntimePermissions, 14458 params.traceMethod, params.traceCookie, params.certificates); 14459 } 14460 14461 int copyApk(IMediaContainerService imcs, boolean temp) { 14462 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14463 + move.fromUuid + " to " + move.toUuid); 14464 synchronized (mInstaller) { 14465 try { 14466 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14467 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14468 } catch (InstallerException e) { 14469 Slog.w(TAG, "Failed to move app", e); 14470 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14471 } 14472 } 14473 14474 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14475 resourceFile = codeFile; 14476 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14477 14478 return PackageManager.INSTALL_SUCCEEDED; 14479 } 14480 14481 int doPreInstall(int status) { 14482 if (status != PackageManager.INSTALL_SUCCEEDED) { 14483 cleanUp(move.toUuid); 14484 } 14485 return status; 14486 } 14487 14488 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14489 if (status != PackageManager.INSTALL_SUCCEEDED) { 14490 cleanUp(move.toUuid); 14491 return false; 14492 } 14493 14494 // Reflect the move in app info 14495 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14496 pkg.setApplicationInfoCodePath(pkg.codePath); 14497 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14498 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14499 pkg.setApplicationInfoResourcePath(pkg.codePath); 14500 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14501 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14502 14503 return true; 14504 } 14505 14506 int doPostInstall(int status, int uid) { 14507 if (status == PackageManager.INSTALL_SUCCEEDED) { 14508 cleanUp(move.fromUuid); 14509 } else { 14510 cleanUp(move.toUuid); 14511 } 14512 return status; 14513 } 14514 14515 @Override 14516 String getCodePath() { 14517 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14518 } 14519 14520 @Override 14521 String getResourcePath() { 14522 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14523 } 14524 14525 private boolean cleanUp(String volumeUuid) { 14526 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14527 move.dataAppName); 14528 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14529 final int[] userIds = sUserManager.getUserIds(); 14530 synchronized (mInstallLock) { 14531 // Clean up both app data and code 14532 // All package moves are frozen until finished 14533 for (int userId : userIds) { 14534 try { 14535 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14536 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14537 } catch (InstallerException e) { 14538 Slog.w(TAG, String.valueOf(e)); 14539 } 14540 } 14541 removeCodePathLI(codeFile); 14542 } 14543 return true; 14544 } 14545 14546 void cleanUpResourcesLI() { 14547 throw new UnsupportedOperationException(); 14548 } 14549 14550 boolean doPostDeleteLI(boolean delete) { 14551 throw new UnsupportedOperationException(); 14552 } 14553 } 14554 14555 static String getAsecPackageName(String packageCid) { 14556 int idx = packageCid.lastIndexOf("-"); 14557 if (idx == -1) { 14558 return packageCid; 14559 } 14560 return packageCid.substring(0, idx); 14561 } 14562 14563 // Utility method used to create code paths based on package name and available index. 14564 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14565 String idxStr = ""; 14566 int idx = 1; 14567 // Fall back to default value of idx=1 if prefix is not 14568 // part of oldCodePath 14569 if (oldCodePath != null) { 14570 String subStr = oldCodePath; 14571 // Drop the suffix right away 14572 if (suffix != null && subStr.endsWith(suffix)) { 14573 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14574 } 14575 // If oldCodePath already contains prefix find out the 14576 // ending index to either increment or decrement. 14577 int sidx = subStr.lastIndexOf(prefix); 14578 if (sidx != -1) { 14579 subStr = subStr.substring(sidx + prefix.length()); 14580 if (subStr != null) { 14581 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14582 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14583 } 14584 try { 14585 idx = Integer.parseInt(subStr); 14586 if (idx <= 1) { 14587 idx++; 14588 } else { 14589 idx--; 14590 } 14591 } catch(NumberFormatException e) { 14592 } 14593 } 14594 } 14595 } 14596 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14597 return prefix + idxStr; 14598 } 14599 14600 private File getNextCodePath(File targetDir, String packageName) { 14601 File result; 14602 SecureRandom random = new SecureRandom(); 14603 byte[] bytes = new byte[16]; 14604 do { 14605 random.nextBytes(bytes); 14606 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14607 result = new File(targetDir, packageName + "-" + suffix); 14608 } while (result.exists()); 14609 return result; 14610 } 14611 14612 // Utility method that returns the relative package path with respect 14613 // to the installation directory. Like say for /data/data/com.test-1.apk 14614 // string com.test-1 is returned. 14615 static String deriveCodePathName(String codePath) { 14616 if (codePath == null) { 14617 return null; 14618 } 14619 final File codeFile = new File(codePath); 14620 final String name = codeFile.getName(); 14621 if (codeFile.isDirectory()) { 14622 return name; 14623 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14624 final int lastDot = name.lastIndexOf('.'); 14625 return name.substring(0, lastDot); 14626 } else { 14627 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14628 return null; 14629 } 14630 } 14631 14632 static class PackageInstalledInfo { 14633 String name; 14634 int uid; 14635 // The set of users that originally had this package installed. 14636 int[] origUsers; 14637 // The set of users that now have this package installed. 14638 int[] newUsers; 14639 PackageParser.Package pkg; 14640 int returnCode; 14641 String returnMsg; 14642 PackageRemovedInfo removedInfo; 14643 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14644 14645 public void setError(int code, String msg) { 14646 setReturnCode(code); 14647 setReturnMessage(msg); 14648 Slog.w(TAG, msg); 14649 } 14650 14651 public void setError(String msg, PackageParserException e) { 14652 setReturnCode(e.error); 14653 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14654 Slog.w(TAG, msg, e); 14655 } 14656 14657 public void setError(String msg, PackageManagerException e) { 14658 returnCode = e.error; 14659 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14660 Slog.w(TAG, msg, e); 14661 } 14662 14663 public void setReturnCode(int returnCode) { 14664 this.returnCode = returnCode; 14665 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14666 for (int i = 0; i < childCount; i++) { 14667 addedChildPackages.valueAt(i).returnCode = returnCode; 14668 } 14669 } 14670 14671 private void setReturnMessage(String returnMsg) { 14672 this.returnMsg = returnMsg; 14673 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14674 for (int i = 0; i < childCount; i++) { 14675 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14676 } 14677 } 14678 14679 // In some error cases we want to convey more info back to the observer 14680 String origPackage; 14681 String origPermission; 14682 } 14683 14684 /* 14685 * Install a non-existing package. 14686 */ 14687 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14688 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14689 PackageInstalledInfo res) { 14690 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14691 14692 // Remember this for later, in case we need to rollback this install 14693 String pkgName = pkg.packageName; 14694 14695 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14696 14697 synchronized(mPackages) { 14698 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14699 if (renamedPackage != null) { 14700 // A package with the same name is already installed, though 14701 // it has been renamed to an older name. The package we 14702 // are trying to install should be installed as an update to 14703 // the existing one, but that has not been requested, so bail. 14704 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14705 + " without first uninstalling package running as " 14706 + renamedPackage); 14707 return; 14708 } 14709 if (mPackages.containsKey(pkgName)) { 14710 // Don't allow installation over an existing package with the same name. 14711 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14712 + " without first uninstalling."); 14713 return; 14714 } 14715 } 14716 14717 try { 14718 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14719 System.currentTimeMillis(), user); 14720 14721 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14722 14723 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14724 prepareAppDataAfterInstallLIF(newPackage); 14725 14726 } else { 14727 // Remove package from internal structures, but keep around any 14728 // data that might have already existed 14729 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14730 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14731 } 14732 } catch (PackageManagerException e) { 14733 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14734 } 14735 14736 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14737 } 14738 14739 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14740 // Can't rotate keys during boot or if sharedUser. 14741 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14742 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14743 return false; 14744 } 14745 // app is using upgradeKeySets; make sure all are valid 14746 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14747 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14748 for (int i = 0; i < upgradeKeySets.length; i++) { 14749 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14750 Slog.wtf(TAG, "Package " 14751 + (oldPs.name != null ? oldPs.name : "<null>") 14752 + " contains upgrade-key-set reference to unknown key-set: " 14753 + upgradeKeySets[i] 14754 + " reverting to signatures check."); 14755 return false; 14756 } 14757 } 14758 return true; 14759 } 14760 14761 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14762 // Upgrade keysets are being used. Determine if new package has a superset of the 14763 // required keys. 14764 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14765 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14766 for (int i = 0; i < upgradeKeySets.length; i++) { 14767 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14768 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14769 return true; 14770 } 14771 } 14772 return false; 14773 } 14774 14775 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14776 try (DigestInputStream digestStream = 14777 new DigestInputStream(new FileInputStream(file), digest)) { 14778 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14779 } 14780 } 14781 14782 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14783 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14784 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14785 14786 final PackageParser.Package oldPackage; 14787 final String pkgName = pkg.packageName; 14788 final int[] allUsers; 14789 final int[] installedUsers; 14790 14791 synchronized(mPackages) { 14792 oldPackage = mPackages.get(pkgName); 14793 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14794 14795 // don't allow upgrade to target a release SDK from a pre-release SDK 14796 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14797 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14798 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14799 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14800 if (oldTargetsPreRelease 14801 && !newTargetsPreRelease 14802 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14803 Slog.w(TAG, "Can't install package targeting released sdk"); 14804 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14805 return; 14806 } 14807 14808 // don't allow an upgrade from full to ephemeral 14809 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14810 if (isEphemeral && !oldIsEphemeral) { 14811 // can't downgrade from full to ephemeral 14812 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14813 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14814 return; 14815 } 14816 14817 // verify signatures are valid 14818 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14819 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14820 if (!checkUpgradeKeySetLP(ps, pkg)) { 14821 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14822 "New package not signed by keys specified by upgrade-keysets: " 14823 + pkgName); 14824 return; 14825 } 14826 } else { 14827 // default to original signature matching 14828 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14829 != PackageManager.SIGNATURE_MATCH) { 14830 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14831 "New package has a different signature: " + pkgName); 14832 return; 14833 } 14834 } 14835 14836 // don't allow a system upgrade unless the upgrade hash matches 14837 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14838 byte[] digestBytes = null; 14839 try { 14840 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14841 updateDigest(digest, new File(pkg.baseCodePath)); 14842 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14843 for (String path : pkg.splitCodePaths) { 14844 updateDigest(digest, new File(path)); 14845 } 14846 } 14847 digestBytes = digest.digest(); 14848 } catch (NoSuchAlgorithmException | IOException e) { 14849 res.setError(INSTALL_FAILED_INVALID_APK, 14850 "Could not compute hash: " + pkgName); 14851 return; 14852 } 14853 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14854 res.setError(INSTALL_FAILED_INVALID_APK, 14855 "New package fails restrict-update check: " + pkgName); 14856 return; 14857 } 14858 // retain upgrade restriction 14859 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14860 } 14861 14862 // Check for shared user id changes 14863 String invalidPackageName = 14864 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14865 if (invalidPackageName != null) { 14866 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14867 "Package " + invalidPackageName + " tried to change user " 14868 + oldPackage.mSharedUserId); 14869 return; 14870 } 14871 14872 // In case of rollback, remember per-user/profile install state 14873 allUsers = sUserManager.getUserIds(); 14874 installedUsers = ps.queryInstalledUsers(allUsers, true); 14875 } 14876 14877 // Update what is removed 14878 res.removedInfo = new PackageRemovedInfo(); 14879 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14880 res.removedInfo.removedPackage = oldPackage.packageName; 14881 res.removedInfo.isUpdate = true; 14882 res.removedInfo.origUsers = installedUsers; 14883 final int childCount = (oldPackage.childPackages != null) 14884 ? oldPackage.childPackages.size() : 0; 14885 for (int i = 0; i < childCount; i++) { 14886 boolean childPackageUpdated = false; 14887 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14888 if (res.addedChildPackages != null) { 14889 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14890 if (childRes != null) { 14891 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14892 childRes.removedInfo.removedPackage = childPkg.packageName; 14893 childRes.removedInfo.isUpdate = true; 14894 childPackageUpdated = true; 14895 } 14896 } 14897 if (!childPackageUpdated) { 14898 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14899 childRemovedRes.removedPackage = childPkg.packageName; 14900 childRemovedRes.isUpdate = false; 14901 childRemovedRes.dataRemoved = true; 14902 synchronized (mPackages) { 14903 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14904 if (childPs != null) { 14905 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14906 } 14907 } 14908 if (res.removedInfo.removedChildPackages == null) { 14909 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14910 } 14911 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14912 } 14913 } 14914 14915 boolean sysPkg = (isSystemApp(oldPackage)); 14916 if (sysPkg) { 14917 // Set the system/privileged flags as needed 14918 final boolean privileged = 14919 (oldPackage.applicationInfo.privateFlags 14920 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14921 final int systemPolicyFlags = policyFlags 14922 | PackageParser.PARSE_IS_SYSTEM 14923 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14924 14925 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14926 user, allUsers, installerPackageName, res); 14927 } else { 14928 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14929 user, allUsers, installerPackageName, res); 14930 } 14931 } 14932 14933 public List<String> getPreviousCodePaths(String packageName) { 14934 final PackageSetting ps = mSettings.mPackages.get(packageName); 14935 final List<String> result = new ArrayList<String>(); 14936 if (ps != null && ps.oldCodePaths != null) { 14937 result.addAll(ps.oldCodePaths); 14938 } 14939 return result; 14940 } 14941 14942 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14943 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14944 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14945 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14946 + deletedPackage); 14947 14948 String pkgName = deletedPackage.packageName; 14949 boolean deletedPkg = true; 14950 boolean addedPkg = false; 14951 boolean updatedSettings = false; 14952 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14953 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14954 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14955 14956 final long origUpdateTime = (pkg.mExtras != null) 14957 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14958 14959 // First delete the existing package while retaining the data directory 14960 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14961 res.removedInfo, true, pkg)) { 14962 // If the existing package wasn't successfully deleted 14963 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14964 deletedPkg = false; 14965 } else { 14966 // Successfully deleted the old package; proceed with replace. 14967 14968 // If deleted package lived in a container, give users a chance to 14969 // relinquish resources before killing. 14970 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14971 if (DEBUG_INSTALL) { 14972 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14973 } 14974 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14975 final ArrayList<String> pkgList = new ArrayList<String>(1); 14976 pkgList.add(deletedPackage.applicationInfo.packageName); 14977 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14978 } 14979 14980 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14981 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14982 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14983 14984 try { 14985 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14986 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14987 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14988 14989 // Update the in-memory copy of the previous code paths. 14990 PackageSetting ps = mSettings.mPackages.get(pkgName); 14991 if (!killApp) { 14992 if (ps.oldCodePaths == null) { 14993 ps.oldCodePaths = new ArraySet<>(); 14994 } 14995 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14996 if (deletedPackage.splitCodePaths != null) { 14997 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14998 } 14999 } else { 15000 ps.oldCodePaths = null; 15001 } 15002 if (ps.childPackageNames != null) { 15003 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15004 final String childPkgName = ps.childPackageNames.get(i); 15005 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15006 childPs.oldCodePaths = ps.oldCodePaths; 15007 } 15008 } 15009 prepareAppDataAfterInstallLIF(newPackage); 15010 addedPkg = true; 15011 } catch (PackageManagerException e) { 15012 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15013 } 15014 } 15015 15016 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15017 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15018 15019 // Revert all internal state mutations and added folders for the failed install 15020 if (addedPkg) { 15021 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15022 res.removedInfo, true, null); 15023 } 15024 15025 // Restore the old package 15026 if (deletedPkg) { 15027 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15028 File restoreFile = new File(deletedPackage.codePath); 15029 // Parse old package 15030 boolean oldExternal = isExternal(deletedPackage); 15031 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15032 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15033 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15034 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15035 try { 15036 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15037 null); 15038 } catch (PackageManagerException e) { 15039 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15040 + e.getMessage()); 15041 return; 15042 } 15043 15044 synchronized (mPackages) { 15045 // Ensure the installer package name up to date 15046 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15047 15048 // Update permissions for restored package 15049 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15050 15051 mSettings.writeLPr(); 15052 } 15053 15054 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15055 } 15056 } else { 15057 synchronized (mPackages) { 15058 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15059 if (ps != null) { 15060 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15061 if (res.removedInfo.removedChildPackages != null) { 15062 final int childCount = res.removedInfo.removedChildPackages.size(); 15063 // Iterate in reverse as we may modify the collection 15064 for (int i = childCount - 1; i >= 0; i--) { 15065 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15066 if (res.addedChildPackages.containsKey(childPackageName)) { 15067 res.removedInfo.removedChildPackages.removeAt(i); 15068 } else { 15069 PackageRemovedInfo childInfo = res.removedInfo 15070 .removedChildPackages.valueAt(i); 15071 childInfo.removedForAllUsers = mPackages.get( 15072 childInfo.removedPackage) == null; 15073 } 15074 } 15075 } 15076 } 15077 } 15078 } 15079 } 15080 15081 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15082 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15083 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 15084 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15085 + ", old=" + deletedPackage); 15086 15087 final boolean disabledSystem; 15088 15089 // Remove existing system package 15090 removePackageLI(deletedPackage, true); 15091 15092 synchronized (mPackages) { 15093 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15094 } 15095 if (!disabledSystem) { 15096 // We didn't need to disable the .apk as a current system package, 15097 // which means we are replacing another update that is already 15098 // installed. We need to make sure to delete the older one's .apk. 15099 res.removedInfo.args = createInstallArgsForExisting(0, 15100 deletedPackage.applicationInfo.getCodePath(), 15101 deletedPackage.applicationInfo.getResourcePath(), 15102 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15103 } else { 15104 res.removedInfo.args = null; 15105 } 15106 15107 // Successfully disabled the old package. Now proceed with re-installation 15108 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15109 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15110 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15111 15112 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15113 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15114 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15115 15116 PackageParser.Package newPackage = null; 15117 try { 15118 // Add the package to the internal data structures 15119 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 15120 15121 // Set the update and install times 15122 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15123 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15124 System.currentTimeMillis()); 15125 15126 // Update the package dynamic state if succeeded 15127 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15128 // Now that the install succeeded make sure we remove data 15129 // directories for any child package the update removed. 15130 final int deletedChildCount = (deletedPackage.childPackages != null) 15131 ? deletedPackage.childPackages.size() : 0; 15132 final int newChildCount = (newPackage.childPackages != null) 15133 ? newPackage.childPackages.size() : 0; 15134 for (int i = 0; i < deletedChildCount; i++) { 15135 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15136 boolean childPackageDeleted = true; 15137 for (int j = 0; j < newChildCount; j++) { 15138 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15139 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15140 childPackageDeleted = false; 15141 break; 15142 } 15143 } 15144 if (childPackageDeleted) { 15145 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15146 deletedChildPkg.packageName); 15147 if (ps != null && res.removedInfo.removedChildPackages != null) { 15148 PackageRemovedInfo removedChildRes = res.removedInfo 15149 .removedChildPackages.get(deletedChildPkg.packageName); 15150 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15151 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15152 } 15153 } 15154 } 15155 15156 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15157 prepareAppDataAfterInstallLIF(newPackage); 15158 } 15159 } catch (PackageManagerException e) { 15160 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15161 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15162 } 15163 15164 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15165 // Re installation failed. Restore old information 15166 // Remove new pkg information 15167 if (newPackage != null) { 15168 removeInstalledPackageLI(newPackage, true); 15169 } 15170 // Add back the old system package 15171 try { 15172 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15173 } catch (PackageManagerException e) { 15174 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15175 } 15176 15177 synchronized (mPackages) { 15178 if (disabledSystem) { 15179 enableSystemPackageLPw(deletedPackage); 15180 } 15181 15182 // Ensure the installer package name up to date 15183 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15184 15185 // Update permissions for restored package 15186 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15187 15188 mSettings.writeLPr(); 15189 } 15190 15191 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15192 + " after failed upgrade"); 15193 } 15194 } 15195 15196 /** 15197 * Checks whether the parent or any of the child packages have a change shared 15198 * user. For a package to be a valid update the shred users of the parent and 15199 * the children should match. We may later support changing child shared users. 15200 * @param oldPkg The updated package. 15201 * @param newPkg The update package. 15202 * @return The shared user that change between the versions. 15203 */ 15204 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15205 PackageParser.Package newPkg) { 15206 // Check parent shared user 15207 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15208 return newPkg.packageName; 15209 } 15210 // Check child shared users 15211 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15212 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15213 for (int i = 0; i < newChildCount; i++) { 15214 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15215 // If this child was present, did it have the same shared user? 15216 for (int j = 0; j < oldChildCount; j++) { 15217 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15218 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15219 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15220 return newChildPkg.packageName; 15221 } 15222 } 15223 } 15224 return null; 15225 } 15226 15227 private void removeNativeBinariesLI(PackageSetting ps) { 15228 // Remove the lib path for the parent package 15229 if (ps != null) { 15230 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15231 // Remove the lib path for the child packages 15232 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15233 for (int i = 0; i < childCount; i++) { 15234 PackageSetting childPs = null; 15235 synchronized (mPackages) { 15236 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15237 } 15238 if (childPs != null) { 15239 NativeLibraryHelper.removeNativeBinariesLI(childPs 15240 .legacyNativeLibraryPathString); 15241 } 15242 } 15243 } 15244 } 15245 15246 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15247 // Enable the parent package 15248 mSettings.enableSystemPackageLPw(pkg.packageName); 15249 // Enable the child packages 15250 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15251 for (int i = 0; i < childCount; i++) { 15252 PackageParser.Package childPkg = pkg.childPackages.get(i); 15253 mSettings.enableSystemPackageLPw(childPkg.packageName); 15254 } 15255 } 15256 15257 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15258 PackageParser.Package newPkg) { 15259 // Disable the parent package (parent always replaced) 15260 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15261 // Disable the child packages 15262 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15263 for (int i = 0; i < childCount; i++) { 15264 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15265 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15266 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15267 } 15268 return disabled; 15269 } 15270 15271 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15272 String installerPackageName) { 15273 // Enable the parent package 15274 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15275 // Enable the child packages 15276 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15277 for (int i = 0; i < childCount; i++) { 15278 PackageParser.Package childPkg = pkg.childPackages.get(i); 15279 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15280 } 15281 } 15282 15283 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15284 // Collect all used permissions in the UID 15285 ArraySet<String> usedPermissions = new ArraySet<>(); 15286 final int packageCount = su.packages.size(); 15287 for (int i = 0; i < packageCount; i++) { 15288 PackageSetting ps = su.packages.valueAt(i); 15289 if (ps.pkg == null) { 15290 continue; 15291 } 15292 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15293 for (int j = 0; j < requestedPermCount; j++) { 15294 String permission = ps.pkg.requestedPermissions.get(j); 15295 BasePermission bp = mSettings.mPermissions.get(permission); 15296 if (bp != null) { 15297 usedPermissions.add(permission); 15298 } 15299 } 15300 } 15301 15302 PermissionsState permissionsState = su.getPermissionsState(); 15303 // Prune install permissions 15304 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15305 final int installPermCount = installPermStates.size(); 15306 for (int i = installPermCount - 1; i >= 0; i--) { 15307 PermissionState permissionState = installPermStates.get(i); 15308 if (!usedPermissions.contains(permissionState.getName())) { 15309 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15310 if (bp != null) { 15311 permissionsState.revokeInstallPermission(bp); 15312 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15313 PackageManager.MASK_PERMISSION_FLAGS, 0); 15314 } 15315 } 15316 } 15317 15318 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15319 15320 // Prune runtime permissions 15321 for (int userId : allUserIds) { 15322 List<PermissionState> runtimePermStates = permissionsState 15323 .getRuntimePermissionStates(userId); 15324 final int runtimePermCount = runtimePermStates.size(); 15325 for (int i = runtimePermCount - 1; i >= 0; i--) { 15326 PermissionState permissionState = runtimePermStates.get(i); 15327 if (!usedPermissions.contains(permissionState.getName())) { 15328 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15329 if (bp != null) { 15330 permissionsState.revokeRuntimePermission(bp, userId); 15331 permissionsState.updatePermissionFlags(bp, userId, 15332 PackageManager.MASK_PERMISSION_FLAGS, 0); 15333 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15334 runtimePermissionChangedUserIds, userId); 15335 } 15336 } 15337 } 15338 } 15339 15340 return runtimePermissionChangedUserIds; 15341 } 15342 15343 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15344 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15345 // Update the parent package setting 15346 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15347 res, user); 15348 // Update the child packages setting 15349 final int childCount = (newPackage.childPackages != null) 15350 ? newPackage.childPackages.size() : 0; 15351 for (int i = 0; i < childCount; i++) { 15352 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15353 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15354 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15355 childRes.origUsers, childRes, user); 15356 } 15357 } 15358 15359 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15360 String installerPackageName, int[] allUsers, int[] installedForUsers, 15361 PackageInstalledInfo res, UserHandle user) { 15362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15363 15364 String pkgName = newPackage.packageName; 15365 synchronized (mPackages) { 15366 //write settings. the installStatus will be incomplete at this stage. 15367 //note that the new package setting would have already been 15368 //added to mPackages. It hasn't been persisted yet. 15369 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15370 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15371 mSettings.writeLPr(); 15372 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15373 } 15374 15375 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15376 synchronized (mPackages) { 15377 updatePermissionsLPw(newPackage.packageName, newPackage, 15378 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15379 ? UPDATE_PERMISSIONS_ALL : 0)); 15380 // For system-bundled packages, we assume that installing an upgraded version 15381 // of the package implies that the user actually wants to run that new code, 15382 // so we enable the package. 15383 PackageSetting ps = mSettings.mPackages.get(pkgName); 15384 final int userId = user.getIdentifier(); 15385 if (ps != null) { 15386 if (isSystemApp(newPackage)) { 15387 if (DEBUG_INSTALL) { 15388 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15389 } 15390 // Enable system package for requested users 15391 if (res.origUsers != null) { 15392 for (int origUserId : res.origUsers) { 15393 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15394 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15395 origUserId, installerPackageName); 15396 } 15397 } 15398 } 15399 // Also convey the prior install/uninstall state 15400 if (allUsers != null && installedForUsers != null) { 15401 for (int currentUserId : allUsers) { 15402 final boolean installed = ArrayUtils.contains( 15403 installedForUsers, currentUserId); 15404 if (DEBUG_INSTALL) { 15405 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15406 } 15407 ps.setInstalled(installed, currentUserId); 15408 } 15409 // these install state changes will be persisted in the 15410 // upcoming call to mSettings.writeLPr(). 15411 } 15412 } 15413 // It's implied that when a user requests installation, they want the app to be 15414 // installed and enabled. 15415 if (userId != UserHandle.USER_ALL) { 15416 ps.setInstalled(true, userId); 15417 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15418 } 15419 } 15420 res.name = pkgName; 15421 res.uid = newPackage.applicationInfo.uid; 15422 res.pkg = newPackage; 15423 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15424 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15425 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15426 //to update install status 15427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15428 mSettings.writeLPr(); 15429 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15430 } 15431 15432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15433 } 15434 15435 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15436 try { 15437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15438 installPackageLI(args, res); 15439 } finally { 15440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15441 } 15442 } 15443 15444 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15445 final int installFlags = args.installFlags; 15446 final String installerPackageName = args.installerPackageName; 15447 final String volumeUuid = args.volumeUuid; 15448 final File tmpPackageFile = new File(args.getCodePath()); 15449 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15450 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15451 || (args.volumeUuid != null)); 15452 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15453 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15454 boolean replace = false; 15455 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15456 if (args.move != null) { 15457 // moving a complete application; perform an initial scan on the new install location 15458 scanFlags |= SCAN_INITIAL; 15459 } 15460 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15461 scanFlags |= SCAN_DONT_KILL_APP; 15462 } 15463 15464 // Result object to be returned 15465 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15466 15467 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15468 15469 // Sanity check 15470 if (ephemeral && (forwardLocked || onExternal)) { 15471 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15472 + " external=" + onExternal); 15473 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15474 return; 15475 } 15476 15477 // Retrieve PackageSettings and parse package 15478 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15479 | PackageParser.PARSE_ENFORCE_CODE 15480 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15481 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15482 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15483 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15484 PackageParser pp = new PackageParser(); 15485 pp.setSeparateProcesses(mSeparateProcesses); 15486 pp.setDisplayMetrics(mMetrics); 15487 15488 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15489 final PackageParser.Package pkg; 15490 try { 15491 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15492 } catch (PackageParserException e) { 15493 res.setError("Failed parse during installPackageLI", e); 15494 return; 15495 } finally { 15496 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15497 } 15498 15499 // Ephemeral apps must have target SDK >= O. 15500 // TODO: Update conditional and error message when O gets locked down 15501 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 15502 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 15503 "Ephemeral apps must have target SDK version of at least O"); 15504 return; 15505 } 15506 15507 // If we are installing a clustered package add results for the children 15508 if (pkg.childPackages != null) { 15509 synchronized (mPackages) { 15510 final int childCount = pkg.childPackages.size(); 15511 for (int i = 0; i < childCount; i++) { 15512 PackageParser.Package childPkg = pkg.childPackages.get(i); 15513 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15514 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15515 childRes.pkg = childPkg; 15516 childRes.name = childPkg.packageName; 15517 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15518 if (childPs != null) { 15519 childRes.origUsers = childPs.queryInstalledUsers( 15520 sUserManager.getUserIds(), true); 15521 } 15522 if ((mPackages.containsKey(childPkg.packageName))) { 15523 childRes.removedInfo = new PackageRemovedInfo(); 15524 childRes.removedInfo.removedPackage = childPkg.packageName; 15525 } 15526 if (res.addedChildPackages == null) { 15527 res.addedChildPackages = new ArrayMap<>(); 15528 } 15529 res.addedChildPackages.put(childPkg.packageName, childRes); 15530 } 15531 } 15532 } 15533 15534 // If package doesn't declare API override, mark that we have an install 15535 // time CPU ABI override. 15536 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15537 pkg.cpuAbiOverride = args.abiOverride; 15538 } 15539 15540 String pkgName = res.name = pkg.packageName; 15541 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15542 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15543 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15544 return; 15545 } 15546 } 15547 15548 try { 15549 // either use what we've been given or parse directly from the APK 15550 if (args.certificates != null) { 15551 try { 15552 PackageParser.populateCertificates(pkg, args.certificates); 15553 } catch (PackageParserException e) { 15554 // there was something wrong with the certificates we were given; 15555 // try to pull them from the APK 15556 PackageParser.collectCertificates(pkg, parseFlags); 15557 } 15558 } else { 15559 PackageParser.collectCertificates(pkg, parseFlags); 15560 } 15561 } catch (PackageParserException e) { 15562 res.setError("Failed collect during installPackageLI", e); 15563 return; 15564 } 15565 15566 // Get rid of all references to package scan path via parser. 15567 pp = null; 15568 String oldCodePath = null; 15569 boolean systemApp = false; 15570 synchronized (mPackages) { 15571 // Check if installing already existing package 15572 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15573 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15574 if (pkg.mOriginalPackages != null 15575 && pkg.mOriginalPackages.contains(oldName) 15576 && mPackages.containsKey(oldName)) { 15577 // This package is derived from an original package, 15578 // and this device has been updating from that original 15579 // name. We must continue using the original name, so 15580 // rename the new package here. 15581 pkg.setPackageName(oldName); 15582 pkgName = pkg.packageName; 15583 replace = true; 15584 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15585 + oldName + " pkgName=" + pkgName); 15586 } else if (mPackages.containsKey(pkgName)) { 15587 // This package, under its official name, already exists 15588 // on the device; we should replace it. 15589 replace = true; 15590 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15591 } 15592 15593 // Child packages are installed through the parent package 15594 if (pkg.parentPackage != null) { 15595 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15596 "Package " + pkg.packageName + " is child of package " 15597 + pkg.parentPackage.parentPackage + ". Child packages " 15598 + "can be updated only through the parent package."); 15599 return; 15600 } 15601 15602 if (replace) { 15603 // Prevent apps opting out from runtime permissions 15604 PackageParser.Package oldPackage = mPackages.get(pkgName); 15605 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15606 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15607 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15608 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15609 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15610 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15611 + " doesn't support runtime permissions but the old" 15612 + " target SDK " + oldTargetSdk + " does."); 15613 return; 15614 } 15615 15616 // Prevent installing of child packages 15617 if (oldPackage.parentPackage != null) { 15618 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15619 "Package " + pkg.packageName + " is child of package " 15620 + oldPackage.parentPackage + ". Child packages " 15621 + "can be updated only through the parent package."); 15622 return; 15623 } 15624 } 15625 } 15626 15627 PackageSetting ps = mSettings.mPackages.get(pkgName); 15628 if (ps != null) { 15629 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15630 15631 // Quick sanity check that we're signed correctly if updating; 15632 // we'll check this again later when scanning, but we want to 15633 // bail early here before tripping over redefined permissions. 15634 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15635 if (!checkUpgradeKeySetLP(ps, pkg)) { 15636 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15637 + pkg.packageName + " upgrade keys do not match the " 15638 + "previously installed version"); 15639 return; 15640 } 15641 } else { 15642 try { 15643 verifySignaturesLP(ps, pkg); 15644 } catch (PackageManagerException e) { 15645 res.setError(e.error, e.getMessage()); 15646 return; 15647 } 15648 } 15649 15650 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15651 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15652 systemApp = (ps.pkg.applicationInfo.flags & 15653 ApplicationInfo.FLAG_SYSTEM) != 0; 15654 } 15655 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15656 } 15657 15658 // Check whether the newly-scanned package wants to define an already-defined perm 15659 int N = pkg.permissions.size(); 15660 for (int i = N-1; i >= 0; i--) { 15661 PackageParser.Permission perm = pkg.permissions.get(i); 15662 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15663 if (bp != null) { 15664 // If the defining package is signed with our cert, it's okay. This 15665 // also includes the "updating the same package" case, of course. 15666 // "updating same package" could also involve key-rotation. 15667 final boolean sigsOk; 15668 if (bp.sourcePackage.equals(pkg.packageName) 15669 && (bp.packageSetting instanceof PackageSetting) 15670 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15671 scanFlags))) { 15672 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15673 } else { 15674 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15675 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15676 } 15677 if (!sigsOk) { 15678 // If the owning package is the system itself, we log but allow 15679 // install to proceed; we fail the install on all other permission 15680 // redefinitions. 15681 if (!bp.sourcePackage.equals("android")) { 15682 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15683 + pkg.packageName + " attempting to redeclare permission " 15684 + perm.info.name + " already owned by " + bp.sourcePackage); 15685 res.origPermission = perm.info.name; 15686 res.origPackage = bp.sourcePackage; 15687 return; 15688 } else { 15689 Slog.w(TAG, "Package " + pkg.packageName 15690 + " attempting to redeclare system permission " 15691 + perm.info.name + "; ignoring new declaration"); 15692 pkg.permissions.remove(i); 15693 } 15694 } 15695 } 15696 } 15697 } 15698 15699 if (systemApp) { 15700 if (onExternal) { 15701 // Abort update; system app can't be replaced with app on sdcard 15702 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15703 "Cannot install updates to system apps on sdcard"); 15704 return; 15705 } else if (ephemeral) { 15706 // Abort update; system app can't be replaced with an ephemeral app 15707 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15708 "Cannot update a system app with an ephemeral app"); 15709 return; 15710 } 15711 } 15712 15713 if (args.move != null) { 15714 // We did an in-place move, so dex is ready to roll 15715 scanFlags |= SCAN_NO_DEX; 15716 scanFlags |= SCAN_MOVE; 15717 15718 synchronized (mPackages) { 15719 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15720 if (ps == null) { 15721 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15722 "Missing settings for moved package " + pkgName); 15723 } 15724 15725 // We moved the entire application as-is, so bring over the 15726 // previously derived ABI information. 15727 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15728 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15729 } 15730 15731 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15732 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15733 scanFlags |= SCAN_NO_DEX; 15734 15735 try { 15736 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15737 args.abiOverride : pkg.cpuAbiOverride); 15738 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15739 true /*extractLibs*/, mAppLib32InstallDir); 15740 } catch (PackageManagerException pme) { 15741 Slog.e(TAG, "Error deriving application ABI", pme); 15742 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15743 return; 15744 } 15745 15746 // Shared libraries for the package need to be updated. 15747 synchronized (mPackages) { 15748 try { 15749 updateSharedLibrariesLPr(pkg, null); 15750 } catch (PackageManagerException e) { 15751 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15752 } 15753 } 15754 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15755 // Do not run PackageDexOptimizer through the local performDexOpt 15756 // method because `pkg` may not be in `mPackages` yet. 15757 // 15758 // Also, don't fail application installs if the dexopt step fails. 15759 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15760 null /* instructionSets */, false /* checkProfiles */, 15761 getCompilerFilterForReason(REASON_INSTALL), 15762 getOrCreateCompilerPackageStats(pkg)); 15763 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15764 15765 // Notify BackgroundDexOptService that the package has been changed. 15766 // If this is an update of a package which used to fail to compile, 15767 // BDOS will remove it from its blacklist. 15768 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15769 } 15770 15771 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15772 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15773 return; 15774 } 15775 15776 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15777 15778 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15779 "installPackageLI")) { 15780 if (replace) { 15781 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15782 installerPackageName, res); 15783 } else { 15784 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15785 args.user, installerPackageName, volumeUuid, res); 15786 } 15787 } 15788 synchronized (mPackages) { 15789 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15790 if (ps != null) { 15791 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15792 } 15793 15794 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15795 for (int i = 0; i < childCount; i++) { 15796 PackageParser.Package childPkg = pkg.childPackages.get(i); 15797 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15798 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15799 if (childPs != null) { 15800 childRes.newUsers = childPs.queryInstalledUsers( 15801 sUserManager.getUserIds(), true); 15802 } 15803 } 15804 } 15805 } 15806 15807 private void startIntentFilterVerifications(int userId, boolean replacing, 15808 PackageParser.Package pkg) { 15809 if (mIntentFilterVerifierComponent == null) { 15810 Slog.w(TAG, "No IntentFilter verification will not be done as " 15811 + "there is no IntentFilterVerifier available!"); 15812 return; 15813 } 15814 15815 final int verifierUid = getPackageUid( 15816 mIntentFilterVerifierComponent.getPackageName(), 15817 MATCH_DEBUG_TRIAGED_MISSING, 15818 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15819 15820 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15821 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15822 mHandler.sendMessage(msg); 15823 15824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15825 for (int i = 0; i < childCount; i++) { 15826 PackageParser.Package childPkg = pkg.childPackages.get(i); 15827 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15828 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15829 mHandler.sendMessage(msg); 15830 } 15831 } 15832 15833 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15834 PackageParser.Package pkg) { 15835 int size = pkg.activities.size(); 15836 if (size == 0) { 15837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15838 "No activity, so no need to verify any IntentFilter!"); 15839 return; 15840 } 15841 15842 final boolean hasDomainURLs = hasDomainURLs(pkg); 15843 if (!hasDomainURLs) { 15844 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15845 "No domain URLs, so no need to verify any IntentFilter!"); 15846 return; 15847 } 15848 15849 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15850 + " if any IntentFilter from the " + size 15851 + " Activities needs verification ..."); 15852 15853 int count = 0; 15854 final String packageName = pkg.packageName; 15855 15856 synchronized (mPackages) { 15857 // If this is a new install and we see that we've already run verification for this 15858 // package, we have nothing to do: it means the state was restored from backup. 15859 if (!replacing) { 15860 IntentFilterVerificationInfo ivi = 15861 mSettings.getIntentFilterVerificationLPr(packageName); 15862 if (ivi != null) { 15863 if (DEBUG_DOMAIN_VERIFICATION) { 15864 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15865 + ivi.getStatusString()); 15866 } 15867 return; 15868 } 15869 } 15870 15871 // If any filters need to be verified, then all need to be. 15872 boolean needToVerify = false; 15873 for (PackageParser.Activity a : pkg.activities) { 15874 for (ActivityIntentInfo filter : a.intents) { 15875 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15876 if (DEBUG_DOMAIN_VERIFICATION) { 15877 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15878 } 15879 needToVerify = true; 15880 break; 15881 } 15882 } 15883 } 15884 15885 if (needToVerify) { 15886 final int verificationId = mIntentFilterVerificationToken++; 15887 for (PackageParser.Activity a : pkg.activities) { 15888 for (ActivityIntentInfo filter : a.intents) { 15889 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15890 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15891 "Verification needed for IntentFilter:" + filter.toString()); 15892 mIntentFilterVerifier.addOneIntentFilterVerification( 15893 verifierUid, userId, verificationId, filter, packageName); 15894 count++; 15895 } 15896 } 15897 } 15898 } 15899 } 15900 15901 if (count > 0) { 15902 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15903 + " IntentFilter verification" + (count > 1 ? "s" : "") 15904 + " for userId:" + userId); 15905 mIntentFilterVerifier.startVerifications(userId); 15906 } else { 15907 if (DEBUG_DOMAIN_VERIFICATION) { 15908 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15909 } 15910 } 15911 } 15912 15913 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15914 final ComponentName cn = filter.activity.getComponentName(); 15915 final String packageName = cn.getPackageName(); 15916 15917 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15918 packageName); 15919 if (ivi == null) { 15920 return true; 15921 } 15922 int status = ivi.getStatus(); 15923 switch (status) { 15924 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15925 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15926 return true; 15927 15928 default: 15929 // Nothing to do 15930 return false; 15931 } 15932 } 15933 15934 private static boolean isMultiArch(ApplicationInfo info) { 15935 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15936 } 15937 15938 private static boolean isExternal(PackageParser.Package pkg) { 15939 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15940 } 15941 15942 private static boolean isExternal(PackageSetting ps) { 15943 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15944 } 15945 15946 private static boolean isEphemeral(PackageParser.Package pkg) { 15947 return pkg.applicationInfo.isEphemeralApp(); 15948 } 15949 15950 private static boolean isEphemeral(PackageSetting ps) { 15951 return ps.pkg != null && isEphemeral(ps.pkg); 15952 } 15953 15954 private static boolean isSystemApp(PackageParser.Package pkg) { 15955 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15956 } 15957 15958 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15959 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15960 } 15961 15962 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15963 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15964 } 15965 15966 private static boolean isSystemApp(PackageSetting ps) { 15967 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15968 } 15969 15970 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15971 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15972 } 15973 15974 private int packageFlagsToInstallFlags(PackageSetting ps) { 15975 int installFlags = 0; 15976 if (isEphemeral(ps)) { 15977 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15978 } 15979 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15980 // This existing package was an external ASEC install when we have 15981 // the external flag without a UUID 15982 installFlags |= PackageManager.INSTALL_EXTERNAL; 15983 } 15984 if (ps.isForwardLocked()) { 15985 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15986 } 15987 return installFlags; 15988 } 15989 15990 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15991 if (isExternal(pkg)) { 15992 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15993 return StorageManager.UUID_PRIMARY_PHYSICAL; 15994 } else { 15995 return pkg.volumeUuid; 15996 } 15997 } else { 15998 return StorageManager.UUID_PRIVATE_INTERNAL; 15999 } 16000 } 16001 16002 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16003 if (isExternal(pkg)) { 16004 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16005 return mSettings.getExternalVersion(); 16006 } else { 16007 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16008 } 16009 } else { 16010 return mSettings.getInternalVersion(); 16011 } 16012 } 16013 16014 private void deleteTempPackageFiles() { 16015 final FilenameFilter filter = new FilenameFilter() { 16016 public boolean accept(File dir, String name) { 16017 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16018 } 16019 }; 16020 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16021 file.delete(); 16022 } 16023 } 16024 16025 @Override 16026 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 16027 int flags) { 16028 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 16029 flags); 16030 } 16031 16032 @Override 16033 public void deletePackage(final String packageName, 16034 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16035 mContext.enforceCallingOrSelfPermission( 16036 android.Manifest.permission.DELETE_PACKAGES, null); 16037 Preconditions.checkNotNull(packageName); 16038 Preconditions.checkNotNull(observer); 16039 final int uid = Binder.getCallingUid(); 16040 if (!isOrphaned(packageName) 16041 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 16042 try { 16043 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16044 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16045 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16046 observer.onUserActionRequired(intent); 16047 } catch (RemoteException re) { 16048 } 16049 return; 16050 } 16051 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16052 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16053 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16054 mContext.enforceCallingOrSelfPermission( 16055 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16056 "deletePackage for user " + userId); 16057 } 16058 16059 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16060 try { 16061 observer.onPackageDeleted(packageName, 16062 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16063 } catch (RemoteException re) { 16064 } 16065 return; 16066 } 16067 16068 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 16069 try { 16070 observer.onPackageDeleted(packageName, 16071 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16072 } catch (RemoteException re) { 16073 } 16074 return; 16075 } 16076 16077 if (DEBUG_REMOVE) { 16078 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 16079 + " deleteAllUsers: " + deleteAllUsers ); 16080 } 16081 // Queue up an async operation since the package deletion may take a little while. 16082 mHandler.post(new Runnable() { 16083 public void run() { 16084 mHandler.removeCallbacks(this); 16085 int returnCode; 16086 if (!deleteAllUsers) { 16087 returnCode = deletePackageX(packageName, userId, deleteFlags); 16088 } else { 16089 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 16090 // If nobody is blocking uninstall, proceed with delete for all users 16091 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16092 returnCode = deletePackageX(packageName, userId, deleteFlags); 16093 } else { 16094 // Otherwise uninstall individually for users with blockUninstalls=false 16095 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16096 for (int userId : users) { 16097 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16098 returnCode = deletePackageX(packageName, userId, userFlags); 16099 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16100 Slog.w(TAG, "Package delete failed for user " + userId 16101 + ", returnCode " + returnCode); 16102 } 16103 } 16104 } 16105 // The app has only been marked uninstalled for certain users. 16106 // We still need to report that delete was blocked 16107 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16108 } 16109 } 16110 try { 16111 observer.onPackageDeleted(packageName, returnCode, null); 16112 } catch (RemoteException e) { 16113 Log.i(TAG, "Observer no longer exists."); 16114 } //end catch 16115 } //end run 16116 }); 16117 } 16118 16119 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 16120 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 16121 || callingUid == Process.SYSTEM_UID) { 16122 return true; 16123 } 16124 final int callingUserId = UserHandle.getUserId(callingUid); 16125 // If the caller installed the pkgName, then allow it to silently uninstall. 16126 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 16127 return true; 16128 } 16129 16130 // Allow package verifier to silently uninstall. 16131 if (mRequiredVerifierPackage != null && 16132 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 16133 return true; 16134 } 16135 16136 // Allow package uninstaller to silently uninstall. 16137 if (mRequiredUninstallerPackage != null && 16138 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 16139 return true; 16140 } 16141 16142 // Allow storage manager to silently uninstall. 16143 if (mStorageManagerPackage != null && 16144 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 16145 return true; 16146 } 16147 return false; 16148 } 16149 16150 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16151 int[] result = EMPTY_INT_ARRAY; 16152 for (int userId : userIds) { 16153 if (getBlockUninstallForUser(packageName, userId)) { 16154 result = ArrayUtils.appendInt(result, userId); 16155 } 16156 } 16157 return result; 16158 } 16159 16160 @Override 16161 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16162 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16163 } 16164 16165 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16166 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16167 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16168 try { 16169 if (dpm != null) { 16170 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16171 /* callingUserOnly =*/ false); 16172 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16173 : deviceOwnerComponentName.getPackageName(); 16174 // Does the package contains the device owner? 16175 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16176 // this check is probably not needed, since DO should be registered as a device 16177 // admin on some user too. (Original bug for this: b/17657954) 16178 if (packageName.equals(deviceOwnerPackageName)) { 16179 return true; 16180 } 16181 // Does it contain a device admin for any user? 16182 int[] users; 16183 if (userId == UserHandle.USER_ALL) { 16184 users = sUserManager.getUserIds(); 16185 } else { 16186 users = new int[]{userId}; 16187 } 16188 for (int i = 0; i < users.length; ++i) { 16189 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16190 return true; 16191 } 16192 } 16193 } 16194 } catch (RemoteException e) { 16195 } 16196 return false; 16197 } 16198 16199 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16200 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16201 } 16202 16203 /** 16204 * This method is an internal method that could be get invoked either 16205 * to delete an installed package or to clean up a failed installation. 16206 * After deleting an installed package, a broadcast is sent to notify any 16207 * listeners that the package has been removed. For cleaning up a failed 16208 * installation, the broadcast is not necessary since the package's 16209 * installation wouldn't have sent the initial broadcast either 16210 * The key steps in deleting a package are 16211 * deleting the package information in internal structures like mPackages, 16212 * deleting the packages base directories through installd 16213 * updating mSettings to reflect current status 16214 * persisting settings for later use 16215 * sending a broadcast if necessary 16216 */ 16217 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16218 final PackageRemovedInfo info = new PackageRemovedInfo(); 16219 final boolean res; 16220 16221 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16222 ? UserHandle.USER_ALL : userId; 16223 16224 if (isPackageDeviceAdmin(packageName, removeUser)) { 16225 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16226 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16227 } 16228 16229 PackageSetting uninstalledPs = null; 16230 16231 // for the uninstall-updates case and restricted profiles, remember the per- 16232 // user handle installed state 16233 int[] allUsers; 16234 synchronized (mPackages) { 16235 uninstalledPs = mSettings.mPackages.get(packageName); 16236 if (uninstalledPs == null) { 16237 Slog.w(TAG, "Not removing non-existent package " + packageName); 16238 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16239 } 16240 allUsers = sUserManager.getUserIds(); 16241 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16242 } 16243 16244 final int freezeUser; 16245 if (isUpdatedSystemApp(uninstalledPs) 16246 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16247 // We're downgrading a system app, which will apply to all users, so 16248 // freeze them all during the downgrade 16249 freezeUser = UserHandle.USER_ALL; 16250 } else { 16251 freezeUser = removeUser; 16252 } 16253 16254 synchronized (mInstallLock) { 16255 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16256 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16257 deleteFlags, "deletePackageX")) { 16258 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16259 deleteFlags | REMOVE_CHATTY, info, true, null); 16260 } 16261 synchronized (mPackages) { 16262 if (res) { 16263 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16264 } 16265 } 16266 } 16267 16268 if (res) { 16269 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16270 info.sendPackageRemovedBroadcasts(killApp); 16271 info.sendSystemPackageUpdatedBroadcasts(); 16272 info.sendSystemPackageAppearedBroadcasts(); 16273 } 16274 // Force a gc here. 16275 Runtime.getRuntime().gc(); 16276 // Delete the resources here after sending the broadcast to let 16277 // other processes clean up before deleting resources. 16278 if (info.args != null) { 16279 synchronized (mInstallLock) { 16280 info.args.doPostDeleteLI(true); 16281 } 16282 } 16283 16284 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16285 } 16286 16287 class PackageRemovedInfo { 16288 String removedPackage; 16289 int uid = -1; 16290 int removedAppId = -1; 16291 int[] origUsers; 16292 int[] removedUsers = null; 16293 boolean isRemovedPackageSystemUpdate = false; 16294 boolean isUpdate; 16295 boolean dataRemoved; 16296 boolean removedForAllUsers; 16297 // Clean up resources deleted packages. 16298 InstallArgs args = null; 16299 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16300 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16301 16302 void sendPackageRemovedBroadcasts(boolean killApp) { 16303 sendPackageRemovedBroadcastInternal(killApp); 16304 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16305 for (int i = 0; i < childCount; i++) { 16306 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16307 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16308 } 16309 } 16310 16311 void sendSystemPackageUpdatedBroadcasts() { 16312 if (isRemovedPackageSystemUpdate) { 16313 sendSystemPackageUpdatedBroadcastsInternal(); 16314 final int childCount = (removedChildPackages != null) 16315 ? removedChildPackages.size() : 0; 16316 for (int i = 0; i < childCount; i++) { 16317 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16318 if (childInfo.isRemovedPackageSystemUpdate) { 16319 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16320 } 16321 } 16322 } 16323 } 16324 16325 void sendSystemPackageAppearedBroadcasts() { 16326 final int packageCount = (appearedChildPackages != null) 16327 ? appearedChildPackages.size() : 0; 16328 for (int i = 0; i < packageCount; i++) { 16329 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16330 sendPackageAddedForNewUsers(installedInfo.name, true, 16331 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16332 } 16333 } 16334 16335 private void sendSystemPackageUpdatedBroadcastsInternal() { 16336 Bundle extras = new Bundle(2); 16337 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16338 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16339 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16340 extras, 0, null, null, null); 16341 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16342 extras, 0, null, null, null); 16343 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16344 null, 0, removedPackage, null, null); 16345 } 16346 16347 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16348 Bundle extras = new Bundle(2); 16349 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16350 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16351 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16352 if (isUpdate || isRemovedPackageSystemUpdate) { 16353 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16354 } 16355 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16356 if (removedPackage != null) { 16357 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16358 extras, 0, null, null, removedUsers); 16359 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16360 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16361 removedPackage, extras, 0, null, null, removedUsers); 16362 } 16363 } 16364 if (removedAppId >= 0) { 16365 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16366 removedUsers); 16367 } 16368 } 16369 } 16370 16371 /* 16372 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16373 * flag is not set, the data directory is removed as well. 16374 * make sure this flag is set for partially installed apps. If not its meaningless to 16375 * delete a partially installed application. 16376 */ 16377 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16378 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16379 String packageName = ps.name; 16380 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16381 // Retrieve object to delete permissions for shared user later on 16382 final PackageParser.Package deletedPkg; 16383 final PackageSetting deletedPs; 16384 // reader 16385 synchronized (mPackages) { 16386 deletedPkg = mPackages.get(packageName); 16387 deletedPs = mSettings.mPackages.get(packageName); 16388 if (outInfo != null) { 16389 outInfo.removedPackage = packageName; 16390 outInfo.removedUsers = deletedPs != null 16391 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16392 : null; 16393 } 16394 } 16395 16396 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16397 16398 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16399 final PackageParser.Package resolvedPkg; 16400 if (deletedPkg != null) { 16401 resolvedPkg = deletedPkg; 16402 } else { 16403 // We don't have a parsed package when it lives on an ejected 16404 // adopted storage device, so fake something together 16405 resolvedPkg = new PackageParser.Package(ps.name); 16406 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16407 } 16408 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16409 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16410 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16411 if (outInfo != null) { 16412 outInfo.dataRemoved = true; 16413 } 16414 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16415 } 16416 16417 // writer 16418 synchronized (mPackages) { 16419 if (deletedPs != null) { 16420 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16421 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16422 clearDefaultBrowserIfNeeded(packageName); 16423 if (outInfo != null) { 16424 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16425 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16426 } 16427 updatePermissionsLPw(deletedPs.name, null, 0); 16428 if (deletedPs.sharedUser != null) { 16429 // Remove permissions associated with package. Since runtime 16430 // permissions are per user we have to kill the removed package 16431 // or packages running under the shared user of the removed 16432 // package if revoking the permissions requested only by the removed 16433 // package is successful and this causes a change in gids. 16434 for (int userId : UserManagerService.getInstance().getUserIds()) { 16435 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16436 userId); 16437 if (userIdToKill == UserHandle.USER_ALL 16438 || userIdToKill >= UserHandle.USER_SYSTEM) { 16439 // If gids changed for this user, kill all affected packages. 16440 mHandler.post(new Runnable() { 16441 @Override 16442 public void run() { 16443 // This has to happen with no lock held. 16444 killApplication(deletedPs.name, deletedPs.appId, 16445 KILL_APP_REASON_GIDS_CHANGED); 16446 } 16447 }); 16448 break; 16449 } 16450 } 16451 } 16452 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16453 } 16454 // make sure to preserve per-user disabled state if this removal was just 16455 // a downgrade of a system app to the factory package 16456 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16457 if (DEBUG_REMOVE) { 16458 Slog.d(TAG, "Propagating install state across downgrade"); 16459 } 16460 for (int userId : allUserHandles) { 16461 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16462 if (DEBUG_REMOVE) { 16463 Slog.d(TAG, " user " + userId + " => " + installed); 16464 } 16465 ps.setInstalled(installed, userId); 16466 } 16467 } 16468 } 16469 // can downgrade to reader 16470 if (writeSettings) { 16471 // Save settings now 16472 mSettings.writeLPr(); 16473 } 16474 } 16475 if (outInfo != null) { 16476 // A user ID was deleted here. Go through all users and remove it 16477 // from KeyStore. 16478 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16479 } 16480 } 16481 16482 static boolean locationIsPrivileged(File path) { 16483 try { 16484 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16485 .getCanonicalPath(); 16486 return path.getCanonicalPath().startsWith(privilegedAppDir); 16487 } catch (IOException e) { 16488 Slog.e(TAG, "Unable to access code path " + path); 16489 } 16490 return false; 16491 } 16492 16493 /* 16494 * Tries to delete system package. 16495 */ 16496 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16497 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16498 boolean writeSettings) { 16499 if (deletedPs.parentPackageName != null) { 16500 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16501 return false; 16502 } 16503 16504 final boolean applyUserRestrictions 16505 = (allUserHandles != null) && (outInfo.origUsers != null); 16506 final PackageSetting disabledPs; 16507 // Confirm if the system package has been updated 16508 // An updated system app can be deleted. This will also have to restore 16509 // the system pkg from system partition 16510 // reader 16511 synchronized (mPackages) { 16512 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16513 } 16514 16515 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16516 + " disabledPs=" + disabledPs); 16517 16518 if (disabledPs == null) { 16519 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16520 return false; 16521 } else if (DEBUG_REMOVE) { 16522 Slog.d(TAG, "Deleting system pkg from data partition"); 16523 } 16524 16525 if (DEBUG_REMOVE) { 16526 if (applyUserRestrictions) { 16527 Slog.d(TAG, "Remembering install states:"); 16528 for (int userId : allUserHandles) { 16529 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16530 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16531 } 16532 } 16533 } 16534 16535 // Delete the updated package 16536 outInfo.isRemovedPackageSystemUpdate = true; 16537 if (outInfo.removedChildPackages != null) { 16538 final int childCount = (deletedPs.childPackageNames != null) 16539 ? deletedPs.childPackageNames.size() : 0; 16540 for (int i = 0; i < childCount; i++) { 16541 String childPackageName = deletedPs.childPackageNames.get(i); 16542 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16543 .contains(childPackageName)) { 16544 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16545 childPackageName); 16546 if (childInfo != null) { 16547 childInfo.isRemovedPackageSystemUpdate = true; 16548 } 16549 } 16550 } 16551 } 16552 16553 if (disabledPs.versionCode < deletedPs.versionCode) { 16554 // Delete data for downgrades 16555 flags &= ~PackageManager.DELETE_KEEP_DATA; 16556 } else { 16557 // Preserve data by setting flag 16558 flags |= PackageManager.DELETE_KEEP_DATA; 16559 } 16560 16561 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16562 outInfo, writeSettings, disabledPs.pkg); 16563 if (!ret) { 16564 return false; 16565 } 16566 16567 // writer 16568 synchronized (mPackages) { 16569 // Reinstate the old system package 16570 enableSystemPackageLPw(disabledPs.pkg); 16571 // Remove any native libraries from the upgraded package. 16572 removeNativeBinariesLI(deletedPs); 16573 } 16574 16575 // Install the system package 16576 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16577 int parseFlags = mDefParseFlags 16578 | PackageParser.PARSE_MUST_BE_APK 16579 | PackageParser.PARSE_IS_SYSTEM 16580 | PackageParser.PARSE_IS_SYSTEM_DIR; 16581 if (locationIsPrivileged(disabledPs.codePath)) { 16582 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16583 } 16584 16585 final PackageParser.Package newPkg; 16586 try { 16587 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16588 0 /* currentTime */, null); 16589 } catch (PackageManagerException e) { 16590 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16591 + e.getMessage()); 16592 return false; 16593 } 16594 try { 16595 // update shared libraries for the newly re-installed system package 16596 updateSharedLibrariesLPr(newPkg, null); 16597 } catch (PackageManagerException e) { 16598 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16599 } 16600 16601 prepareAppDataAfterInstallLIF(newPkg); 16602 16603 // writer 16604 synchronized (mPackages) { 16605 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16606 16607 // Propagate the permissions state as we do not want to drop on the floor 16608 // runtime permissions. The update permissions method below will take 16609 // care of removing obsolete permissions and grant install permissions. 16610 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16611 updatePermissionsLPw(newPkg.packageName, newPkg, 16612 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16613 16614 if (applyUserRestrictions) { 16615 if (DEBUG_REMOVE) { 16616 Slog.d(TAG, "Propagating install state across reinstall"); 16617 } 16618 for (int userId : allUserHandles) { 16619 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16620 if (DEBUG_REMOVE) { 16621 Slog.d(TAG, " user " + userId + " => " + installed); 16622 } 16623 ps.setInstalled(installed, userId); 16624 16625 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16626 } 16627 // Regardless of writeSettings we need to ensure that this restriction 16628 // state propagation is persisted 16629 mSettings.writeAllUsersPackageRestrictionsLPr(); 16630 } 16631 // can downgrade to reader here 16632 if (writeSettings) { 16633 mSettings.writeLPr(); 16634 } 16635 } 16636 return true; 16637 } 16638 16639 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16640 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16641 PackageRemovedInfo outInfo, boolean writeSettings, 16642 PackageParser.Package replacingPackage) { 16643 synchronized (mPackages) { 16644 if (outInfo != null) { 16645 outInfo.uid = ps.appId; 16646 } 16647 16648 if (outInfo != null && outInfo.removedChildPackages != null) { 16649 final int childCount = (ps.childPackageNames != null) 16650 ? ps.childPackageNames.size() : 0; 16651 for (int i = 0; i < childCount; i++) { 16652 String childPackageName = ps.childPackageNames.get(i); 16653 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16654 if (childPs == null) { 16655 return false; 16656 } 16657 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16658 childPackageName); 16659 if (childInfo != null) { 16660 childInfo.uid = childPs.appId; 16661 } 16662 } 16663 } 16664 } 16665 16666 // Delete package data from internal structures and also remove data if flag is set 16667 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16668 16669 // Delete the child packages data 16670 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16671 for (int i = 0; i < childCount; i++) { 16672 PackageSetting childPs; 16673 synchronized (mPackages) { 16674 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16675 } 16676 if (childPs != null) { 16677 PackageRemovedInfo childOutInfo = (outInfo != null 16678 && outInfo.removedChildPackages != null) 16679 ? outInfo.removedChildPackages.get(childPs.name) : null; 16680 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16681 && (replacingPackage != null 16682 && !replacingPackage.hasChildPackage(childPs.name)) 16683 ? flags & ~DELETE_KEEP_DATA : flags; 16684 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16685 deleteFlags, writeSettings); 16686 } 16687 } 16688 16689 // Delete application code and resources only for parent packages 16690 if (ps.parentPackageName == null) { 16691 if (deleteCodeAndResources && (outInfo != null)) { 16692 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16693 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16694 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16695 } 16696 } 16697 16698 return true; 16699 } 16700 16701 @Override 16702 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16703 int userId) { 16704 mContext.enforceCallingOrSelfPermission( 16705 android.Manifest.permission.DELETE_PACKAGES, null); 16706 synchronized (mPackages) { 16707 PackageSetting ps = mSettings.mPackages.get(packageName); 16708 if (ps == null) { 16709 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16710 return false; 16711 } 16712 if (!ps.getInstalled(userId)) { 16713 // Can't block uninstall for an app that is not installed or enabled. 16714 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16715 return false; 16716 } 16717 ps.setBlockUninstall(blockUninstall, userId); 16718 mSettings.writePackageRestrictionsLPr(userId); 16719 } 16720 return true; 16721 } 16722 16723 @Override 16724 public boolean getBlockUninstallForUser(String packageName, int userId) { 16725 synchronized (mPackages) { 16726 PackageSetting ps = mSettings.mPackages.get(packageName); 16727 if (ps == null) { 16728 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16729 return false; 16730 } 16731 return ps.getBlockUninstall(userId); 16732 } 16733 } 16734 16735 @Override 16736 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16737 int callingUid = Binder.getCallingUid(); 16738 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16739 throw new SecurityException( 16740 "setRequiredForSystemUser can only be run by the system or root"); 16741 } 16742 synchronized (mPackages) { 16743 PackageSetting ps = mSettings.mPackages.get(packageName); 16744 if (ps == null) { 16745 Log.w(TAG, "Package doesn't exist: " + packageName); 16746 return false; 16747 } 16748 if (systemUserApp) { 16749 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16750 } else { 16751 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16752 } 16753 mSettings.writeLPr(); 16754 } 16755 return true; 16756 } 16757 16758 /* 16759 * This method handles package deletion in general 16760 */ 16761 private boolean deletePackageLIF(String packageName, UserHandle user, 16762 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16763 PackageRemovedInfo outInfo, boolean writeSettings, 16764 PackageParser.Package replacingPackage) { 16765 if (packageName == null) { 16766 Slog.w(TAG, "Attempt to delete null packageName."); 16767 return false; 16768 } 16769 16770 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16771 16772 PackageSetting ps; 16773 16774 synchronized (mPackages) { 16775 ps = mSettings.mPackages.get(packageName); 16776 if (ps == null) { 16777 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16778 return false; 16779 } 16780 16781 if (ps.parentPackageName != null && (!isSystemApp(ps) 16782 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16783 if (DEBUG_REMOVE) { 16784 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16785 + ((user == null) ? UserHandle.USER_ALL : user)); 16786 } 16787 final int removedUserId = (user != null) ? user.getIdentifier() 16788 : UserHandle.USER_ALL; 16789 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16790 return false; 16791 } 16792 markPackageUninstalledForUserLPw(ps, user); 16793 scheduleWritePackageRestrictionsLocked(user); 16794 return true; 16795 } 16796 } 16797 16798 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16799 && user.getIdentifier() != UserHandle.USER_ALL)) { 16800 // The caller is asking that the package only be deleted for a single 16801 // user. To do this, we just mark its uninstalled state and delete 16802 // its data. If this is a system app, we only allow this to happen if 16803 // they have set the special DELETE_SYSTEM_APP which requests different 16804 // semantics than normal for uninstalling system apps. 16805 markPackageUninstalledForUserLPw(ps, user); 16806 16807 if (!isSystemApp(ps)) { 16808 // Do not uninstall the APK if an app should be cached 16809 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16810 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16811 // Other user still have this package installed, so all 16812 // we need to do is clear this user's data and save that 16813 // it is uninstalled. 16814 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16815 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16816 return false; 16817 } 16818 scheduleWritePackageRestrictionsLocked(user); 16819 return true; 16820 } else { 16821 // We need to set it back to 'installed' so the uninstall 16822 // broadcasts will be sent correctly. 16823 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16824 ps.setInstalled(true, user.getIdentifier()); 16825 } 16826 } else { 16827 // This is a system app, so we assume that the 16828 // other users still have this package installed, so all 16829 // we need to do is clear this user's data and save that 16830 // it is uninstalled. 16831 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16832 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16833 return false; 16834 } 16835 scheduleWritePackageRestrictionsLocked(user); 16836 return true; 16837 } 16838 } 16839 16840 // If we are deleting a composite package for all users, keep track 16841 // of result for each child. 16842 if (ps.childPackageNames != null && outInfo != null) { 16843 synchronized (mPackages) { 16844 final int childCount = ps.childPackageNames.size(); 16845 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16846 for (int i = 0; i < childCount; i++) { 16847 String childPackageName = ps.childPackageNames.get(i); 16848 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16849 childInfo.removedPackage = childPackageName; 16850 outInfo.removedChildPackages.put(childPackageName, childInfo); 16851 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16852 if (childPs != null) { 16853 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16854 } 16855 } 16856 } 16857 } 16858 16859 boolean ret = false; 16860 if (isSystemApp(ps)) { 16861 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16862 // When an updated system application is deleted we delete the existing resources 16863 // as well and fall back to existing code in system partition 16864 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16865 } else { 16866 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16867 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16868 outInfo, writeSettings, replacingPackage); 16869 } 16870 16871 // Take a note whether we deleted the package for all users 16872 if (outInfo != null) { 16873 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16874 if (outInfo.removedChildPackages != null) { 16875 synchronized (mPackages) { 16876 final int childCount = outInfo.removedChildPackages.size(); 16877 for (int i = 0; i < childCount; i++) { 16878 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16879 if (childInfo != null) { 16880 childInfo.removedForAllUsers = mPackages.get( 16881 childInfo.removedPackage) == null; 16882 } 16883 } 16884 } 16885 } 16886 // If we uninstalled an update to a system app there may be some 16887 // child packages that appeared as they are declared in the system 16888 // app but were not declared in the update. 16889 if (isSystemApp(ps)) { 16890 synchronized (mPackages) { 16891 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16892 final int childCount = (updatedPs.childPackageNames != null) 16893 ? updatedPs.childPackageNames.size() : 0; 16894 for (int i = 0; i < childCount; i++) { 16895 String childPackageName = updatedPs.childPackageNames.get(i); 16896 if (outInfo.removedChildPackages == null 16897 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16898 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16899 if (childPs == null) { 16900 continue; 16901 } 16902 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16903 installRes.name = childPackageName; 16904 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16905 installRes.pkg = mPackages.get(childPackageName); 16906 installRes.uid = childPs.pkg.applicationInfo.uid; 16907 if (outInfo.appearedChildPackages == null) { 16908 outInfo.appearedChildPackages = new ArrayMap<>(); 16909 } 16910 outInfo.appearedChildPackages.put(childPackageName, installRes); 16911 } 16912 } 16913 } 16914 } 16915 } 16916 16917 return ret; 16918 } 16919 16920 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16921 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16922 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16923 for (int nextUserId : userIds) { 16924 if (DEBUG_REMOVE) { 16925 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16926 } 16927 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16928 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16929 false /*hidden*/, false /*suspended*/, null, null, null, 16930 false /*blockUninstall*/, 16931 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16932 } 16933 } 16934 16935 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16936 PackageRemovedInfo outInfo) { 16937 final PackageParser.Package pkg; 16938 synchronized (mPackages) { 16939 pkg = mPackages.get(ps.name); 16940 } 16941 16942 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16943 : new int[] {userId}; 16944 for (int nextUserId : userIds) { 16945 if (DEBUG_REMOVE) { 16946 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16947 + nextUserId); 16948 } 16949 16950 destroyAppDataLIF(pkg, userId, 16951 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16952 destroyAppProfilesLIF(pkg, userId); 16953 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16954 schedulePackageCleaning(ps.name, nextUserId, false); 16955 synchronized (mPackages) { 16956 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16957 scheduleWritePackageRestrictionsLocked(nextUserId); 16958 } 16959 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16960 } 16961 } 16962 16963 if (outInfo != null) { 16964 outInfo.removedPackage = ps.name; 16965 outInfo.removedAppId = ps.appId; 16966 outInfo.removedUsers = userIds; 16967 } 16968 16969 return true; 16970 } 16971 16972 private final class ClearStorageConnection implements ServiceConnection { 16973 IMediaContainerService mContainerService; 16974 16975 @Override 16976 public void onServiceConnected(ComponentName name, IBinder service) { 16977 synchronized (this) { 16978 mContainerService = IMediaContainerService.Stub 16979 .asInterface(Binder.allowBlocking(service)); 16980 notifyAll(); 16981 } 16982 } 16983 16984 @Override 16985 public void onServiceDisconnected(ComponentName name) { 16986 } 16987 } 16988 16989 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16990 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16991 16992 final boolean mounted; 16993 if (Environment.isExternalStorageEmulated()) { 16994 mounted = true; 16995 } else { 16996 final String status = Environment.getExternalStorageState(); 16997 16998 mounted = status.equals(Environment.MEDIA_MOUNTED) 16999 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 17000 } 17001 17002 if (!mounted) { 17003 return; 17004 } 17005 17006 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 17007 int[] users; 17008 if (userId == UserHandle.USER_ALL) { 17009 users = sUserManager.getUserIds(); 17010 } else { 17011 users = new int[] { userId }; 17012 } 17013 final ClearStorageConnection conn = new ClearStorageConnection(); 17014 if (mContext.bindServiceAsUser( 17015 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 17016 try { 17017 for (int curUser : users) { 17018 long timeout = SystemClock.uptimeMillis() + 5000; 17019 synchronized (conn) { 17020 long now; 17021 while (conn.mContainerService == null && 17022 (now = SystemClock.uptimeMillis()) < timeout) { 17023 try { 17024 conn.wait(timeout - now); 17025 } catch (InterruptedException e) { 17026 } 17027 } 17028 } 17029 if (conn.mContainerService == null) { 17030 return; 17031 } 17032 17033 final UserEnvironment userEnv = new UserEnvironment(curUser); 17034 clearDirectory(conn.mContainerService, 17035 userEnv.buildExternalStorageAppCacheDirs(packageName)); 17036 if (allData) { 17037 clearDirectory(conn.mContainerService, 17038 userEnv.buildExternalStorageAppDataDirs(packageName)); 17039 clearDirectory(conn.mContainerService, 17040 userEnv.buildExternalStorageAppMediaDirs(packageName)); 17041 } 17042 } 17043 } finally { 17044 mContext.unbindService(conn); 17045 } 17046 } 17047 } 17048 17049 @Override 17050 public void clearApplicationProfileData(String packageName) { 17051 enforceSystemOrRoot("Only the system can clear all profile data"); 17052 17053 final PackageParser.Package pkg; 17054 synchronized (mPackages) { 17055 pkg = mPackages.get(packageName); 17056 } 17057 17058 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 17059 synchronized (mInstallLock) { 17060 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 17061 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 17062 true /* removeBaseMarker */); 17063 } 17064 } 17065 } 17066 17067 @Override 17068 public void clearApplicationUserData(final String packageName, 17069 final IPackageDataObserver observer, final int userId) { 17070 mContext.enforceCallingOrSelfPermission( 17071 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 17072 17073 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17074 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 17075 17076 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 17077 throw new SecurityException("Cannot clear data for a protected package: " 17078 + packageName); 17079 } 17080 // Queue up an async operation since the package deletion may take a little while. 17081 mHandler.post(new Runnable() { 17082 public void run() { 17083 mHandler.removeCallbacks(this); 17084 final boolean succeeded; 17085 try (PackageFreezer freezer = freezePackage(packageName, 17086 "clearApplicationUserData")) { 17087 synchronized (mInstallLock) { 17088 succeeded = clearApplicationUserDataLIF(packageName, userId); 17089 } 17090 clearExternalStorageDataSync(packageName, userId, true); 17091 } 17092 if (succeeded) { 17093 // invoke DeviceStorageMonitor's update method to clear any notifications 17094 DeviceStorageMonitorInternal dsm = LocalServices 17095 .getService(DeviceStorageMonitorInternal.class); 17096 if (dsm != null) { 17097 dsm.checkMemory(); 17098 } 17099 } 17100 if(observer != null) { 17101 try { 17102 observer.onRemoveCompleted(packageName, succeeded); 17103 } catch (RemoteException e) { 17104 Log.i(TAG, "Observer no longer exists."); 17105 } 17106 } //end if observer 17107 } //end run 17108 }); 17109 } 17110 17111 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 17112 if (packageName == null) { 17113 Slog.w(TAG, "Attempt to delete null packageName."); 17114 return false; 17115 } 17116 17117 // Try finding details about the requested package 17118 PackageParser.Package pkg; 17119 synchronized (mPackages) { 17120 pkg = mPackages.get(packageName); 17121 if (pkg == null) { 17122 final PackageSetting ps = mSettings.mPackages.get(packageName); 17123 if (ps != null) { 17124 pkg = ps.pkg; 17125 } 17126 } 17127 17128 if (pkg == null) { 17129 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17130 return false; 17131 } 17132 17133 PackageSetting ps = (PackageSetting) pkg.mExtras; 17134 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17135 } 17136 17137 clearAppDataLIF(pkg, userId, 17138 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17139 17140 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17141 removeKeystoreDataIfNeeded(userId, appId); 17142 17143 UserManagerInternal umInternal = getUserManagerInternal(); 17144 final int flags; 17145 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17146 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17147 } else if (umInternal.isUserRunning(userId)) { 17148 flags = StorageManager.FLAG_STORAGE_DE; 17149 } else { 17150 flags = 0; 17151 } 17152 prepareAppDataContentsLIF(pkg, userId, flags); 17153 17154 return true; 17155 } 17156 17157 /** 17158 * Reverts user permission state changes (permissions and flags) in 17159 * all packages for a given user. 17160 * 17161 * @param userId The device user for which to do a reset. 17162 */ 17163 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17164 final int packageCount = mPackages.size(); 17165 for (int i = 0; i < packageCount; i++) { 17166 PackageParser.Package pkg = mPackages.valueAt(i); 17167 PackageSetting ps = (PackageSetting) pkg.mExtras; 17168 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17169 } 17170 } 17171 17172 private void resetNetworkPolicies(int userId) { 17173 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17174 } 17175 17176 /** 17177 * Reverts user permission state changes (permissions and flags). 17178 * 17179 * @param ps The package for which to reset. 17180 * @param userId The device user for which to do a reset. 17181 */ 17182 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17183 final PackageSetting ps, final int userId) { 17184 if (ps.pkg == null) { 17185 return; 17186 } 17187 17188 // These are flags that can change base on user actions. 17189 final int userSettableMask = FLAG_PERMISSION_USER_SET 17190 | FLAG_PERMISSION_USER_FIXED 17191 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17192 | FLAG_PERMISSION_REVIEW_REQUIRED; 17193 17194 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17195 | FLAG_PERMISSION_POLICY_FIXED; 17196 17197 boolean writeInstallPermissions = false; 17198 boolean writeRuntimePermissions = false; 17199 17200 final int permissionCount = ps.pkg.requestedPermissions.size(); 17201 for (int i = 0; i < permissionCount; i++) { 17202 String permission = ps.pkg.requestedPermissions.get(i); 17203 17204 BasePermission bp = mSettings.mPermissions.get(permission); 17205 if (bp == null) { 17206 continue; 17207 } 17208 17209 // If shared user we just reset the state to which only this app contributed. 17210 if (ps.sharedUser != null) { 17211 boolean used = false; 17212 final int packageCount = ps.sharedUser.packages.size(); 17213 for (int j = 0; j < packageCount; j++) { 17214 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17215 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17216 && pkg.pkg.requestedPermissions.contains(permission)) { 17217 used = true; 17218 break; 17219 } 17220 } 17221 if (used) { 17222 continue; 17223 } 17224 } 17225 17226 PermissionsState permissionsState = ps.getPermissionsState(); 17227 17228 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17229 17230 // Always clear the user settable flags. 17231 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17232 bp.name) != null; 17233 // If permission review is enabled and this is a legacy app, mark the 17234 // permission as requiring a review as this is the initial state. 17235 int flags = 0; 17236 if (mPermissionReviewRequired 17237 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17238 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17239 } 17240 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17241 if (hasInstallState) { 17242 writeInstallPermissions = true; 17243 } else { 17244 writeRuntimePermissions = true; 17245 } 17246 } 17247 17248 // Below is only runtime permission handling. 17249 if (!bp.isRuntime()) { 17250 continue; 17251 } 17252 17253 // Never clobber system or policy. 17254 if ((oldFlags & policyOrSystemFlags) != 0) { 17255 continue; 17256 } 17257 17258 // If this permission was granted by default, make sure it is. 17259 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17260 if (permissionsState.grantRuntimePermission(bp, userId) 17261 != PERMISSION_OPERATION_FAILURE) { 17262 writeRuntimePermissions = true; 17263 } 17264 // If permission review is enabled the permissions for a legacy apps 17265 // are represented as constantly granted runtime ones, so don't revoke. 17266 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17267 // Otherwise, reset the permission. 17268 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17269 switch (revokeResult) { 17270 case PERMISSION_OPERATION_SUCCESS: 17271 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17272 writeRuntimePermissions = true; 17273 final int appId = ps.appId; 17274 mHandler.post(new Runnable() { 17275 @Override 17276 public void run() { 17277 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17278 } 17279 }); 17280 } break; 17281 } 17282 } 17283 } 17284 17285 // Synchronously write as we are taking permissions away. 17286 if (writeRuntimePermissions) { 17287 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17288 } 17289 17290 // Synchronously write as we are taking permissions away. 17291 if (writeInstallPermissions) { 17292 mSettings.writeLPr(); 17293 } 17294 } 17295 17296 /** 17297 * Remove entries from the keystore daemon. Will only remove it if the 17298 * {@code appId} is valid. 17299 */ 17300 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17301 if (appId < 0) { 17302 return; 17303 } 17304 17305 final KeyStore keyStore = KeyStore.getInstance(); 17306 if (keyStore != null) { 17307 if (userId == UserHandle.USER_ALL) { 17308 for (final int individual : sUserManager.getUserIds()) { 17309 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17310 } 17311 } else { 17312 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17313 } 17314 } else { 17315 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17316 } 17317 } 17318 17319 @Override 17320 public void deleteApplicationCacheFiles(final String packageName, 17321 final IPackageDataObserver observer) { 17322 final int userId = UserHandle.getCallingUserId(); 17323 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17324 } 17325 17326 @Override 17327 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17328 final IPackageDataObserver observer) { 17329 mContext.enforceCallingOrSelfPermission( 17330 android.Manifest.permission.DELETE_CACHE_FILES, null); 17331 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17332 /* requireFullPermission= */ true, /* checkShell= */ false, 17333 "delete application cache files"); 17334 17335 final PackageParser.Package pkg; 17336 synchronized (mPackages) { 17337 pkg = mPackages.get(packageName); 17338 } 17339 17340 // Queue up an async operation since the package deletion may take a little while. 17341 mHandler.post(new Runnable() { 17342 public void run() { 17343 synchronized (mInstallLock) { 17344 final int flags = StorageManager.FLAG_STORAGE_DE 17345 | StorageManager.FLAG_STORAGE_CE; 17346 // We're only clearing cache files, so we don't care if the 17347 // app is unfrozen and still able to run 17348 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17349 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17350 } 17351 clearExternalStorageDataSync(packageName, userId, false); 17352 if (observer != null) { 17353 try { 17354 observer.onRemoveCompleted(packageName, true); 17355 } catch (RemoteException e) { 17356 Log.i(TAG, "Observer no longer exists."); 17357 } 17358 } 17359 } 17360 }); 17361 } 17362 17363 @Override 17364 public void getPackageSizeInfo(final String packageName, int userHandle, 17365 final IPackageStatsObserver observer) { 17366 mContext.enforceCallingOrSelfPermission( 17367 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17368 if (packageName == null) { 17369 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17370 } 17371 17372 PackageStats stats = new PackageStats(packageName, userHandle); 17373 17374 /* 17375 * Queue up an async operation since the package measurement may take a 17376 * little while. 17377 */ 17378 Message msg = mHandler.obtainMessage(INIT_COPY); 17379 msg.obj = new MeasureParams(stats, observer); 17380 mHandler.sendMessage(msg); 17381 } 17382 17383 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17384 final PackageSetting ps; 17385 synchronized (mPackages) { 17386 ps = mSettings.mPackages.get(packageName); 17387 if (ps == null) { 17388 Slog.w(TAG, "Failed to find settings for " + packageName); 17389 return false; 17390 } 17391 } 17392 try { 17393 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17394 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17395 ps.getCeDataInode(userId), ps.codePathString, stats); 17396 } catch (InstallerException e) { 17397 Slog.w(TAG, String.valueOf(e)); 17398 return false; 17399 } 17400 17401 // For now, ignore code size of packages on system partition 17402 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17403 stats.codeSize = 0; 17404 } 17405 17406 return true; 17407 } 17408 17409 private int getUidTargetSdkVersionLockedLPr(int uid) { 17410 Object obj = mSettings.getUserIdLPr(uid); 17411 if (obj instanceof SharedUserSetting) { 17412 final SharedUserSetting sus = (SharedUserSetting) obj; 17413 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17414 final Iterator<PackageSetting> it = sus.packages.iterator(); 17415 while (it.hasNext()) { 17416 final PackageSetting ps = it.next(); 17417 if (ps.pkg != null) { 17418 int v = ps.pkg.applicationInfo.targetSdkVersion; 17419 if (v < vers) vers = v; 17420 } 17421 } 17422 return vers; 17423 } else if (obj instanceof PackageSetting) { 17424 final PackageSetting ps = (PackageSetting) obj; 17425 if (ps.pkg != null) { 17426 return ps.pkg.applicationInfo.targetSdkVersion; 17427 } 17428 } 17429 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17430 } 17431 17432 @Override 17433 public void addPreferredActivity(IntentFilter filter, int match, 17434 ComponentName[] set, ComponentName activity, int userId) { 17435 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17436 "Adding preferred"); 17437 } 17438 17439 private void addPreferredActivityInternal(IntentFilter filter, int match, 17440 ComponentName[] set, ComponentName activity, boolean always, int userId, 17441 String opname) { 17442 // writer 17443 int callingUid = Binder.getCallingUid(); 17444 enforceCrossUserPermission(callingUid, userId, 17445 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17446 if (filter.countActions() == 0) { 17447 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17448 return; 17449 } 17450 synchronized (mPackages) { 17451 if (mContext.checkCallingOrSelfPermission( 17452 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17453 != PackageManager.PERMISSION_GRANTED) { 17454 if (getUidTargetSdkVersionLockedLPr(callingUid) 17455 < Build.VERSION_CODES.FROYO) { 17456 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17457 + callingUid); 17458 return; 17459 } 17460 mContext.enforceCallingOrSelfPermission( 17461 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17462 } 17463 17464 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17465 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17466 + userId + ":"); 17467 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17468 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17469 scheduleWritePackageRestrictionsLocked(userId); 17470 postPreferredActivityChangedBroadcast(userId); 17471 } 17472 } 17473 17474 private void postPreferredActivityChangedBroadcast(int userId) { 17475 mHandler.post(() -> { 17476 final IActivityManager am = ActivityManager.getService(); 17477 if (am == null) { 17478 return; 17479 } 17480 17481 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17482 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17483 try { 17484 am.broadcastIntent(null, intent, null, null, 17485 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17486 null, false, false, userId); 17487 } catch (RemoteException e) { 17488 } 17489 }); 17490 } 17491 17492 @Override 17493 public void replacePreferredActivity(IntentFilter filter, int match, 17494 ComponentName[] set, ComponentName activity, int userId) { 17495 if (filter.countActions() != 1) { 17496 throw new IllegalArgumentException( 17497 "replacePreferredActivity expects filter to have only 1 action."); 17498 } 17499 if (filter.countDataAuthorities() != 0 17500 || filter.countDataPaths() != 0 17501 || filter.countDataSchemes() > 1 17502 || filter.countDataTypes() != 0) { 17503 throw new IllegalArgumentException( 17504 "replacePreferredActivity expects filter to have no data authorities, " + 17505 "paths, or types; and at most one scheme."); 17506 } 17507 17508 final int callingUid = Binder.getCallingUid(); 17509 enforceCrossUserPermission(callingUid, userId, 17510 true /* requireFullPermission */, false /* checkShell */, 17511 "replace preferred activity"); 17512 synchronized (mPackages) { 17513 if (mContext.checkCallingOrSelfPermission( 17514 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17515 != PackageManager.PERMISSION_GRANTED) { 17516 if (getUidTargetSdkVersionLockedLPr(callingUid) 17517 < Build.VERSION_CODES.FROYO) { 17518 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17519 + Binder.getCallingUid()); 17520 return; 17521 } 17522 mContext.enforceCallingOrSelfPermission( 17523 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17524 } 17525 17526 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17527 if (pir != null) { 17528 // Get all of the existing entries that exactly match this filter. 17529 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17530 if (existing != null && existing.size() == 1) { 17531 PreferredActivity cur = existing.get(0); 17532 if (DEBUG_PREFERRED) { 17533 Slog.i(TAG, "Checking replace of preferred:"); 17534 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17535 if (!cur.mPref.mAlways) { 17536 Slog.i(TAG, " -- CUR; not mAlways!"); 17537 } else { 17538 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17539 Slog.i(TAG, " -- CUR: mSet=" 17540 + Arrays.toString(cur.mPref.mSetComponents)); 17541 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17542 Slog.i(TAG, " -- NEW: mMatch=" 17543 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17544 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17545 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17546 } 17547 } 17548 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17549 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17550 && cur.mPref.sameSet(set)) { 17551 // Setting the preferred activity to what it happens to be already 17552 if (DEBUG_PREFERRED) { 17553 Slog.i(TAG, "Replacing with same preferred activity " 17554 + cur.mPref.mShortComponent + " for user " 17555 + userId + ":"); 17556 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17557 } 17558 return; 17559 } 17560 } 17561 17562 if (existing != null) { 17563 if (DEBUG_PREFERRED) { 17564 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17565 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17566 } 17567 for (int i = 0; i < existing.size(); i++) { 17568 PreferredActivity pa = existing.get(i); 17569 if (DEBUG_PREFERRED) { 17570 Slog.i(TAG, "Removing existing preferred activity " 17571 + pa.mPref.mComponent + ":"); 17572 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17573 } 17574 pir.removeFilter(pa); 17575 } 17576 } 17577 } 17578 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17579 "Replacing preferred"); 17580 } 17581 } 17582 17583 @Override 17584 public void clearPackagePreferredActivities(String packageName) { 17585 final int uid = Binder.getCallingUid(); 17586 // writer 17587 synchronized (mPackages) { 17588 PackageParser.Package pkg = mPackages.get(packageName); 17589 if (pkg == null || pkg.applicationInfo.uid != uid) { 17590 if (mContext.checkCallingOrSelfPermission( 17591 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17592 != PackageManager.PERMISSION_GRANTED) { 17593 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17594 < Build.VERSION_CODES.FROYO) { 17595 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17596 + Binder.getCallingUid()); 17597 return; 17598 } 17599 mContext.enforceCallingOrSelfPermission( 17600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17601 } 17602 } 17603 17604 int user = UserHandle.getCallingUserId(); 17605 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17606 scheduleWritePackageRestrictionsLocked(user); 17607 } 17608 } 17609 } 17610 17611 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17612 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17613 ArrayList<PreferredActivity> removed = null; 17614 boolean changed = false; 17615 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17616 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17617 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17618 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17619 continue; 17620 } 17621 Iterator<PreferredActivity> it = pir.filterIterator(); 17622 while (it.hasNext()) { 17623 PreferredActivity pa = it.next(); 17624 // Mark entry for removal only if it matches the package name 17625 // and the entry is of type "always". 17626 if (packageName == null || 17627 (pa.mPref.mComponent.getPackageName().equals(packageName) 17628 && pa.mPref.mAlways)) { 17629 if (removed == null) { 17630 removed = new ArrayList<PreferredActivity>(); 17631 } 17632 removed.add(pa); 17633 } 17634 } 17635 if (removed != null) { 17636 for (int j=0; j<removed.size(); j++) { 17637 PreferredActivity pa = removed.get(j); 17638 pir.removeFilter(pa); 17639 } 17640 changed = true; 17641 } 17642 } 17643 if (changed) { 17644 postPreferredActivityChangedBroadcast(userId); 17645 } 17646 return changed; 17647 } 17648 17649 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17650 private void clearIntentFilterVerificationsLPw(int userId) { 17651 final int packageCount = mPackages.size(); 17652 for (int i = 0; i < packageCount; i++) { 17653 PackageParser.Package pkg = mPackages.valueAt(i); 17654 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17655 } 17656 } 17657 17658 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17659 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17660 if (userId == UserHandle.USER_ALL) { 17661 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17662 sUserManager.getUserIds())) { 17663 for (int oneUserId : sUserManager.getUserIds()) { 17664 scheduleWritePackageRestrictionsLocked(oneUserId); 17665 } 17666 } 17667 } else { 17668 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17669 scheduleWritePackageRestrictionsLocked(userId); 17670 } 17671 } 17672 } 17673 17674 void clearDefaultBrowserIfNeeded(String packageName) { 17675 for (int oneUserId : sUserManager.getUserIds()) { 17676 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17677 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17678 if (packageName.equals(defaultBrowserPackageName)) { 17679 setDefaultBrowserPackageName(null, oneUserId); 17680 } 17681 } 17682 } 17683 17684 @Override 17685 public void resetApplicationPreferences(int userId) { 17686 mContext.enforceCallingOrSelfPermission( 17687 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17688 final long identity = Binder.clearCallingIdentity(); 17689 // writer 17690 try { 17691 synchronized (mPackages) { 17692 clearPackagePreferredActivitiesLPw(null, userId); 17693 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17694 // TODO: We have to reset the default SMS and Phone. This requires 17695 // significant refactoring to keep all default apps in the package 17696 // manager (cleaner but more work) or have the services provide 17697 // callbacks to the package manager to request a default app reset. 17698 applyFactoryDefaultBrowserLPw(userId); 17699 clearIntentFilterVerificationsLPw(userId); 17700 primeDomainVerificationsLPw(userId); 17701 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17702 scheduleWritePackageRestrictionsLocked(userId); 17703 } 17704 resetNetworkPolicies(userId); 17705 } finally { 17706 Binder.restoreCallingIdentity(identity); 17707 } 17708 } 17709 17710 @Override 17711 public int getPreferredActivities(List<IntentFilter> outFilters, 17712 List<ComponentName> outActivities, String packageName) { 17713 17714 int num = 0; 17715 final int userId = UserHandle.getCallingUserId(); 17716 // reader 17717 synchronized (mPackages) { 17718 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17719 if (pir != null) { 17720 final Iterator<PreferredActivity> it = pir.filterIterator(); 17721 while (it.hasNext()) { 17722 final PreferredActivity pa = it.next(); 17723 if (packageName == null 17724 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17725 && pa.mPref.mAlways)) { 17726 if (outFilters != null) { 17727 outFilters.add(new IntentFilter(pa)); 17728 } 17729 if (outActivities != null) { 17730 outActivities.add(pa.mPref.mComponent); 17731 } 17732 } 17733 } 17734 } 17735 } 17736 17737 return num; 17738 } 17739 17740 @Override 17741 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17742 int userId) { 17743 int callingUid = Binder.getCallingUid(); 17744 if (callingUid != Process.SYSTEM_UID) { 17745 throw new SecurityException( 17746 "addPersistentPreferredActivity can only be run by the system"); 17747 } 17748 if (filter.countActions() == 0) { 17749 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17750 return; 17751 } 17752 synchronized (mPackages) { 17753 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17754 ":"); 17755 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17756 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17757 new PersistentPreferredActivity(filter, activity)); 17758 scheduleWritePackageRestrictionsLocked(userId); 17759 postPreferredActivityChangedBroadcast(userId); 17760 } 17761 } 17762 17763 @Override 17764 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17765 int callingUid = Binder.getCallingUid(); 17766 if (callingUid != Process.SYSTEM_UID) { 17767 throw new SecurityException( 17768 "clearPackagePersistentPreferredActivities can only be run by the system"); 17769 } 17770 ArrayList<PersistentPreferredActivity> removed = null; 17771 boolean changed = false; 17772 synchronized (mPackages) { 17773 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17774 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17775 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17776 .valueAt(i); 17777 if (userId != thisUserId) { 17778 continue; 17779 } 17780 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17781 while (it.hasNext()) { 17782 PersistentPreferredActivity ppa = it.next(); 17783 // Mark entry for removal only if it matches the package name. 17784 if (ppa.mComponent.getPackageName().equals(packageName)) { 17785 if (removed == null) { 17786 removed = new ArrayList<PersistentPreferredActivity>(); 17787 } 17788 removed.add(ppa); 17789 } 17790 } 17791 if (removed != null) { 17792 for (int j=0; j<removed.size(); j++) { 17793 PersistentPreferredActivity ppa = removed.get(j); 17794 ppir.removeFilter(ppa); 17795 } 17796 changed = true; 17797 } 17798 } 17799 17800 if (changed) { 17801 scheduleWritePackageRestrictionsLocked(userId); 17802 postPreferredActivityChangedBroadcast(userId); 17803 } 17804 } 17805 } 17806 17807 /** 17808 * Common machinery for picking apart a restored XML blob and passing 17809 * it to a caller-supplied functor to be applied to the running system. 17810 */ 17811 private void restoreFromXml(XmlPullParser parser, int userId, 17812 String expectedStartTag, BlobXmlRestorer functor) 17813 throws IOException, XmlPullParserException { 17814 int type; 17815 while ((type = parser.next()) != XmlPullParser.START_TAG 17816 && type != XmlPullParser.END_DOCUMENT) { 17817 } 17818 if (type != XmlPullParser.START_TAG) { 17819 // oops didn't find a start tag?! 17820 if (DEBUG_BACKUP) { 17821 Slog.e(TAG, "Didn't find start tag during restore"); 17822 } 17823 return; 17824 } 17825Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17826 // this is supposed to be TAG_PREFERRED_BACKUP 17827 if (!expectedStartTag.equals(parser.getName())) { 17828 if (DEBUG_BACKUP) { 17829 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17830 } 17831 return; 17832 } 17833 17834 // skip interfering stuff, then we're aligned with the backing implementation 17835 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17836Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17837 functor.apply(parser, userId); 17838 } 17839 17840 private interface BlobXmlRestorer { 17841 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17842 } 17843 17844 /** 17845 * Non-Binder method, support for the backup/restore mechanism: write the 17846 * full set of preferred activities in its canonical XML format. Returns the 17847 * XML output as a byte array, or null if there is none. 17848 */ 17849 @Override 17850 public byte[] getPreferredActivityBackup(int userId) { 17851 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17852 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17853 } 17854 17855 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17856 try { 17857 final XmlSerializer serializer = new FastXmlSerializer(); 17858 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17859 serializer.startDocument(null, true); 17860 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17861 17862 synchronized (mPackages) { 17863 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17864 } 17865 17866 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17867 serializer.endDocument(); 17868 serializer.flush(); 17869 } catch (Exception e) { 17870 if (DEBUG_BACKUP) { 17871 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17872 } 17873 return null; 17874 } 17875 17876 return dataStream.toByteArray(); 17877 } 17878 17879 @Override 17880 public void restorePreferredActivities(byte[] backup, int userId) { 17881 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17882 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17883 } 17884 17885 try { 17886 final XmlPullParser parser = Xml.newPullParser(); 17887 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17888 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17889 new BlobXmlRestorer() { 17890 @Override 17891 public void apply(XmlPullParser parser, int userId) 17892 throws XmlPullParserException, IOException { 17893 synchronized (mPackages) { 17894 mSettings.readPreferredActivitiesLPw(parser, userId); 17895 } 17896 } 17897 } ); 17898 } catch (Exception e) { 17899 if (DEBUG_BACKUP) { 17900 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17901 } 17902 } 17903 } 17904 17905 /** 17906 * Non-Binder method, support for the backup/restore mechanism: write the 17907 * default browser (etc) settings in its canonical XML format. Returns the default 17908 * browser XML representation as a byte array, or null if there is none. 17909 */ 17910 @Override 17911 public byte[] getDefaultAppsBackup(int userId) { 17912 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17913 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17914 } 17915 17916 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17917 try { 17918 final XmlSerializer serializer = new FastXmlSerializer(); 17919 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17920 serializer.startDocument(null, true); 17921 serializer.startTag(null, TAG_DEFAULT_APPS); 17922 17923 synchronized (mPackages) { 17924 mSettings.writeDefaultAppsLPr(serializer, userId); 17925 } 17926 17927 serializer.endTag(null, TAG_DEFAULT_APPS); 17928 serializer.endDocument(); 17929 serializer.flush(); 17930 } catch (Exception e) { 17931 if (DEBUG_BACKUP) { 17932 Slog.e(TAG, "Unable to write default apps for backup", e); 17933 } 17934 return null; 17935 } 17936 17937 return dataStream.toByteArray(); 17938 } 17939 17940 @Override 17941 public void restoreDefaultApps(byte[] backup, int userId) { 17942 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17943 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17944 } 17945 17946 try { 17947 final XmlPullParser parser = Xml.newPullParser(); 17948 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17949 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17950 new BlobXmlRestorer() { 17951 @Override 17952 public void apply(XmlPullParser parser, int userId) 17953 throws XmlPullParserException, IOException { 17954 synchronized (mPackages) { 17955 mSettings.readDefaultAppsLPw(parser, userId); 17956 } 17957 } 17958 } ); 17959 } catch (Exception e) { 17960 if (DEBUG_BACKUP) { 17961 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17962 } 17963 } 17964 } 17965 17966 @Override 17967 public byte[] getIntentFilterVerificationBackup(int userId) { 17968 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17969 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17970 } 17971 17972 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17973 try { 17974 final XmlSerializer serializer = new FastXmlSerializer(); 17975 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17976 serializer.startDocument(null, true); 17977 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17978 17979 synchronized (mPackages) { 17980 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17981 } 17982 17983 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17984 serializer.endDocument(); 17985 serializer.flush(); 17986 } catch (Exception e) { 17987 if (DEBUG_BACKUP) { 17988 Slog.e(TAG, "Unable to write default apps for backup", e); 17989 } 17990 return null; 17991 } 17992 17993 return dataStream.toByteArray(); 17994 } 17995 17996 @Override 17997 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17998 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17999 throw new SecurityException("Only the system may call restorePreferredActivities()"); 18000 } 18001 18002 try { 18003 final XmlPullParser parser = Xml.newPullParser(); 18004 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18005 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 18006 new BlobXmlRestorer() { 18007 @Override 18008 public void apply(XmlPullParser parser, int userId) 18009 throws XmlPullParserException, IOException { 18010 synchronized (mPackages) { 18011 mSettings.readAllDomainVerificationsLPr(parser, userId); 18012 mSettings.writeLPr(); 18013 } 18014 } 18015 } ); 18016 } catch (Exception e) { 18017 if (DEBUG_BACKUP) { 18018 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18019 } 18020 } 18021 } 18022 18023 @Override 18024 public byte[] getPermissionGrantBackup(int userId) { 18025 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18026 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 18027 } 18028 18029 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18030 try { 18031 final XmlSerializer serializer = new FastXmlSerializer(); 18032 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18033 serializer.startDocument(null, true); 18034 serializer.startTag(null, TAG_PERMISSION_BACKUP); 18035 18036 synchronized (mPackages) { 18037 serializeRuntimePermissionGrantsLPr(serializer, userId); 18038 } 18039 18040 serializer.endTag(null, TAG_PERMISSION_BACKUP); 18041 serializer.endDocument(); 18042 serializer.flush(); 18043 } catch (Exception e) { 18044 if (DEBUG_BACKUP) { 18045 Slog.e(TAG, "Unable to write default apps for backup", e); 18046 } 18047 return null; 18048 } 18049 18050 return dataStream.toByteArray(); 18051 } 18052 18053 @Override 18054 public void restorePermissionGrants(byte[] backup, int userId) { 18055 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18056 throw new SecurityException("Only the system may call restorePermissionGrants()"); 18057 } 18058 18059 try { 18060 final XmlPullParser parser = Xml.newPullParser(); 18061 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18062 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 18063 new BlobXmlRestorer() { 18064 @Override 18065 public void apply(XmlPullParser parser, int userId) 18066 throws XmlPullParserException, IOException { 18067 synchronized (mPackages) { 18068 processRestoredPermissionGrantsLPr(parser, userId); 18069 } 18070 } 18071 } ); 18072 } catch (Exception e) { 18073 if (DEBUG_BACKUP) { 18074 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18075 } 18076 } 18077 } 18078 18079 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 18080 throws IOException { 18081 serializer.startTag(null, TAG_ALL_GRANTS); 18082 18083 final int N = mSettings.mPackages.size(); 18084 for (int i = 0; i < N; i++) { 18085 final PackageSetting ps = mSettings.mPackages.valueAt(i); 18086 boolean pkgGrantsKnown = false; 18087 18088 PermissionsState packagePerms = ps.getPermissionsState(); 18089 18090 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 18091 final int grantFlags = state.getFlags(); 18092 // only look at grants that are not system/policy fixed 18093 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 18094 final boolean isGranted = state.isGranted(); 18095 // And only back up the user-twiddled state bits 18096 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 18097 final String packageName = mSettings.mPackages.keyAt(i); 18098 if (!pkgGrantsKnown) { 18099 serializer.startTag(null, TAG_GRANT); 18100 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 18101 pkgGrantsKnown = true; 18102 } 18103 18104 final boolean userSet = 18105 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 18106 final boolean userFixed = 18107 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 18108 final boolean revoke = 18109 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 18110 18111 serializer.startTag(null, TAG_PERMISSION); 18112 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 18113 if (isGranted) { 18114 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 18115 } 18116 if (userSet) { 18117 serializer.attribute(null, ATTR_USER_SET, "true"); 18118 } 18119 if (userFixed) { 18120 serializer.attribute(null, ATTR_USER_FIXED, "true"); 18121 } 18122 if (revoke) { 18123 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 18124 } 18125 serializer.endTag(null, TAG_PERMISSION); 18126 } 18127 } 18128 } 18129 18130 if (pkgGrantsKnown) { 18131 serializer.endTag(null, TAG_GRANT); 18132 } 18133 } 18134 18135 serializer.endTag(null, TAG_ALL_GRANTS); 18136 } 18137 18138 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 18139 throws XmlPullParserException, IOException { 18140 String pkgName = null; 18141 int outerDepth = parser.getDepth(); 18142 int type; 18143 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 18144 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 18145 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18146 continue; 18147 } 18148 18149 final String tagName = parser.getName(); 18150 if (tagName.equals(TAG_GRANT)) { 18151 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18152 if (DEBUG_BACKUP) { 18153 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18154 } 18155 } else if (tagName.equals(TAG_PERMISSION)) { 18156 18157 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18158 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18159 18160 int newFlagSet = 0; 18161 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18162 newFlagSet |= FLAG_PERMISSION_USER_SET; 18163 } 18164 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18165 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18166 } 18167 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18168 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18169 } 18170 if (DEBUG_BACKUP) { 18171 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18172 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18173 } 18174 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18175 if (ps != null) { 18176 // Already installed so we apply the grant immediately 18177 if (DEBUG_BACKUP) { 18178 Slog.v(TAG, " + already installed; applying"); 18179 } 18180 PermissionsState perms = ps.getPermissionsState(); 18181 BasePermission bp = mSettings.mPermissions.get(permName); 18182 if (bp != null) { 18183 if (isGranted) { 18184 perms.grantRuntimePermission(bp, userId); 18185 } 18186 if (newFlagSet != 0) { 18187 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18188 } 18189 } 18190 } else { 18191 // Need to wait for post-restore install to apply the grant 18192 if (DEBUG_BACKUP) { 18193 Slog.v(TAG, " - not yet installed; saving for later"); 18194 } 18195 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18196 isGranted, newFlagSet, userId); 18197 } 18198 } else { 18199 PackageManagerService.reportSettingsProblem(Log.WARN, 18200 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18201 XmlUtils.skipCurrentTag(parser); 18202 } 18203 } 18204 18205 scheduleWriteSettingsLocked(); 18206 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18207 } 18208 18209 @Override 18210 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18211 int sourceUserId, int targetUserId, int flags) { 18212 mContext.enforceCallingOrSelfPermission( 18213 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18214 int callingUid = Binder.getCallingUid(); 18215 enforceOwnerRights(ownerPackage, callingUid); 18216 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18217 if (intentFilter.countActions() == 0) { 18218 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18219 return; 18220 } 18221 synchronized (mPackages) { 18222 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18223 ownerPackage, targetUserId, flags); 18224 CrossProfileIntentResolver resolver = 18225 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18226 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18227 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18228 if (existing != null) { 18229 int size = existing.size(); 18230 for (int i = 0; i < size; i++) { 18231 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18232 return; 18233 } 18234 } 18235 } 18236 resolver.addFilter(newFilter); 18237 scheduleWritePackageRestrictionsLocked(sourceUserId); 18238 } 18239 } 18240 18241 @Override 18242 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18243 mContext.enforceCallingOrSelfPermission( 18244 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18245 int callingUid = Binder.getCallingUid(); 18246 enforceOwnerRights(ownerPackage, callingUid); 18247 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18248 synchronized (mPackages) { 18249 CrossProfileIntentResolver resolver = 18250 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18251 ArraySet<CrossProfileIntentFilter> set = 18252 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18253 for (CrossProfileIntentFilter filter : set) { 18254 if (filter.getOwnerPackage().equals(ownerPackage)) { 18255 resolver.removeFilter(filter); 18256 } 18257 } 18258 scheduleWritePackageRestrictionsLocked(sourceUserId); 18259 } 18260 } 18261 18262 // Enforcing that callingUid is owning pkg on userId 18263 private void enforceOwnerRights(String pkg, int callingUid) { 18264 // The system owns everything. 18265 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18266 return; 18267 } 18268 int callingUserId = UserHandle.getUserId(callingUid); 18269 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18270 if (pi == null) { 18271 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18272 + callingUserId); 18273 } 18274 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18275 throw new SecurityException("Calling uid " + callingUid 18276 + " does not own package " + pkg); 18277 } 18278 } 18279 18280 @Override 18281 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18282 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18283 } 18284 18285 private Intent getHomeIntent() { 18286 Intent intent = new Intent(Intent.ACTION_MAIN); 18287 intent.addCategory(Intent.CATEGORY_HOME); 18288 intent.addCategory(Intent.CATEGORY_DEFAULT); 18289 return intent; 18290 } 18291 18292 private IntentFilter getHomeFilter() { 18293 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18294 filter.addCategory(Intent.CATEGORY_HOME); 18295 filter.addCategory(Intent.CATEGORY_DEFAULT); 18296 return filter; 18297 } 18298 18299 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18300 int userId) { 18301 Intent intent = getHomeIntent(); 18302 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18303 PackageManager.GET_META_DATA, userId); 18304 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18305 true, false, false, userId); 18306 18307 allHomeCandidates.clear(); 18308 if (list != null) { 18309 for (ResolveInfo ri : list) { 18310 allHomeCandidates.add(ri); 18311 } 18312 } 18313 return (preferred == null || preferred.activityInfo == null) 18314 ? null 18315 : new ComponentName(preferred.activityInfo.packageName, 18316 preferred.activityInfo.name); 18317 } 18318 18319 @Override 18320 public void setHomeActivity(ComponentName comp, int userId) { 18321 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18322 getHomeActivitiesAsUser(homeActivities, userId); 18323 18324 boolean found = false; 18325 18326 final int size = homeActivities.size(); 18327 final ComponentName[] set = new ComponentName[size]; 18328 for (int i = 0; i < size; i++) { 18329 final ResolveInfo candidate = homeActivities.get(i); 18330 final ActivityInfo info = candidate.activityInfo; 18331 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18332 set[i] = activityName; 18333 if (!found && activityName.equals(comp)) { 18334 found = true; 18335 } 18336 } 18337 if (!found) { 18338 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18339 + userId); 18340 } 18341 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18342 set, comp, userId); 18343 } 18344 18345 private @Nullable String getSetupWizardPackageName() { 18346 final Intent intent = new Intent(Intent.ACTION_MAIN); 18347 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18348 18349 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18350 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18351 | MATCH_DISABLED_COMPONENTS, 18352 UserHandle.myUserId()); 18353 if (matches.size() == 1) { 18354 return matches.get(0).getComponentInfo().packageName; 18355 } else { 18356 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18357 + ": matches=" + matches); 18358 return null; 18359 } 18360 } 18361 18362 private @Nullable String getStorageManagerPackageName() { 18363 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18364 18365 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18366 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18367 | MATCH_DISABLED_COMPONENTS, 18368 UserHandle.myUserId()); 18369 if (matches.size() == 1) { 18370 return matches.get(0).getComponentInfo().packageName; 18371 } else { 18372 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18373 + matches.size() + ": matches=" + matches); 18374 return null; 18375 } 18376 } 18377 18378 @Override 18379 public void setApplicationEnabledSetting(String appPackageName, 18380 int newState, int flags, int userId, String callingPackage) { 18381 if (!sUserManager.exists(userId)) return; 18382 if (callingPackage == null) { 18383 callingPackage = Integer.toString(Binder.getCallingUid()); 18384 } 18385 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18386 } 18387 18388 @Override 18389 public void setComponentEnabledSetting(ComponentName componentName, 18390 int newState, int flags, int userId) { 18391 if (!sUserManager.exists(userId)) return; 18392 setEnabledSetting(componentName.getPackageName(), 18393 componentName.getClassName(), newState, flags, userId, null); 18394 } 18395 18396 private void setEnabledSetting(final String packageName, String className, int newState, 18397 final int flags, int userId, String callingPackage) { 18398 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18399 || newState == COMPONENT_ENABLED_STATE_ENABLED 18400 || newState == COMPONENT_ENABLED_STATE_DISABLED 18401 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18402 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18403 throw new IllegalArgumentException("Invalid new component state: " 18404 + newState); 18405 } 18406 PackageSetting pkgSetting; 18407 final int uid = Binder.getCallingUid(); 18408 final int permission; 18409 if (uid == Process.SYSTEM_UID) { 18410 permission = PackageManager.PERMISSION_GRANTED; 18411 } else { 18412 permission = mContext.checkCallingOrSelfPermission( 18413 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18414 } 18415 enforceCrossUserPermission(uid, userId, 18416 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18417 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18418 boolean sendNow = false; 18419 boolean isApp = (className == null); 18420 String componentName = isApp ? packageName : className; 18421 int packageUid = -1; 18422 ArrayList<String> components; 18423 18424 // writer 18425 synchronized (mPackages) { 18426 pkgSetting = mSettings.mPackages.get(packageName); 18427 if (pkgSetting == null) { 18428 if (className == null) { 18429 throw new IllegalArgumentException("Unknown package: " + packageName); 18430 } 18431 throw new IllegalArgumentException( 18432 "Unknown component: " + packageName + "/" + className); 18433 } 18434 } 18435 18436 // Limit who can change which apps 18437 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18438 // Don't allow apps that don't have permission to modify other apps 18439 if (!allowedByPermission) { 18440 throw new SecurityException( 18441 "Permission Denial: attempt to change component state from pid=" 18442 + Binder.getCallingPid() 18443 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18444 } 18445 // Don't allow changing protected packages. 18446 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18447 throw new SecurityException("Cannot disable a protected package: " + packageName); 18448 } 18449 } 18450 18451 synchronized (mPackages) { 18452 if (uid == Process.SHELL_UID 18453 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18454 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18455 // unless it is a test package. 18456 int oldState = pkgSetting.getEnabled(userId); 18457 if (className == null 18458 && 18459 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18460 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18461 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18462 && 18463 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18464 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18465 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18466 // ok 18467 } else { 18468 throw new SecurityException( 18469 "Shell cannot change component state for " + packageName + "/" 18470 + className + " to " + newState); 18471 } 18472 } 18473 if (className == null) { 18474 // We're dealing with an application/package level state change 18475 if (pkgSetting.getEnabled(userId) == newState) { 18476 // Nothing to do 18477 return; 18478 } 18479 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18480 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18481 // Don't care about who enables an app. 18482 callingPackage = null; 18483 } 18484 pkgSetting.setEnabled(newState, userId, callingPackage); 18485 // pkgSetting.pkg.mSetEnabled = newState; 18486 } else { 18487 // We're dealing with a component level state change 18488 // First, verify that this is a valid class name. 18489 PackageParser.Package pkg = pkgSetting.pkg; 18490 if (pkg == null || !pkg.hasComponentClassName(className)) { 18491 if (pkg != null && 18492 pkg.applicationInfo.targetSdkVersion >= 18493 Build.VERSION_CODES.JELLY_BEAN) { 18494 throw new IllegalArgumentException("Component class " + className 18495 + " does not exist in " + packageName); 18496 } else { 18497 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18498 + className + " does not exist in " + packageName); 18499 } 18500 } 18501 switch (newState) { 18502 case COMPONENT_ENABLED_STATE_ENABLED: 18503 if (!pkgSetting.enableComponentLPw(className, userId)) { 18504 return; 18505 } 18506 break; 18507 case COMPONENT_ENABLED_STATE_DISABLED: 18508 if (!pkgSetting.disableComponentLPw(className, userId)) { 18509 return; 18510 } 18511 break; 18512 case COMPONENT_ENABLED_STATE_DEFAULT: 18513 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18514 return; 18515 } 18516 break; 18517 default: 18518 Slog.e(TAG, "Invalid new component state: " + newState); 18519 return; 18520 } 18521 } 18522 scheduleWritePackageRestrictionsLocked(userId); 18523 components = mPendingBroadcasts.get(userId, packageName); 18524 final boolean newPackage = components == null; 18525 if (newPackage) { 18526 components = new ArrayList<String>(); 18527 } 18528 if (!components.contains(componentName)) { 18529 components.add(componentName); 18530 } 18531 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18532 sendNow = true; 18533 // Purge entry from pending broadcast list if another one exists already 18534 // since we are sending one right away. 18535 mPendingBroadcasts.remove(userId, packageName); 18536 } else { 18537 if (newPackage) { 18538 mPendingBroadcasts.put(userId, packageName, components); 18539 } 18540 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18541 // Schedule a message 18542 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18543 } 18544 } 18545 } 18546 18547 long callingId = Binder.clearCallingIdentity(); 18548 try { 18549 if (sendNow) { 18550 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18551 sendPackageChangedBroadcast(packageName, 18552 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18553 } 18554 } finally { 18555 Binder.restoreCallingIdentity(callingId); 18556 } 18557 } 18558 18559 @Override 18560 public void flushPackageRestrictionsAsUser(int userId) { 18561 if (!sUserManager.exists(userId)) { 18562 return; 18563 } 18564 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18565 false /* checkShell */, "flushPackageRestrictions"); 18566 synchronized (mPackages) { 18567 mSettings.writePackageRestrictionsLPr(userId); 18568 mDirtyUsers.remove(userId); 18569 if (mDirtyUsers.isEmpty()) { 18570 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18571 } 18572 } 18573 } 18574 18575 private void sendPackageChangedBroadcast(String packageName, 18576 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18577 if (DEBUG_INSTALL) 18578 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18579 + componentNames); 18580 Bundle extras = new Bundle(4); 18581 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18582 String nameList[] = new String[componentNames.size()]; 18583 componentNames.toArray(nameList); 18584 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18585 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18586 extras.putInt(Intent.EXTRA_UID, packageUid); 18587 // If this is not reporting a change of the overall package, then only send it 18588 // to registered receivers. We don't want to launch a swath of apps for every 18589 // little component state change. 18590 final int flags = !componentNames.contains(packageName) 18591 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18592 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18593 new int[] {UserHandle.getUserId(packageUid)}); 18594 } 18595 18596 @Override 18597 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18598 if (!sUserManager.exists(userId)) return; 18599 final int uid = Binder.getCallingUid(); 18600 final int permission = mContext.checkCallingOrSelfPermission( 18601 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18602 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18603 enforceCrossUserPermission(uid, userId, 18604 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18605 // writer 18606 synchronized (mPackages) { 18607 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18608 allowedByPermission, uid, userId)) { 18609 scheduleWritePackageRestrictionsLocked(userId); 18610 } 18611 } 18612 } 18613 18614 @Override 18615 public String getInstallerPackageName(String packageName) { 18616 // reader 18617 synchronized (mPackages) { 18618 return mSettings.getInstallerPackageNameLPr(packageName); 18619 } 18620 } 18621 18622 public boolean isOrphaned(String packageName) { 18623 // reader 18624 synchronized (mPackages) { 18625 return mSettings.isOrphaned(packageName); 18626 } 18627 } 18628 18629 @Override 18630 public int getApplicationEnabledSetting(String packageName, int userId) { 18631 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18632 int uid = Binder.getCallingUid(); 18633 enforceCrossUserPermission(uid, userId, 18634 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18635 // reader 18636 synchronized (mPackages) { 18637 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18638 } 18639 } 18640 18641 @Override 18642 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18643 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18644 int uid = Binder.getCallingUid(); 18645 enforceCrossUserPermission(uid, userId, 18646 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18647 // reader 18648 synchronized (mPackages) { 18649 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18650 } 18651 } 18652 18653 @Override 18654 public void enterSafeMode() { 18655 enforceSystemOrRoot("Only the system can request entering safe mode"); 18656 18657 if (!mSystemReady) { 18658 mSafeMode = true; 18659 } 18660 } 18661 18662 @Override 18663 public void systemReady() { 18664 mSystemReady = true; 18665 18666 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18667 // disabled after already being started. 18668 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18669 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18670 18671 // Read the compatibilty setting when the system is ready. 18672 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18673 mContext.getContentResolver(), 18674 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18675 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18676 if (DEBUG_SETTINGS) { 18677 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18678 } 18679 18680 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18681 18682 synchronized (mPackages) { 18683 // Verify that all of the preferred activity components actually 18684 // exist. It is possible for applications to be updated and at 18685 // that point remove a previously declared activity component that 18686 // had been set as a preferred activity. We try to clean this up 18687 // the next time we encounter that preferred activity, but it is 18688 // possible for the user flow to never be able to return to that 18689 // situation so here we do a sanity check to make sure we haven't 18690 // left any junk around. 18691 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18692 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18693 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18694 removed.clear(); 18695 for (PreferredActivity pa : pir.filterSet()) { 18696 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18697 removed.add(pa); 18698 } 18699 } 18700 if (removed.size() > 0) { 18701 for (int r=0; r<removed.size(); r++) { 18702 PreferredActivity pa = removed.get(r); 18703 Slog.w(TAG, "Removing dangling preferred activity: " 18704 + pa.mPref.mComponent); 18705 pir.removeFilter(pa); 18706 } 18707 mSettings.writePackageRestrictionsLPr( 18708 mSettings.mPreferredActivities.keyAt(i)); 18709 } 18710 } 18711 18712 for (int userId : UserManagerService.getInstance().getUserIds()) { 18713 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18714 grantPermissionsUserIds = ArrayUtils.appendInt( 18715 grantPermissionsUserIds, userId); 18716 } 18717 } 18718 } 18719 sUserManager.systemReady(); 18720 18721 // If we upgraded grant all default permissions before kicking off. 18722 for (int userId : grantPermissionsUserIds) { 18723 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18724 } 18725 18726 // If we did not grant default permissions, we preload from this the 18727 // default permission exceptions lazily to ensure we don't hit the 18728 // disk on a new user creation. 18729 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18730 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18731 } 18732 18733 // Kick off any messages waiting for system ready 18734 if (mPostSystemReadyMessages != null) { 18735 for (Message msg : mPostSystemReadyMessages) { 18736 msg.sendToTarget(); 18737 } 18738 mPostSystemReadyMessages = null; 18739 } 18740 18741 // Watch for external volumes that come and go over time 18742 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18743 storage.registerListener(mStorageListener); 18744 18745 mInstallerService.systemReady(); 18746 mPackageDexOptimizer.systemReady(); 18747 18748 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18749 StorageManagerInternal.class); 18750 StorageManagerInternal.addExternalStoragePolicy( 18751 new StorageManagerInternal.ExternalStorageMountPolicy() { 18752 @Override 18753 public int getMountMode(int uid, String packageName) { 18754 if (Process.isIsolated(uid)) { 18755 return Zygote.MOUNT_EXTERNAL_NONE; 18756 } 18757 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18758 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18759 } 18760 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18761 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18762 } 18763 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18764 return Zygote.MOUNT_EXTERNAL_READ; 18765 } 18766 return Zygote.MOUNT_EXTERNAL_WRITE; 18767 } 18768 18769 @Override 18770 public boolean hasExternalStorage(int uid, String packageName) { 18771 return true; 18772 } 18773 }); 18774 18775 // Now that we're mostly running, clean up stale users and apps 18776 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18777 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18778 } 18779 18780 @Override 18781 public boolean isSafeMode() { 18782 return mSafeMode; 18783 } 18784 18785 @Override 18786 public boolean hasSystemUidErrors() { 18787 return mHasSystemUidErrors; 18788 } 18789 18790 static String arrayToString(int[] array) { 18791 StringBuffer buf = new StringBuffer(128); 18792 buf.append('['); 18793 if (array != null) { 18794 for (int i=0; i<array.length; i++) { 18795 if (i > 0) buf.append(", "); 18796 buf.append(array[i]); 18797 } 18798 } 18799 buf.append(']'); 18800 return buf.toString(); 18801 } 18802 18803 static class DumpState { 18804 public static final int DUMP_LIBS = 1 << 0; 18805 public static final int DUMP_FEATURES = 1 << 1; 18806 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18807 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18808 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18809 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18810 public static final int DUMP_PERMISSIONS = 1 << 6; 18811 public static final int DUMP_PACKAGES = 1 << 7; 18812 public static final int DUMP_SHARED_USERS = 1 << 8; 18813 public static final int DUMP_MESSAGES = 1 << 9; 18814 public static final int DUMP_PROVIDERS = 1 << 10; 18815 public static final int DUMP_VERIFIERS = 1 << 11; 18816 public static final int DUMP_PREFERRED = 1 << 12; 18817 public static final int DUMP_PREFERRED_XML = 1 << 13; 18818 public static final int DUMP_KEYSETS = 1 << 14; 18819 public static final int DUMP_VERSION = 1 << 15; 18820 public static final int DUMP_INSTALLS = 1 << 16; 18821 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18822 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18823 public static final int DUMP_FROZEN = 1 << 19; 18824 public static final int DUMP_DEXOPT = 1 << 20; 18825 public static final int DUMP_COMPILER_STATS = 1 << 21; 18826 18827 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18828 18829 private int mTypes; 18830 18831 private int mOptions; 18832 18833 private boolean mTitlePrinted; 18834 18835 private SharedUserSetting mSharedUser; 18836 18837 public boolean isDumping(int type) { 18838 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18839 return true; 18840 } 18841 18842 return (mTypes & type) != 0; 18843 } 18844 18845 public void setDump(int type) { 18846 mTypes |= type; 18847 } 18848 18849 public boolean isOptionEnabled(int option) { 18850 return (mOptions & option) != 0; 18851 } 18852 18853 public void setOptionEnabled(int option) { 18854 mOptions |= option; 18855 } 18856 18857 public boolean onTitlePrinted() { 18858 final boolean printed = mTitlePrinted; 18859 mTitlePrinted = true; 18860 return printed; 18861 } 18862 18863 public boolean getTitlePrinted() { 18864 return mTitlePrinted; 18865 } 18866 18867 public void setTitlePrinted(boolean enabled) { 18868 mTitlePrinted = enabled; 18869 } 18870 18871 public SharedUserSetting getSharedUser() { 18872 return mSharedUser; 18873 } 18874 18875 public void setSharedUser(SharedUserSetting user) { 18876 mSharedUser = user; 18877 } 18878 } 18879 18880 @Override 18881 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18882 FileDescriptor err, String[] args, ShellCallback callback, 18883 ResultReceiver resultReceiver) { 18884 (new PackageManagerShellCommand(this)).exec( 18885 this, in, out, err, args, callback, resultReceiver); 18886 } 18887 18888 @Override 18889 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18890 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18891 != PackageManager.PERMISSION_GRANTED) { 18892 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18893 + Binder.getCallingPid() 18894 + ", uid=" + Binder.getCallingUid() 18895 + " without permission " 18896 + android.Manifest.permission.DUMP); 18897 return; 18898 } 18899 18900 DumpState dumpState = new DumpState(); 18901 boolean fullPreferred = false; 18902 boolean checkin = false; 18903 18904 String packageName = null; 18905 ArraySet<String> permissionNames = null; 18906 18907 int opti = 0; 18908 while (opti < args.length) { 18909 String opt = args[opti]; 18910 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18911 break; 18912 } 18913 opti++; 18914 18915 if ("-a".equals(opt)) { 18916 // Right now we only know how to print all. 18917 } else if ("-h".equals(opt)) { 18918 pw.println("Package manager dump options:"); 18919 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18920 pw.println(" --checkin: dump for a checkin"); 18921 pw.println(" -f: print details of intent filters"); 18922 pw.println(" -h: print this help"); 18923 pw.println(" cmd may be one of:"); 18924 pw.println(" l[ibraries]: list known shared libraries"); 18925 pw.println(" f[eatures]: list device features"); 18926 pw.println(" k[eysets]: print known keysets"); 18927 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18928 pw.println(" perm[issions]: dump permissions"); 18929 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18930 pw.println(" pref[erred]: print preferred package settings"); 18931 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18932 pw.println(" prov[iders]: dump content providers"); 18933 pw.println(" p[ackages]: dump installed packages"); 18934 pw.println(" s[hared-users]: dump shared user IDs"); 18935 pw.println(" m[essages]: print collected runtime messages"); 18936 pw.println(" v[erifiers]: print package verifier info"); 18937 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18938 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18939 pw.println(" version: print database version info"); 18940 pw.println(" write: write current settings now"); 18941 pw.println(" installs: details about install sessions"); 18942 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18943 pw.println(" dexopt: dump dexopt state"); 18944 pw.println(" compiler-stats: dump compiler statistics"); 18945 pw.println(" <package.name>: info about given package"); 18946 return; 18947 } else if ("--checkin".equals(opt)) { 18948 checkin = true; 18949 } else if ("-f".equals(opt)) { 18950 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18951 } else { 18952 pw.println("Unknown argument: " + opt + "; use -h for help"); 18953 } 18954 } 18955 18956 // Is the caller requesting to dump a particular piece of data? 18957 if (opti < args.length) { 18958 String cmd = args[opti]; 18959 opti++; 18960 // Is this a package name? 18961 if ("android".equals(cmd) || cmd.contains(".")) { 18962 packageName = cmd; 18963 // When dumping a single package, we always dump all of its 18964 // filter information since the amount of data will be reasonable. 18965 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18966 } else if ("check-permission".equals(cmd)) { 18967 if (opti >= args.length) { 18968 pw.println("Error: check-permission missing permission argument"); 18969 return; 18970 } 18971 String perm = args[opti]; 18972 opti++; 18973 if (opti >= args.length) { 18974 pw.println("Error: check-permission missing package argument"); 18975 return; 18976 } 18977 String pkg = args[opti]; 18978 opti++; 18979 int user = UserHandle.getUserId(Binder.getCallingUid()); 18980 if (opti < args.length) { 18981 try { 18982 user = Integer.parseInt(args[opti]); 18983 } catch (NumberFormatException e) { 18984 pw.println("Error: check-permission user argument is not a number: " 18985 + args[opti]); 18986 return; 18987 } 18988 } 18989 pw.println(checkPermission(perm, pkg, user)); 18990 return; 18991 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18992 dumpState.setDump(DumpState.DUMP_LIBS); 18993 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18994 dumpState.setDump(DumpState.DUMP_FEATURES); 18995 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18996 if (opti >= args.length) { 18997 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18998 | DumpState.DUMP_SERVICE_RESOLVERS 18999 | DumpState.DUMP_RECEIVER_RESOLVERS 19000 | DumpState.DUMP_CONTENT_RESOLVERS); 19001 } else { 19002 while (opti < args.length) { 19003 String name = args[opti]; 19004 if ("a".equals(name) || "activity".equals(name)) { 19005 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 19006 } else if ("s".equals(name) || "service".equals(name)) { 19007 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 19008 } else if ("r".equals(name) || "receiver".equals(name)) { 19009 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 19010 } else if ("c".equals(name) || "content".equals(name)) { 19011 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 19012 } else { 19013 pw.println("Error: unknown resolver table type: " + name); 19014 return; 19015 } 19016 opti++; 19017 } 19018 } 19019 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 19020 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 19021 } else if ("permission".equals(cmd)) { 19022 if (opti >= args.length) { 19023 pw.println("Error: permission requires permission name"); 19024 return; 19025 } 19026 permissionNames = new ArraySet<>(); 19027 while (opti < args.length) { 19028 permissionNames.add(args[opti]); 19029 opti++; 19030 } 19031 dumpState.setDump(DumpState.DUMP_PERMISSIONS 19032 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 19033 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 19034 dumpState.setDump(DumpState.DUMP_PREFERRED); 19035 } else if ("preferred-xml".equals(cmd)) { 19036 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 19037 if (opti < args.length && "--full".equals(args[opti])) { 19038 fullPreferred = true; 19039 opti++; 19040 } 19041 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 19042 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 19043 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 19044 dumpState.setDump(DumpState.DUMP_PACKAGES); 19045 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 19046 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 19047 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 19048 dumpState.setDump(DumpState.DUMP_PROVIDERS); 19049 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 19050 dumpState.setDump(DumpState.DUMP_MESSAGES); 19051 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 19052 dumpState.setDump(DumpState.DUMP_VERIFIERS); 19053 } else if ("i".equals(cmd) || "ifv".equals(cmd) 19054 || "intent-filter-verifiers".equals(cmd)) { 19055 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 19056 } else if ("version".equals(cmd)) { 19057 dumpState.setDump(DumpState.DUMP_VERSION); 19058 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 19059 dumpState.setDump(DumpState.DUMP_KEYSETS); 19060 } else if ("installs".equals(cmd)) { 19061 dumpState.setDump(DumpState.DUMP_INSTALLS); 19062 } else if ("frozen".equals(cmd)) { 19063 dumpState.setDump(DumpState.DUMP_FROZEN); 19064 } else if ("dexopt".equals(cmd)) { 19065 dumpState.setDump(DumpState.DUMP_DEXOPT); 19066 } else if ("compiler-stats".equals(cmd)) { 19067 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 19068 } else if ("write".equals(cmd)) { 19069 synchronized (mPackages) { 19070 mSettings.writeLPr(); 19071 pw.println("Settings written."); 19072 return; 19073 } 19074 } 19075 } 19076 19077 if (checkin) { 19078 pw.println("vers,1"); 19079 } 19080 19081 // reader 19082 synchronized (mPackages) { 19083 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 19084 if (!checkin) { 19085 if (dumpState.onTitlePrinted()) 19086 pw.println(); 19087 pw.println("Database versions:"); 19088 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 19089 } 19090 } 19091 19092 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 19093 if (!checkin) { 19094 if (dumpState.onTitlePrinted()) 19095 pw.println(); 19096 pw.println("Verifiers:"); 19097 pw.print(" Required: "); 19098 pw.print(mRequiredVerifierPackage); 19099 pw.print(" (uid="); 19100 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19101 UserHandle.USER_SYSTEM)); 19102 pw.println(")"); 19103 } else if (mRequiredVerifierPackage != null) { 19104 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 19105 pw.print(","); 19106 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19107 UserHandle.USER_SYSTEM)); 19108 } 19109 } 19110 19111 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 19112 packageName == null) { 19113 if (mIntentFilterVerifierComponent != null) { 19114 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 19115 if (!checkin) { 19116 if (dumpState.onTitlePrinted()) 19117 pw.println(); 19118 pw.println("Intent Filter Verifier:"); 19119 pw.print(" Using: "); 19120 pw.print(verifierPackageName); 19121 pw.print(" (uid="); 19122 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19123 UserHandle.USER_SYSTEM)); 19124 pw.println(")"); 19125 } else if (verifierPackageName != null) { 19126 pw.print("ifv,"); pw.print(verifierPackageName); 19127 pw.print(","); 19128 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19129 UserHandle.USER_SYSTEM)); 19130 } 19131 } else { 19132 pw.println(); 19133 pw.println("No Intent Filter Verifier available!"); 19134 } 19135 } 19136 19137 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 19138 boolean printedHeader = false; 19139 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 19140 while (it.hasNext()) { 19141 String name = it.next(); 19142 SharedLibraryEntry ent = mSharedLibraries.get(name); 19143 if (!checkin) { 19144 if (!printedHeader) { 19145 if (dumpState.onTitlePrinted()) 19146 pw.println(); 19147 pw.println("Libraries:"); 19148 printedHeader = true; 19149 } 19150 pw.print(" "); 19151 } else { 19152 pw.print("lib,"); 19153 } 19154 pw.print(name); 19155 if (!checkin) { 19156 pw.print(" -> "); 19157 } 19158 if (ent.path != null) { 19159 if (!checkin) { 19160 pw.print("(jar) "); 19161 pw.print(ent.path); 19162 } else { 19163 pw.print(",jar,"); 19164 pw.print(ent.path); 19165 } 19166 } else { 19167 if (!checkin) { 19168 pw.print("(apk) "); 19169 pw.print(ent.apk); 19170 } else { 19171 pw.print(",apk,"); 19172 pw.print(ent.apk); 19173 } 19174 } 19175 pw.println(); 19176 } 19177 } 19178 19179 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19180 if (dumpState.onTitlePrinted()) 19181 pw.println(); 19182 if (!checkin) { 19183 pw.println("Features:"); 19184 } 19185 19186 for (FeatureInfo feat : mAvailableFeatures.values()) { 19187 if (checkin) { 19188 pw.print("feat,"); 19189 pw.print(feat.name); 19190 pw.print(","); 19191 pw.println(feat.version); 19192 } else { 19193 pw.print(" "); 19194 pw.print(feat.name); 19195 if (feat.version > 0) { 19196 pw.print(" version="); 19197 pw.print(feat.version); 19198 } 19199 pw.println(); 19200 } 19201 } 19202 } 19203 19204 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19205 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19206 : "Activity Resolver Table:", " ", packageName, 19207 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19208 dumpState.setTitlePrinted(true); 19209 } 19210 } 19211 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19212 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19213 : "Receiver Resolver Table:", " ", packageName, 19214 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19215 dumpState.setTitlePrinted(true); 19216 } 19217 } 19218 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19219 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19220 : "Service Resolver Table:", " ", packageName, 19221 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19222 dumpState.setTitlePrinted(true); 19223 } 19224 } 19225 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19226 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19227 : "Provider Resolver Table:", " ", packageName, 19228 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19229 dumpState.setTitlePrinted(true); 19230 } 19231 } 19232 19233 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19234 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19235 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19236 int user = mSettings.mPreferredActivities.keyAt(i); 19237 if (pir.dump(pw, 19238 dumpState.getTitlePrinted() 19239 ? "\nPreferred Activities User " + user + ":" 19240 : "Preferred Activities User " + user + ":", " ", 19241 packageName, true, false)) { 19242 dumpState.setTitlePrinted(true); 19243 } 19244 } 19245 } 19246 19247 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19248 pw.flush(); 19249 FileOutputStream fout = new FileOutputStream(fd); 19250 BufferedOutputStream str = new BufferedOutputStream(fout); 19251 XmlSerializer serializer = new FastXmlSerializer(); 19252 try { 19253 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19254 serializer.startDocument(null, true); 19255 serializer.setFeature( 19256 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19257 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19258 serializer.endDocument(); 19259 serializer.flush(); 19260 } catch (IllegalArgumentException e) { 19261 pw.println("Failed writing: " + e); 19262 } catch (IllegalStateException e) { 19263 pw.println("Failed writing: " + e); 19264 } catch (IOException e) { 19265 pw.println("Failed writing: " + e); 19266 } 19267 } 19268 19269 if (!checkin 19270 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19271 && packageName == null) { 19272 pw.println(); 19273 int count = mSettings.mPackages.size(); 19274 if (count == 0) { 19275 pw.println("No applications!"); 19276 pw.println(); 19277 } else { 19278 final String prefix = " "; 19279 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19280 if (allPackageSettings.size() == 0) { 19281 pw.println("No domain preferred apps!"); 19282 pw.println(); 19283 } else { 19284 pw.println("App verification status:"); 19285 pw.println(); 19286 count = 0; 19287 for (PackageSetting ps : allPackageSettings) { 19288 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19289 if (ivi == null || ivi.getPackageName() == null) continue; 19290 pw.println(prefix + "Package: " + ivi.getPackageName()); 19291 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19292 pw.println(prefix + "Status: " + ivi.getStatusString()); 19293 pw.println(); 19294 count++; 19295 } 19296 if (count == 0) { 19297 pw.println(prefix + "No app verification established."); 19298 pw.println(); 19299 } 19300 for (int userId : sUserManager.getUserIds()) { 19301 pw.println("App linkages for user " + userId + ":"); 19302 pw.println(); 19303 count = 0; 19304 for (PackageSetting ps : allPackageSettings) { 19305 final long status = ps.getDomainVerificationStatusForUser(userId); 19306 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19307 continue; 19308 } 19309 pw.println(prefix + "Package: " + ps.name); 19310 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19311 String statusStr = IntentFilterVerificationInfo. 19312 getStatusStringFromValue(status); 19313 pw.println(prefix + "Status: " + statusStr); 19314 pw.println(); 19315 count++; 19316 } 19317 if (count == 0) { 19318 pw.println(prefix + "No configured app linkages."); 19319 pw.println(); 19320 } 19321 } 19322 } 19323 } 19324 } 19325 19326 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19327 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19328 if (packageName == null && permissionNames == null) { 19329 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19330 if (iperm == 0) { 19331 if (dumpState.onTitlePrinted()) 19332 pw.println(); 19333 pw.println("AppOp Permissions:"); 19334 } 19335 pw.print(" AppOp Permission "); 19336 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19337 pw.println(":"); 19338 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19339 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19340 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19341 } 19342 } 19343 } 19344 } 19345 19346 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19347 boolean printedSomething = false; 19348 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19349 if (packageName != null && !packageName.equals(p.info.packageName)) { 19350 continue; 19351 } 19352 if (!printedSomething) { 19353 if (dumpState.onTitlePrinted()) 19354 pw.println(); 19355 pw.println("Registered ContentProviders:"); 19356 printedSomething = true; 19357 } 19358 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19359 pw.print(" "); pw.println(p.toString()); 19360 } 19361 printedSomething = false; 19362 for (Map.Entry<String, PackageParser.Provider> entry : 19363 mProvidersByAuthority.entrySet()) { 19364 PackageParser.Provider p = entry.getValue(); 19365 if (packageName != null && !packageName.equals(p.info.packageName)) { 19366 continue; 19367 } 19368 if (!printedSomething) { 19369 if (dumpState.onTitlePrinted()) 19370 pw.println(); 19371 pw.println("ContentProvider Authorities:"); 19372 printedSomething = true; 19373 } 19374 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19375 pw.print(" "); pw.println(p.toString()); 19376 if (p.info != null && p.info.applicationInfo != null) { 19377 final String appInfo = p.info.applicationInfo.toString(); 19378 pw.print(" applicationInfo="); pw.println(appInfo); 19379 } 19380 } 19381 } 19382 19383 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19384 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19385 } 19386 19387 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19388 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19389 } 19390 19391 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19392 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19393 } 19394 19395 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19396 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19397 } 19398 19399 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19400 // XXX should handle packageName != null by dumping only install data that 19401 // the given package is involved with. 19402 if (dumpState.onTitlePrinted()) pw.println(); 19403 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19404 } 19405 19406 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19407 // XXX should handle packageName != null by dumping only install data that 19408 // the given package is involved with. 19409 if (dumpState.onTitlePrinted()) pw.println(); 19410 19411 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19412 ipw.println(); 19413 ipw.println("Frozen packages:"); 19414 ipw.increaseIndent(); 19415 if (mFrozenPackages.size() == 0) { 19416 ipw.println("(none)"); 19417 } else { 19418 for (int i = 0; i < mFrozenPackages.size(); i++) { 19419 ipw.println(mFrozenPackages.valueAt(i)); 19420 } 19421 } 19422 ipw.decreaseIndent(); 19423 } 19424 19425 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19426 if (dumpState.onTitlePrinted()) pw.println(); 19427 dumpDexoptStateLPr(pw, packageName); 19428 } 19429 19430 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19431 if (dumpState.onTitlePrinted()) pw.println(); 19432 dumpCompilerStatsLPr(pw, packageName); 19433 } 19434 19435 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19436 if (dumpState.onTitlePrinted()) pw.println(); 19437 mSettings.dumpReadMessagesLPr(pw, dumpState); 19438 19439 pw.println(); 19440 pw.println("Package warning messages:"); 19441 BufferedReader in = null; 19442 String line = null; 19443 try { 19444 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19445 while ((line = in.readLine()) != null) { 19446 if (line.contains("ignored: updated version")) continue; 19447 pw.println(line); 19448 } 19449 } catch (IOException ignored) { 19450 } finally { 19451 IoUtils.closeQuietly(in); 19452 } 19453 } 19454 19455 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19456 BufferedReader in = null; 19457 String line = null; 19458 try { 19459 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19460 while ((line = in.readLine()) != null) { 19461 if (line.contains("ignored: updated version")) continue; 19462 pw.print("msg,"); 19463 pw.println(line); 19464 } 19465 } catch (IOException ignored) { 19466 } finally { 19467 IoUtils.closeQuietly(in); 19468 } 19469 } 19470 } 19471 } 19472 19473 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19474 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19475 ipw.println(); 19476 ipw.println("Dexopt state:"); 19477 ipw.increaseIndent(); 19478 Collection<PackageParser.Package> packages = null; 19479 if (packageName != null) { 19480 PackageParser.Package targetPackage = mPackages.get(packageName); 19481 if (targetPackage != null) { 19482 packages = Collections.singletonList(targetPackage); 19483 } else { 19484 ipw.println("Unable to find package: " + packageName); 19485 return; 19486 } 19487 } else { 19488 packages = mPackages.values(); 19489 } 19490 19491 for (PackageParser.Package pkg : packages) { 19492 ipw.println("[" + pkg.packageName + "]"); 19493 ipw.increaseIndent(); 19494 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19495 ipw.decreaseIndent(); 19496 } 19497 } 19498 19499 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19500 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19501 ipw.println(); 19502 ipw.println("Compiler stats:"); 19503 ipw.increaseIndent(); 19504 Collection<PackageParser.Package> packages = null; 19505 if (packageName != null) { 19506 PackageParser.Package targetPackage = mPackages.get(packageName); 19507 if (targetPackage != null) { 19508 packages = Collections.singletonList(targetPackage); 19509 } else { 19510 ipw.println("Unable to find package: " + packageName); 19511 return; 19512 } 19513 } else { 19514 packages = mPackages.values(); 19515 } 19516 19517 for (PackageParser.Package pkg : packages) { 19518 ipw.println("[" + pkg.packageName + "]"); 19519 ipw.increaseIndent(); 19520 19521 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19522 if (stats == null) { 19523 ipw.println("(No recorded stats)"); 19524 } else { 19525 stats.dump(ipw); 19526 } 19527 ipw.decreaseIndent(); 19528 } 19529 } 19530 19531 private String dumpDomainString(String packageName) { 19532 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19533 .getList(); 19534 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19535 19536 ArraySet<String> result = new ArraySet<>(); 19537 if (iviList.size() > 0) { 19538 for (IntentFilterVerificationInfo ivi : iviList) { 19539 for (String host : ivi.getDomains()) { 19540 result.add(host); 19541 } 19542 } 19543 } 19544 if (filters != null && filters.size() > 0) { 19545 for (IntentFilter filter : filters) { 19546 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19547 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19548 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19549 result.addAll(filter.getHostsList()); 19550 } 19551 } 19552 } 19553 19554 StringBuilder sb = new StringBuilder(result.size() * 16); 19555 for (String domain : result) { 19556 if (sb.length() > 0) sb.append(" "); 19557 sb.append(domain); 19558 } 19559 return sb.toString(); 19560 } 19561 19562 // ------- apps on sdcard specific code ------- 19563 static final boolean DEBUG_SD_INSTALL = false; 19564 19565 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19566 19567 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19568 19569 private boolean mMediaMounted = false; 19570 19571 static String getEncryptKey() { 19572 try { 19573 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19574 SD_ENCRYPTION_KEYSTORE_NAME); 19575 if (sdEncKey == null) { 19576 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19577 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19578 if (sdEncKey == null) { 19579 Slog.e(TAG, "Failed to create encryption keys"); 19580 return null; 19581 } 19582 } 19583 return sdEncKey; 19584 } catch (NoSuchAlgorithmException nsae) { 19585 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19586 return null; 19587 } catch (IOException ioe) { 19588 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19589 return null; 19590 } 19591 } 19592 19593 /* 19594 * Update media status on PackageManager. 19595 */ 19596 @Override 19597 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19598 int callingUid = Binder.getCallingUid(); 19599 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19600 throw new SecurityException("Media status can only be updated by the system"); 19601 } 19602 // reader; this apparently protects mMediaMounted, but should probably 19603 // be a different lock in that case. 19604 synchronized (mPackages) { 19605 Log.i(TAG, "Updating external media status from " 19606 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19607 + (mediaStatus ? "mounted" : "unmounted")); 19608 if (DEBUG_SD_INSTALL) 19609 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19610 + ", mMediaMounted=" + mMediaMounted); 19611 if (mediaStatus == mMediaMounted) { 19612 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19613 : 0, -1); 19614 mHandler.sendMessage(msg); 19615 return; 19616 } 19617 mMediaMounted = mediaStatus; 19618 } 19619 // Queue up an async operation since the package installation may take a 19620 // little while. 19621 mHandler.post(new Runnable() { 19622 public void run() { 19623 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19624 } 19625 }); 19626 } 19627 19628 /** 19629 * Called by StorageManagerService when the initial ASECs to scan are available. 19630 * Should block until all the ASEC containers are finished being scanned. 19631 */ 19632 public void scanAvailableAsecs() { 19633 updateExternalMediaStatusInner(true, false, false); 19634 } 19635 19636 /* 19637 * Collect information of applications on external media, map them against 19638 * existing containers and update information based on current mount status. 19639 * Please note that we always have to report status if reportStatus has been 19640 * set to true especially when unloading packages. 19641 */ 19642 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19643 boolean externalStorage) { 19644 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19645 int[] uidArr = EmptyArray.INT; 19646 19647 final String[] list = PackageHelper.getSecureContainerList(); 19648 if (ArrayUtils.isEmpty(list)) { 19649 Log.i(TAG, "No secure containers found"); 19650 } else { 19651 // Process list of secure containers and categorize them 19652 // as active or stale based on their package internal state. 19653 19654 // reader 19655 synchronized (mPackages) { 19656 for (String cid : list) { 19657 // Leave stages untouched for now; installer service owns them 19658 if (PackageInstallerService.isStageName(cid)) continue; 19659 19660 if (DEBUG_SD_INSTALL) 19661 Log.i(TAG, "Processing container " + cid); 19662 String pkgName = getAsecPackageName(cid); 19663 if (pkgName == null) { 19664 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19665 continue; 19666 } 19667 if (DEBUG_SD_INSTALL) 19668 Log.i(TAG, "Looking for pkg : " + pkgName); 19669 19670 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19671 if (ps == null) { 19672 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19673 continue; 19674 } 19675 19676 /* 19677 * Skip packages that are not external if we're unmounting 19678 * external storage. 19679 */ 19680 if (externalStorage && !isMounted && !isExternal(ps)) { 19681 continue; 19682 } 19683 19684 final AsecInstallArgs args = new AsecInstallArgs(cid, 19685 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19686 // The package status is changed only if the code path 19687 // matches between settings and the container id. 19688 if (ps.codePathString != null 19689 && ps.codePathString.startsWith(args.getCodePath())) { 19690 if (DEBUG_SD_INSTALL) { 19691 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19692 + " at code path: " + ps.codePathString); 19693 } 19694 19695 // We do have a valid package installed on sdcard 19696 processCids.put(args, ps.codePathString); 19697 final int uid = ps.appId; 19698 if (uid != -1) { 19699 uidArr = ArrayUtils.appendInt(uidArr, uid); 19700 } 19701 } else { 19702 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19703 + ps.codePathString); 19704 } 19705 } 19706 } 19707 19708 Arrays.sort(uidArr); 19709 } 19710 19711 // Process packages with valid entries. 19712 if (isMounted) { 19713 if (DEBUG_SD_INSTALL) 19714 Log.i(TAG, "Loading packages"); 19715 loadMediaPackages(processCids, uidArr, externalStorage); 19716 startCleaningPackages(); 19717 mInstallerService.onSecureContainersAvailable(); 19718 } else { 19719 if (DEBUG_SD_INSTALL) 19720 Log.i(TAG, "Unloading packages"); 19721 unloadMediaPackages(processCids, uidArr, reportStatus); 19722 } 19723 } 19724 19725 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19726 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19727 final int size = infos.size(); 19728 final String[] packageNames = new String[size]; 19729 final int[] packageUids = new int[size]; 19730 for (int i = 0; i < size; i++) { 19731 final ApplicationInfo info = infos.get(i); 19732 packageNames[i] = info.packageName; 19733 packageUids[i] = info.uid; 19734 } 19735 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19736 finishedReceiver); 19737 } 19738 19739 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19740 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19741 sendResourcesChangedBroadcast(mediaStatus, replacing, 19742 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19743 } 19744 19745 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19746 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19747 int size = pkgList.length; 19748 if (size > 0) { 19749 // Send broadcasts here 19750 Bundle extras = new Bundle(); 19751 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19752 if (uidArr != null) { 19753 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19754 } 19755 if (replacing) { 19756 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19757 } 19758 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19759 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19760 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19761 } 19762 } 19763 19764 /* 19765 * Look at potentially valid container ids from processCids If package 19766 * information doesn't match the one on record or package scanning fails, 19767 * the cid is added to list of removeCids. We currently don't delete stale 19768 * containers. 19769 */ 19770 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19771 boolean externalStorage) { 19772 ArrayList<String> pkgList = new ArrayList<String>(); 19773 Set<AsecInstallArgs> keys = processCids.keySet(); 19774 19775 for (AsecInstallArgs args : keys) { 19776 String codePath = processCids.get(args); 19777 if (DEBUG_SD_INSTALL) 19778 Log.i(TAG, "Loading container : " + args.cid); 19779 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19780 try { 19781 // Make sure there are no container errors first. 19782 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19783 Slog.e(TAG, "Failed to mount cid : " + args.cid 19784 + " when installing from sdcard"); 19785 continue; 19786 } 19787 // Check code path here. 19788 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19789 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19790 + " does not match one in settings " + codePath); 19791 continue; 19792 } 19793 // Parse package 19794 int parseFlags = mDefParseFlags; 19795 if (args.isExternalAsec()) { 19796 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19797 } 19798 if (args.isFwdLocked()) { 19799 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19800 } 19801 19802 synchronized (mInstallLock) { 19803 PackageParser.Package pkg = null; 19804 try { 19805 // Sadly we don't know the package name yet to freeze it 19806 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19807 SCAN_IGNORE_FROZEN, 0, null); 19808 } catch (PackageManagerException e) { 19809 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19810 } 19811 // Scan the package 19812 if (pkg != null) { 19813 /* 19814 * TODO why is the lock being held? doPostInstall is 19815 * called in other places without the lock. This needs 19816 * to be straightened out. 19817 */ 19818 // writer 19819 synchronized (mPackages) { 19820 retCode = PackageManager.INSTALL_SUCCEEDED; 19821 pkgList.add(pkg.packageName); 19822 // Post process args 19823 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19824 pkg.applicationInfo.uid); 19825 } 19826 } else { 19827 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19828 } 19829 } 19830 19831 } finally { 19832 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19833 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19834 } 19835 } 19836 } 19837 // writer 19838 synchronized (mPackages) { 19839 // If the platform SDK has changed since the last time we booted, 19840 // we need to re-grant app permission to catch any new ones that 19841 // appear. This is really a hack, and means that apps can in some 19842 // cases get permissions that the user didn't initially explicitly 19843 // allow... it would be nice to have some better way to handle 19844 // this situation. 19845 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19846 : mSettings.getInternalVersion(); 19847 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19848 : StorageManager.UUID_PRIVATE_INTERNAL; 19849 19850 int updateFlags = UPDATE_PERMISSIONS_ALL; 19851 if (ver.sdkVersion != mSdkVersion) { 19852 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19853 + mSdkVersion + "; regranting permissions for external"); 19854 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19855 } 19856 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19857 19858 // Yay, everything is now upgraded 19859 ver.forceCurrent(); 19860 19861 // can downgrade to reader 19862 // Persist settings 19863 mSettings.writeLPr(); 19864 } 19865 // Send a broadcast to let everyone know we are done processing 19866 if (pkgList.size() > 0) { 19867 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19868 } 19869 } 19870 19871 /* 19872 * Utility method to unload a list of specified containers 19873 */ 19874 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19875 // Just unmount all valid containers. 19876 for (AsecInstallArgs arg : cidArgs) { 19877 synchronized (mInstallLock) { 19878 arg.doPostDeleteLI(false); 19879 } 19880 } 19881 } 19882 19883 /* 19884 * Unload packages mounted on external media. This involves deleting package 19885 * data from internal structures, sending broadcasts about disabled packages, 19886 * gc'ing to free up references, unmounting all secure containers 19887 * corresponding to packages on external media, and posting a 19888 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19889 * that we always have to post this message if status has been requested no 19890 * matter what. 19891 */ 19892 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19893 final boolean reportStatus) { 19894 if (DEBUG_SD_INSTALL) 19895 Log.i(TAG, "unloading media packages"); 19896 ArrayList<String> pkgList = new ArrayList<String>(); 19897 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19898 final Set<AsecInstallArgs> keys = processCids.keySet(); 19899 for (AsecInstallArgs args : keys) { 19900 String pkgName = args.getPackageName(); 19901 if (DEBUG_SD_INSTALL) 19902 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19903 // Delete package internally 19904 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19905 synchronized (mInstallLock) { 19906 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19907 final boolean res; 19908 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19909 "unloadMediaPackages")) { 19910 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19911 null); 19912 } 19913 if (res) { 19914 pkgList.add(pkgName); 19915 } else { 19916 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19917 failedList.add(args); 19918 } 19919 } 19920 } 19921 19922 // reader 19923 synchronized (mPackages) { 19924 // We didn't update the settings after removing each package; 19925 // write them now for all packages. 19926 mSettings.writeLPr(); 19927 } 19928 19929 // We have to absolutely send UPDATED_MEDIA_STATUS only 19930 // after confirming that all the receivers processed the ordered 19931 // broadcast when packages get disabled, force a gc to clean things up. 19932 // and unload all the containers. 19933 if (pkgList.size() > 0) { 19934 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19935 new IIntentReceiver.Stub() { 19936 public void performReceive(Intent intent, int resultCode, String data, 19937 Bundle extras, boolean ordered, boolean sticky, 19938 int sendingUser) throws RemoteException { 19939 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19940 reportStatus ? 1 : 0, 1, keys); 19941 mHandler.sendMessage(msg); 19942 } 19943 }); 19944 } else { 19945 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19946 keys); 19947 mHandler.sendMessage(msg); 19948 } 19949 } 19950 19951 private void loadPrivatePackages(final VolumeInfo vol) { 19952 mHandler.post(new Runnable() { 19953 @Override 19954 public void run() { 19955 loadPrivatePackagesInner(vol); 19956 } 19957 }); 19958 } 19959 19960 private void loadPrivatePackagesInner(VolumeInfo vol) { 19961 final String volumeUuid = vol.fsUuid; 19962 if (TextUtils.isEmpty(volumeUuid)) { 19963 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19964 return; 19965 } 19966 19967 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19968 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19969 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19970 19971 final VersionInfo ver; 19972 final List<PackageSetting> packages; 19973 synchronized (mPackages) { 19974 ver = mSettings.findOrCreateVersion(volumeUuid); 19975 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19976 } 19977 19978 for (PackageSetting ps : packages) { 19979 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19980 synchronized (mInstallLock) { 19981 final PackageParser.Package pkg; 19982 try { 19983 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19984 loaded.add(pkg.applicationInfo); 19985 19986 } catch (PackageManagerException e) { 19987 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19988 } 19989 19990 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19991 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19992 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19993 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19994 } 19995 } 19996 } 19997 19998 // Reconcile app data for all started/unlocked users 19999 final StorageManager sm = mContext.getSystemService(StorageManager.class); 20000 final UserManager um = mContext.getSystemService(UserManager.class); 20001 UserManagerInternal umInternal = getUserManagerInternal(); 20002 for (UserInfo user : um.getUsers()) { 20003 final int flags; 20004 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20005 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20006 } else if (umInternal.isUserRunning(user.id)) { 20007 flags = StorageManager.FLAG_STORAGE_DE; 20008 } else { 20009 continue; 20010 } 20011 20012 try { 20013 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 20014 synchronized (mInstallLock) { 20015 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 20016 } 20017 } catch (IllegalStateException e) { 20018 // Device was probably ejected, and we'll process that event momentarily 20019 Slog.w(TAG, "Failed to prepare storage: " + e); 20020 } 20021 } 20022 20023 synchronized (mPackages) { 20024 int updateFlags = UPDATE_PERMISSIONS_ALL; 20025 if (ver.sdkVersion != mSdkVersion) { 20026 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20027 + mSdkVersion + "; regranting permissions for " + volumeUuid); 20028 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20029 } 20030 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20031 20032 // Yay, everything is now upgraded 20033 ver.forceCurrent(); 20034 20035 mSettings.writeLPr(); 20036 } 20037 20038 for (PackageFreezer freezer : freezers) { 20039 freezer.close(); 20040 } 20041 20042 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 20043 sendResourcesChangedBroadcast(true, false, loaded, null); 20044 } 20045 20046 private void unloadPrivatePackages(final VolumeInfo vol) { 20047 mHandler.post(new Runnable() { 20048 @Override 20049 public void run() { 20050 unloadPrivatePackagesInner(vol); 20051 } 20052 }); 20053 } 20054 20055 private void unloadPrivatePackagesInner(VolumeInfo vol) { 20056 final String volumeUuid = vol.fsUuid; 20057 if (TextUtils.isEmpty(volumeUuid)) { 20058 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 20059 return; 20060 } 20061 20062 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 20063 synchronized (mInstallLock) { 20064 synchronized (mPackages) { 20065 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 20066 for (PackageSetting ps : packages) { 20067 if (ps.pkg == null) continue; 20068 20069 final ApplicationInfo info = ps.pkg.applicationInfo; 20070 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20071 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20072 20073 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 20074 "unloadPrivatePackagesInner")) { 20075 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 20076 false, null)) { 20077 unloaded.add(info); 20078 } else { 20079 Slog.w(TAG, "Failed to unload " + ps.codePath); 20080 } 20081 } 20082 20083 // Try very hard to release any references to this package 20084 // so we don't risk the system server being killed due to 20085 // open FDs 20086 AttributeCache.instance().removePackage(ps.name); 20087 } 20088 20089 mSettings.writeLPr(); 20090 } 20091 } 20092 20093 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 20094 sendResourcesChangedBroadcast(false, false, unloaded, null); 20095 20096 // Try very hard to release any references to this path so we don't risk 20097 // the system server being killed due to open FDs 20098 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 20099 20100 for (int i = 0; i < 3; i++) { 20101 System.gc(); 20102 System.runFinalization(); 20103 } 20104 } 20105 20106 /** 20107 * Prepare storage areas for given user on all mounted devices. 20108 */ 20109 void prepareUserData(int userId, int userSerial, int flags) { 20110 synchronized (mInstallLock) { 20111 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20112 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20113 final String volumeUuid = vol.getFsUuid(); 20114 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 20115 } 20116 } 20117 } 20118 20119 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 20120 boolean allowRecover) { 20121 // Prepare storage and verify that serial numbers are consistent; if 20122 // there's a mismatch we need to destroy to avoid leaking data 20123 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20124 try { 20125 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 20126 20127 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 20128 UserManagerService.enforceSerialNumber( 20129 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 20130 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20131 UserManagerService.enforceSerialNumber( 20132 Environment.getDataSystemDeDirectory(userId), userSerial); 20133 } 20134 } 20135 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 20136 UserManagerService.enforceSerialNumber( 20137 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 20138 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20139 UserManagerService.enforceSerialNumber( 20140 Environment.getDataSystemCeDirectory(userId), userSerial); 20141 } 20142 } 20143 20144 synchronized (mInstallLock) { 20145 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20146 } 20147 } catch (Exception e) { 20148 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20149 + " because we failed to prepare: " + e); 20150 destroyUserDataLI(volumeUuid, userId, 20151 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20152 20153 if (allowRecover) { 20154 // Try one last time; if we fail again we're really in trouble 20155 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20156 } 20157 } 20158 } 20159 20160 /** 20161 * Destroy storage areas for given user on all mounted devices. 20162 */ 20163 void destroyUserData(int userId, int flags) { 20164 synchronized (mInstallLock) { 20165 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20166 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20167 final String volumeUuid = vol.getFsUuid(); 20168 destroyUserDataLI(volumeUuid, userId, flags); 20169 } 20170 } 20171 } 20172 20173 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20174 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20175 try { 20176 // Clean up app data, profile data, and media data 20177 mInstaller.destroyUserData(volumeUuid, userId, flags); 20178 20179 // Clean up system data 20180 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20181 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20182 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20183 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20184 } 20185 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20186 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20187 } 20188 } 20189 20190 // Data with special labels is now gone, so finish the job 20191 storage.destroyUserStorage(volumeUuid, userId, flags); 20192 20193 } catch (Exception e) { 20194 logCriticalInfo(Log.WARN, 20195 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20196 } 20197 } 20198 20199 /** 20200 * Examine all users present on given mounted volume, and destroy data 20201 * belonging to users that are no longer valid, or whose user ID has been 20202 * recycled. 20203 */ 20204 private void reconcileUsers(String volumeUuid) { 20205 final List<File> files = new ArrayList<>(); 20206 Collections.addAll(files, FileUtils 20207 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20208 Collections.addAll(files, FileUtils 20209 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20210 Collections.addAll(files, FileUtils 20211 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20212 Collections.addAll(files, FileUtils 20213 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20214 for (File file : files) { 20215 if (!file.isDirectory()) continue; 20216 20217 final int userId; 20218 final UserInfo info; 20219 try { 20220 userId = Integer.parseInt(file.getName()); 20221 info = sUserManager.getUserInfo(userId); 20222 } catch (NumberFormatException e) { 20223 Slog.w(TAG, "Invalid user directory " + file); 20224 continue; 20225 } 20226 20227 boolean destroyUser = false; 20228 if (info == null) { 20229 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20230 + " because no matching user was found"); 20231 destroyUser = true; 20232 } else if (!mOnlyCore) { 20233 try { 20234 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20235 } catch (IOException e) { 20236 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20237 + " because we failed to enforce serial number: " + e); 20238 destroyUser = true; 20239 } 20240 } 20241 20242 if (destroyUser) { 20243 synchronized (mInstallLock) { 20244 destroyUserDataLI(volumeUuid, userId, 20245 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20246 } 20247 } 20248 } 20249 } 20250 20251 private void assertPackageKnown(String volumeUuid, String packageName) 20252 throws PackageManagerException { 20253 synchronized (mPackages) { 20254 // Normalize package name to handle renamed packages 20255 packageName = normalizePackageNameLPr(packageName); 20256 20257 final PackageSetting ps = mSettings.mPackages.get(packageName); 20258 if (ps == null) { 20259 throw new PackageManagerException("Package " + packageName + " is unknown"); 20260 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20261 throw new PackageManagerException( 20262 "Package " + packageName + " found on unknown volume " + volumeUuid 20263 + "; expected volume " + ps.volumeUuid); 20264 } 20265 } 20266 } 20267 20268 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20269 throws PackageManagerException { 20270 synchronized (mPackages) { 20271 // Normalize package name to handle renamed packages 20272 packageName = normalizePackageNameLPr(packageName); 20273 20274 final PackageSetting ps = mSettings.mPackages.get(packageName); 20275 if (ps == null) { 20276 throw new PackageManagerException("Package " + packageName + " is unknown"); 20277 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20278 throw new PackageManagerException( 20279 "Package " + packageName + " found on unknown volume " + volumeUuid 20280 + "; expected volume " + ps.volumeUuid); 20281 } else if (!ps.getInstalled(userId)) { 20282 throw new PackageManagerException( 20283 "Package " + packageName + " not installed for user " + userId); 20284 } 20285 } 20286 } 20287 20288 /** 20289 * Examine all apps present on given mounted volume, and destroy apps that 20290 * aren't expected, either due to uninstallation or reinstallation on 20291 * another volume. 20292 */ 20293 private void reconcileApps(String volumeUuid) { 20294 final File[] files = FileUtils 20295 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20296 for (File file : files) { 20297 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20298 && !PackageInstallerService.isStageName(file.getName()); 20299 if (!isPackage) { 20300 // Ignore entries which are not packages 20301 continue; 20302 } 20303 20304 try { 20305 final PackageLite pkg = PackageParser.parsePackageLite(file, 20306 PackageParser.PARSE_MUST_BE_APK); 20307 assertPackageKnown(volumeUuid, pkg.packageName); 20308 20309 } catch (PackageParserException | PackageManagerException e) { 20310 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20311 synchronized (mInstallLock) { 20312 removeCodePathLI(file); 20313 } 20314 } 20315 } 20316 } 20317 20318 /** 20319 * Reconcile all app data for the given user. 20320 * <p> 20321 * Verifies that directories exist and that ownership and labeling is 20322 * correct for all installed apps on all mounted volumes. 20323 */ 20324 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20325 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20326 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20327 final String volumeUuid = vol.getFsUuid(); 20328 synchronized (mInstallLock) { 20329 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20330 } 20331 } 20332 } 20333 20334 /** 20335 * Reconcile all app data on given mounted volume. 20336 * <p> 20337 * Destroys app data that isn't expected, either due to uninstallation or 20338 * reinstallation on another volume. 20339 * <p> 20340 * Verifies that directories exist and that ownership and labeling is 20341 * correct for all installed apps. 20342 */ 20343 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20344 boolean migrateAppData) { 20345 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20346 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20347 20348 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20349 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20350 20351 // First look for stale data that doesn't belong, and check if things 20352 // have changed since we did our last restorecon 20353 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20354 if (StorageManager.isFileEncryptedNativeOrEmulated() 20355 && !StorageManager.isUserKeyUnlocked(userId)) { 20356 throw new RuntimeException( 20357 "Yikes, someone asked us to reconcile CE storage while " + userId 20358 + " was still locked; this would have caused massive data loss!"); 20359 } 20360 20361 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20362 for (File file : files) { 20363 final String packageName = file.getName(); 20364 try { 20365 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20366 } catch (PackageManagerException e) { 20367 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20368 try { 20369 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20370 StorageManager.FLAG_STORAGE_CE, 0); 20371 } catch (InstallerException e2) { 20372 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20373 } 20374 } 20375 } 20376 } 20377 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20378 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20379 for (File file : files) { 20380 final String packageName = file.getName(); 20381 try { 20382 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20383 } catch (PackageManagerException e) { 20384 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20385 try { 20386 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20387 StorageManager.FLAG_STORAGE_DE, 0); 20388 } catch (InstallerException e2) { 20389 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20390 } 20391 } 20392 } 20393 } 20394 20395 // Ensure that data directories are ready to roll for all packages 20396 // installed for this volume and user 20397 final List<PackageSetting> packages; 20398 synchronized (mPackages) { 20399 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20400 } 20401 int preparedCount = 0; 20402 for (PackageSetting ps : packages) { 20403 final String packageName = ps.name; 20404 if (ps.pkg == null) { 20405 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20406 // TODO: might be due to legacy ASEC apps; we should circle back 20407 // and reconcile again once they're scanned 20408 continue; 20409 } 20410 20411 if (ps.getInstalled(userId)) { 20412 prepareAppDataLIF(ps.pkg, userId, flags); 20413 20414 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20415 // We may have just shuffled around app data directories, so 20416 // prepare them one more time 20417 prepareAppDataLIF(ps.pkg, userId, flags); 20418 } 20419 20420 preparedCount++; 20421 } 20422 } 20423 20424 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20425 } 20426 20427 /** 20428 * Prepare app data for the given app just after it was installed or 20429 * upgraded. This method carefully only touches users that it's installed 20430 * for, and it forces a restorecon to handle any seinfo changes. 20431 * <p> 20432 * Verifies that directories exist and that ownership and labeling is 20433 * correct for all installed apps. If there is an ownership mismatch, it 20434 * will try recovering system apps by wiping data; third-party app data is 20435 * left intact. 20436 * <p> 20437 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20438 */ 20439 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20440 final PackageSetting ps; 20441 synchronized (mPackages) { 20442 ps = mSettings.mPackages.get(pkg.packageName); 20443 mSettings.writeKernelMappingLPr(ps); 20444 } 20445 20446 final UserManager um = mContext.getSystemService(UserManager.class); 20447 UserManagerInternal umInternal = getUserManagerInternal(); 20448 for (UserInfo user : um.getUsers()) { 20449 final int flags; 20450 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20451 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20452 } else if (umInternal.isUserRunning(user.id)) { 20453 flags = StorageManager.FLAG_STORAGE_DE; 20454 } else { 20455 continue; 20456 } 20457 20458 if (ps.getInstalled(user.id)) { 20459 // TODO: when user data is locked, mark that we're still dirty 20460 prepareAppDataLIF(pkg, user.id, flags); 20461 } 20462 } 20463 } 20464 20465 /** 20466 * Prepare app data for the given app. 20467 * <p> 20468 * Verifies that directories exist and that ownership and labeling is 20469 * correct for all installed apps. If there is an ownership mismatch, this 20470 * will try recovering system apps by wiping data; third-party app data is 20471 * left intact. 20472 */ 20473 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20474 if (pkg == null) { 20475 Slog.wtf(TAG, "Package was null!", new Throwable()); 20476 return; 20477 } 20478 prepareAppDataLeafLIF(pkg, userId, flags); 20479 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20480 for (int i = 0; i < childCount; i++) { 20481 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20482 } 20483 } 20484 20485 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20486 if (DEBUG_APP_DATA) { 20487 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20488 + Integer.toHexString(flags)); 20489 } 20490 20491 final String volumeUuid = pkg.volumeUuid; 20492 final String packageName = pkg.packageName; 20493 final ApplicationInfo app = pkg.applicationInfo; 20494 final int appId = UserHandle.getAppId(app.uid); 20495 20496 Preconditions.checkNotNull(app.seinfo); 20497 20498 long ceDataInode = -1; 20499 try { 20500 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20501 appId, app.seinfo, app.targetSdkVersion); 20502 } catch (InstallerException e) { 20503 if (app.isSystemApp()) { 20504 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20505 + ", but trying to recover: " + e); 20506 destroyAppDataLeafLIF(pkg, userId, flags); 20507 try { 20508 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20509 appId, app.seinfo, app.targetSdkVersion); 20510 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20511 } catch (InstallerException e2) { 20512 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20513 } 20514 } else { 20515 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20516 } 20517 } 20518 20519 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20520 // TODO: mark this structure as dirty so we persist it! 20521 synchronized (mPackages) { 20522 final PackageSetting ps = mSettings.mPackages.get(packageName); 20523 if (ps != null) { 20524 ps.setCeDataInode(ceDataInode, userId); 20525 } 20526 } 20527 } 20528 20529 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20530 } 20531 20532 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20533 if (pkg == null) { 20534 Slog.wtf(TAG, "Package was null!", new Throwable()); 20535 return; 20536 } 20537 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20538 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20539 for (int i = 0; i < childCount; i++) { 20540 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20541 } 20542 } 20543 20544 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20545 final String volumeUuid = pkg.volumeUuid; 20546 final String packageName = pkg.packageName; 20547 final ApplicationInfo app = pkg.applicationInfo; 20548 20549 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20550 // Create a native library symlink only if we have native libraries 20551 // and if the native libraries are 32 bit libraries. We do not provide 20552 // this symlink for 64 bit libraries. 20553 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20554 final String nativeLibPath = app.nativeLibraryDir; 20555 try { 20556 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20557 nativeLibPath, userId); 20558 } catch (InstallerException e) { 20559 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20560 } 20561 } 20562 } 20563 } 20564 20565 /** 20566 * For system apps on non-FBE devices, this method migrates any existing 20567 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20568 * requested by the app. 20569 */ 20570 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20571 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20572 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20573 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20574 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20575 try { 20576 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20577 storageTarget); 20578 } catch (InstallerException e) { 20579 logCriticalInfo(Log.WARN, 20580 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20581 } 20582 return true; 20583 } else { 20584 return false; 20585 } 20586 } 20587 20588 public PackageFreezer freezePackage(String packageName, String killReason) { 20589 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20590 } 20591 20592 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20593 return new PackageFreezer(packageName, userId, killReason); 20594 } 20595 20596 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20597 String killReason) { 20598 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20599 } 20600 20601 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20602 String killReason) { 20603 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20604 return new PackageFreezer(); 20605 } else { 20606 return freezePackage(packageName, userId, killReason); 20607 } 20608 } 20609 20610 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20611 String killReason) { 20612 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20613 } 20614 20615 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20616 String killReason) { 20617 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20618 return new PackageFreezer(); 20619 } else { 20620 return freezePackage(packageName, userId, killReason); 20621 } 20622 } 20623 20624 /** 20625 * Class that freezes and kills the given package upon creation, and 20626 * unfreezes it upon closing. This is typically used when doing surgery on 20627 * app code/data to prevent the app from running while you're working. 20628 */ 20629 private class PackageFreezer implements AutoCloseable { 20630 private final String mPackageName; 20631 private final PackageFreezer[] mChildren; 20632 20633 private final boolean mWeFroze; 20634 20635 private final AtomicBoolean mClosed = new AtomicBoolean(); 20636 private final CloseGuard mCloseGuard = CloseGuard.get(); 20637 20638 /** 20639 * Create and return a stub freezer that doesn't actually do anything, 20640 * typically used when someone requested 20641 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20642 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20643 */ 20644 public PackageFreezer() { 20645 mPackageName = null; 20646 mChildren = null; 20647 mWeFroze = false; 20648 mCloseGuard.open("close"); 20649 } 20650 20651 public PackageFreezer(String packageName, int userId, String killReason) { 20652 synchronized (mPackages) { 20653 mPackageName = packageName; 20654 mWeFroze = mFrozenPackages.add(mPackageName); 20655 20656 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20657 if (ps != null) { 20658 killApplication(ps.name, ps.appId, userId, killReason); 20659 } 20660 20661 final PackageParser.Package p = mPackages.get(packageName); 20662 if (p != null && p.childPackages != null) { 20663 final int N = p.childPackages.size(); 20664 mChildren = new PackageFreezer[N]; 20665 for (int i = 0; i < N; i++) { 20666 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20667 userId, killReason); 20668 } 20669 } else { 20670 mChildren = null; 20671 } 20672 } 20673 mCloseGuard.open("close"); 20674 } 20675 20676 @Override 20677 protected void finalize() throws Throwable { 20678 try { 20679 mCloseGuard.warnIfOpen(); 20680 close(); 20681 } finally { 20682 super.finalize(); 20683 } 20684 } 20685 20686 @Override 20687 public void close() { 20688 mCloseGuard.close(); 20689 if (mClosed.compareAndSet(false, true)) { 20690 synchronized (mPackages) { 20691 if (mWeFroze) { 20692 mFrozenPackages.remove(mPackageName); 20693 } 20694 20695 if (mChildren != null) { 20696 for (PackageFreezer freezer : mChildren) { 20697 freezer.close(); 20698 } 20699 } 20700 } 20701 } 20702 } 20703 } 20704 20705 /** 20706 * Verify that given package is currently frozen. 20707 */ 20708 private void checkPackageFrozen(String packageName) { 20709 synchronized (mPackages) { 20710 if (!mFrozenPackages.contains(packageName)) { 20711 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20712 } 20713 } 20714 } 20715 20716 @Override 20717 public int movePackage(final String packageName, final String volumeUuid) { 20718 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20719 20720 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20721 final int moveId = mNextMoveId.getAndIncrement(); 20722 mHandler.post(new Runnable() { 20723 @Override 20724 public void run() { 20725 try { 20726 movePackageInternal(packageName, volumeUuid, moveId, user); 20727 } catch (PackageManagerException e) { 20728 Slog.w(TAG, "Failed to move " + packageName, e); 20729 mMoveCallbacks.notifyStatusChanged(moveId, 20730 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20731 } 20732 } 20733 }); 20734 return moveId; 20735 } 20736 20737 private void movePackageInternal(final String packageName, final String volumeUuid, 20738 final int moveId, UserHandle user) throws PackageManagerException { 20739 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20740 final PackageManager pm = mContext.getPackageManager(); 20741 20742 final boolean currentAsec; 20743 final String currentVolumeUuid; 20744 final File codeFile; 20745 final String installerPackageName; 20746 final String packageAbiOverride; 20747 final int appId; 20748 final String seinfo; 20749 final String label; 20750 final int targetSdkVersion; 20751 final PackageFreezer freezer; 20752 final int[] installedUserIds; 20753 20754 // reader 20755 synchronized (mPackages) { 20756 final PackageParser.Package pkg = mPackages.get(packageName); 20757 final PackageSetting ps = mSettings.mPackages.get(packageName); 20758 if (pkg == null || ps == null) { 20759 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20760 } 20761 20762 if (pkg.applicationInfo.isSystemApp()) { 20763 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20764 "Cannot move system application"); 20765 } 20766 20767 if (pkg.applicationInfo.isExternalAsec()) { 20768 currentAsec = true; 20769 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20770 } else if (pkg.applicationInfo.isForwardLocked()) { 20771 currentAsec = true; 20772 currentVolumeUuid = "forward_locked"; 20773 } else { 20774 currentAsec = false; 20775 currentVolumeUuid = ps.volumeUuid; 20776 20777 final File probe = new File(pkg.codePath); 20778 final File probeOat = new File(probe, "oat"); 20779 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20780 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20781 "Move only supported for modern cluster style installs"); 20782 } 20783 } 20784 20785 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20786 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20787 "Package already moved to " + volumeUuid); 20788 } 20789 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20790 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20791 "Device admin cannot be moved"); 20792 } 20793 20794 if (mFrozenPackages.contains(packageName)) { 20795 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20796 "Failed to move already frozen package"); 20797 } 20798 20799 codeFile = new File(pkg.codePath); 20800 installerPackageName = ps.installerPackageName; 20801 packageAbiOverride = ps.cpuAbiOverrideString; 20802 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20803 seinfo = pkg.applicationInfo.seinfo; 20804 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20805 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20806 freezer = freezePackage(packageName, "movePackageInternal"); 20807 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20808 } 20809 20810 final Bundle extras = new Bundle(); 20811 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20812 extras.putString(Intent.EXTRA_TITLE, label); 20813 mMoveCallbacks.notifyCreated(moveId, extras); 20814 20815 int installFlags; 20816 final boolean moveCompleteApp; 20817 final File measurePath; 20818 20819 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20820 installFlags = INSTALL_INTERNAL; 20821 moveCompleteApp = !currentAsec; 20822 measurePath = Environment.getDataAppDirectory(volumeUuid); 20823 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20824 installFlags = INSTALL_EXTERNAL; 20825 moveCompleteApp = false; 20826 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20827 } else { 20828 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20829 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20830 || !volume.isMountedWritable()) { 20831 freezer.close(); 20832 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20833 "Move location not mounted private volume"); 20834 } 20835 20836 Preconditions.checkState(!currentAsec); 20837 20838 installFlags = INSTALL_INTERNAL; 20839 moveCompleteApp = true; 20840 measurePath = Environment.getDataAppDirectory(volumeUuid); 20841 } 20842 20843 final PackageStats stats = new PackageStats(null, -1); 20844 synchronized (mInstaller) { 20845 for (int userId : installedUserIds) { 20846 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20847 freezer.close(); 20848 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20849 "Failed to measure package size"); 20850 } 20851 } 20852 } 20853 20854 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20855 + stats.dataSize); 20856 20857 final long startFreeBytes = measurePath.getFreeSpace(); 20858 final long sizeBytes; 20859 if (moveCompleteApp) { 20860 sizeBytes = stats.codeSize + stats.dataSize; 20861 } else { 20862 sizeBytes = stats.codeSize; 20863 } 20864 20865 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20866 freezer.close(); 20867 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20868 "Not enough free space to move"); 20869 } 20870 20871 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20872 20873 final CountDownLatch installedLatch = new CountDownLatch(1); 20874 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20875 @Override 20876 public void onUserActionRequired(Intent intent) throws RemoteException { 20877 throw new IllegalStateException(); 20878 } 20879 20880 @Override 20881 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20882 Bundle extras) throws RemoteException { 20883 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20884 + PackageManager.installStatusToString(returnCode, msg)); 20885 20886 installedLatch.countDown(); 20887 freezer.close(); 20888 20889 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20890 switch (status) { 20891 case PackageInstaller.STATUS_SUCCESS: 20892 mMoveCallbacks.notifyStatusChanged(moveId, 20893 PackageManager.MOVE_SUCCEEDED); 20894 break; 20895 case PackageInstaller.STATUS_FAILURE_STORAGE: 20896 mMoveCallbacks.notifyStatusChanged(moveId, 20897 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20898 break; 20899 default: 20900 mMoveCallbacks.notifyStatusChanged(moveId, 20901 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20902 break; 20903 } 20904 } 20905 }; 20906 20907 final MoveInfo move; 20908 if (moveCompleteApp) { 20909 // Kick off a thread to report progress estimates 20910 new Thread() { 20911 @Override 20912 public void run() { 20913 while (true) { 20914 try { 20915 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20916 break; 20917 } 20918 } catch (InterruptedException ignored) { 20919 } 20920 20921 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20922 final int progress = 10 + (int) MathUtils.constrain( 20923 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20924 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20925 } 20926 } 20927 }.start(); 20928 20929 final String dataAppName = codeFile.getName(); 20930 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20931 dataAppName, appId, seinfo, targetSdkVersion); 20932 } else { 20933 move = null; 20934 } 20935 20936 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20937 20938 final Message msg = mHandler.obtainMessage(INIT_COPY); 20939 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20940 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20941 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20942 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20943 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20944 msg.obj = params; 20945 20946 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20947 System.identityHashCode(msg.obj)); 20948 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20949 System.identityHashCode(msg.obj)); 20950 20951 mHandler.sendMessage(msg); 20952 } 20953 20954 @Override 20955 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20956 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20957 20958 final int realMoveId = mNextMoveId.getAndIncrement(); 20959 final Bundle extras = new Bundle(); 20960 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20961 mMoveCallbacks.notifyCreated(realMoveId, extras); 20962 20963 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20964 @Override 20965 public void onCreated(int moveId, Bundle extras) { 20966 // Ignored 20967 } 20968 20969 @Override 20970 public void onStatusChanged(int moveId, int status, long estMillis) { 20971 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20972 } 20973 }; 20974 20975 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20976 storage.setPrimaryStorageUuid(volumeUuid, callback); 20977 return realMoveId; 20978 } 20979 20980 @Override 20981 public int getMoveStatus(int moveId) { 20982 mContext.enforceCallingOrSelfPermission( 20983 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20984 return mMoveCallbacks.mLastStatus.get(moveId); 20985 } 20986 20987 @Override 20988 public void registerMoveCallback(IPackageMoveObserver callback) { 20989 mContext.enforceCallingOrSelfPermission( 20990 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20991 mMoveCallbacks.register(callback); 20992 } 20993 20994 @Override 20995 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20996 mContext.enforceCallingOrSelfPermission( 20997 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20998 mMoveCallbacks.unregister(callback); 20999 } 21000 21001 @Override 21002 public boolean setInstallLocation(int loc) { 21003 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 21004 null); 21005 if (getInstallLocation() == loc) { 21006 return true; 21007 } 21008 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 21009 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 21010 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 21011 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 21012 return true; 21013 } 21014 return false; 21015 } 21016 21017 @Override 21018 public int getInstallLocation() { 21019 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 21020 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 21021 PackageHelper.APP_INSTALL_AUTO); 21022 } 21023 21024 /** Called by UserManagerService */ 21025 void cleanUpUser(UserManagerService userManager, int userHandle) { 21026 synchronized (mPackages) { 21027 mDirtyUsers.remove(userHandle); 21028 mUserNeedsBadging.delete(userHandle); 21029 mSettings.removeUserLPw(userHandle); 21030 mPendingBroadcasts.remove(userHandle); 21031 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 21032 removeUnusedPackagesLPw(userManager, userHandle); 21033 } 21034 } 21035 21036 /** 21037 * We're removing userHandle and would like to remove any downloaded packages 21038 * that are no longer in use by any other user. 21039 * @param userHandle the user being removed 21040 */ 21041 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 21042 final boolean DEBUG_CLEAN_APKS = false; 21043 int [] users = userManager.getUserIds(); 21044 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 21045 while (psit.hasNext()) { 21046 PackageSetting ps = psit.next(); 21047 if (ps.pkg == null) { 21048 continue; 21049 } 21050 final String packageName = ps.pkg.packageName; 21051 // Skip over if system app 21052 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 21053 continue; 21054 } 21055 if (DEBUG_CLEAN_APKS) { 21056 Slog.i(TAG, "Checking package " + packageName); 21057 } 21058 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 21059 if (keep) { 21060 if (DEBUG_CLEAN_APKS) { 21061 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 21062 } 21063 } else { 21064 for (int i = 0; i < users.length; i++) { 21065 if (users[i] != userHandle && ps.getInstalled(users[i])) { 21066 keep = true; 21067 if (DEBUG_CLEAN_APKS) { 21068 Slog.i(TAG, " Keeping package " + packageName + " for user " 21069 + users[i]); 21070 } 21071 break; 21072 } 21073 } 21074 } 21075 if (!keep) { 21076 if (DEBUG_CLEAN_APKS) { 21077 Slog.i(TAG, " Removing package " + packageName); 21078 } 21079 mHandler.post(new Runnable() { 21080 public void run() { 21081 deletePackageX(packageName, userHandle, 0); 21082 } //end run 21083 }); 21084 } 21085 } 21086 } 21087 21088 /** Called by UserManagerService */ 21089 void createNewUser(int userId, String[] disallowedPackages) { 21090 synchronized (mInstallLock) { 21091 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 21092 } 21093 synchronized (mPackages) { 21094 scheduleWritePackageRestrictionsLocked(userId); 21095 scheduleWritePackageListLocked(userId); 21096 applyFactoryDefaultBrowserLPw(userId); 21097 primeDomainVerificationsLPw(userId); 21098 } 21099 } 21100 21101 void onNewUserCreated(final int userId) { 21102 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21103 // If permission review for legacy apps is required, we represent 21104 // dagerous permissions for such apps as always granted runtime 21105 // permissions to keep per user flag state whether review is needed. 21106 // Hence, if a new user is added we have to propagate dangerous 21107 // permission grants for these legacy apps. 21108 if (mPermissionReviewRequired) { 21109 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 21110 | UPDATE_PERMISSIONS_REPLACE_ALL); 21111 } 21112 } 21113 21114 @Override 21115 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 21116 mContext.enforceCallingOrSelfPermission( 21117 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 21118 "Only package verification agents can read the verifier device identity"); 21119 21120 synchronized (mPackages) { 21121 return mSettings.getVerifierDeviceIdentityLPw(); 21122 } 21123 } 21124 21125 @Override 21126 public void setPermissionEnforced(String permission, boolean enforced) { 21127 // TODO: Now that we no longer change GID for storage, this should to away. 21128 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 21129 "setPermissionEnforced"); 21130 if (READ_EXTERNAL_STORAGE.equals(permission)) { 21131 synchronized (mPackages) { 21132 if (mSettings.mReadExternalStorageEnforced == null 21133 || mSettings.mReadExternalStorageEnforced != enforced) { 21134 mSettings.mReadExternalStorageEnforced = enforced; 21135 mSettings.writeLPr(); 21136 } 21137 } 21138 // kill any non-foreground processes so we restart them and 21139 // grant/revoke the GID. 21140 final IActivityManager am = ActivityManager.getService(); 21141 if (am != null) { 21142 final long token = Binder.clearCallingIdentity(); 21143 try { 21144 am.killProcessesBelowForeground("setPermissionEnforcement"); 21145 } catch (RemoteException e) { 21146 } finally { 21147 Binder.restoreCallingIdentity(token); 21148 } 21149 } 21150 } else { 21151 throw new IllegalArgumentException("No selective enforcement for " + permission); 21152 } 21153 } 21154 21155 @Override 21156 @Deprecated 21157 public boolean isPermissionEnforced(String permission) { 21158 return true; 21159 } 21160 21161 @Override 21162 public boolean isStorageLow() { 21163 final long token = Binder.clearCallingIdentity(); 21164 try { 21165 final DeviceStorageMonitorInternal 21166 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21167 if (dsm != null) { 21168 return dsm.isMemoryLow(); 21169 } else { 21170 return false; 21171 } 21172 } finally { 21173 Binder.restoreCallingIdentity(token); 21174 } 21175 } 21176 21177 @Override 21178 public IPackageInstaller getPackageInstaller() { 21179 return mInstallerService; 21180 } 21181 21182 private boolean userNeedsBadging(int userId) { 21183 int index = mUserNeedsBadging.indexOfKey(userId); 21184 if (index < 0) { 21185 final UserInfo userInfo; 21186 final long token = Binder.clearCallingIdentity(); 21187 try { 21188 userInfo = sUserManager.getUserInfo(userId); 21189 } finally { 21190 Binder.restoreCallingIdentity(token); 21191 } 21192 final boolean b; 21193 if (userInfo != null && userInfo.isManagedProfile()) { 21194 b = true; 21195 } else { 21196 b = false; 21197 } 21198 mUserNeedsBadging.put(userId, b); 21199 return b; 21200 } 21201 return mUserNeedsBadging.valueAt(index); 21202 } 21203 21204 @Override 21205 public KeySet getKeySetByAlias(String packageName, String alias) { 21206 if (packageName == null || alias == null) { 21207 return null; 21208 } 21209 synchronized(mPackages) { 21210 final PackageParser.Package pkg = mPackages.get(packageName); 21211 if (pkg == null) { 21212 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21213 throw new IllegalArgumentException("Unknown package: " + packageName); 21214 } 21215 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21216 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21217 } 21218 } 21219 21220 @Override 21221 public KeySet getSigningKeySet(String packageName) { 21222 if (packageName == null) { 21223 return null; 21224 } 21225 synchronized(mPackages) { 21226 final PackageParser.Package pkg = mPackages.get(packageName); 21227 if (pkg == null) { 21228 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21229 throw new IllegalArgumentException("Unknown package: " + packageName); 21230 } 21231 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21232 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21233 throw new SecurityException("May not access signing KeySet of other apps."); 21234 } 21235 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21236 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21237 } 21238 } 21239 21240 @Override 21241 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21242 if (packageName == null || ks == null) { 21243 return false; 21244 } 21245 synchronized(mPackages) { 21246 final PackageParser.Package pkg = mPackages.get(packageName); 21247 if (pkg == null) { 21248 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21249 throw new IllegalArgumentException("Unknown package: " + packageName); 21250 } 21251 IBinder ksh = ks.getToken(); 21252 if (ksh instanceof KeySetHandle) { 21253 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21254 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21255 } 21256 return false; 21257 } 21258 } 21259 21260 @Override 21261 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21262 if (packageName == null || ks == null) { 21263 return false; 21264 } 21265 synchronized(mPackages) { 21266 final PackageParser.Package pkg = mPackages.get(packageName); 21267 if (pkg == null) { 21268 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21269 throw new IllegalArgumentException("Unknown package: " + packageName); 21270 } 21271 IBinder ksh = ks.getToken(); 21272 if (ksh instanceof KeySetHandle) { 21273 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21274 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21275 } 21276 return false; 21277 } 21278 } 21279 21280 private void deletePackageIfUnusedLPr(final String packageName) { 21281 PackageSetting ps = mSettings.mPackages.get(packageName); 21282 if (ps == null) { 21283 return; 21284 } 21285 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21286 // TODO Implement atomic delete if package is unused 21287 // It is currently possible that the package will be deleted even if it is installed 21288 // after this method returns. 21289 mHandler.post(new Runnable() { 21290 public void run() { 21291 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21292 } 21293 }); 21294 } 21295 } 21296 21297 /** 21298 * Check and throw if the given before/after packages would be considered a 21299 * downgrade. 21300 */ 21301 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21302 throws PackageManagerException { 21303 if (after.versionCode < before.mVersionCode) { 21304 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21305 "Update version code " + after.versionCode + " is older than current " 21306 + before.mVersionCode); 21307 } else if (after.versionCode == before.mVersionCode) { 21308 if (after.baseRevisionCode < before.baseRevisionCode) { 21309 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21310 "Update base revision code " + after.baseRevisionCode 21311 + " is older than current " + before.baseRevisionCode); 21312 } 21313 21314 if (!ArrayUtils.isEmpty(after.splitNames)) { 21315 for (int i = 0; i < after.splitNames.length; i++) { 21316 final String splitName = after.splitNames[i]; 21317 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21318 if (j != -1) { 21319 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21320 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21321 "Update split " + splitName + " revision code " 21322 + after.splitRevisionCodes[i] + " is older than current " 21323 + before.splitRevisionCodes[j]); 21324 } 21325 } 21326 } 21327 } 21328 } 21329 } 21330 21331 private static class MoveCallbacks extends Handler { 21332 private static final int MSG_CREATED = 1; 21333 private static final int MSG_STATUS_CHANGED = 2; 21334 21335 private final RemoteCallbackList<IPackageMoveObserver> 21336 mCallbacks = new RemoteCallbackList<>(); 21337 21338 private final SparseIntArray mLastStatus = new SparseIntArray(); 21339 21340 public MoveCallbacks(Looper looper) { 21341 super(looper); 21342 } 21343 21344 public void register(IPackageMoveObserver callback) { 21345 mCallbacks.register(callback); 21346 } 21347 21348 public void unregister(IPackageMoveObserver callback) { 21349 mCallbacks.unregister(callback); 21350 } 21351 21352 @Override 21353 public void handleMessage(Message msg) { 21354 final SomeArgs args = (SomeArgs) msg.obj; 21355 final int n = mCallbacks.beginBroadcast(); 21356 for (int i = 0; i < n; i++) { 21357 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21358 try { 21359 invokeCallback(callback, msg.what, args); 21360 } catch (RemoteException ignored) { 21361 } 21362 } 21363 mCallbacks.finishBroadcast(); 21364 args.recycle(); 21365 } 21366 21367 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21368 throws RemoteException { 21369 switch (what) { 21370 case MSG_CREATED: { 21371 callback.onCreated(args.argi1, (Bundle) args.arg2); 21372 break; 21373 } 21374 case MSG_STATUS_CHANGED: { 21375 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21376 break; 21377 } 21378 } 21379 } 21380 21381 private void notifyCreated(int moveId, Bundle extras) { 21382 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21383 21384 final SomeArgs args = SomeArgs.obtain(); 21385 args.argi1 = moveId; 21386 args.arg2 = extras; 21387 obtainMessage(MSG_CREATED, args).sendToTarget(); 21388 } 21389 21390 private void notifyStatusChanged(int moveId, int status) { 21391 notifyStatusChanged(moveId, status, -1); 21392 } 21393 21394 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21395 Slog.v(TAG, "Move " + moveId + " status " + status); 21396 21397 final SomeArgs args = SomeArgs.obtain(); 21398 args.argi1 = moveId; 21399 args.argi2 = status; 21400 args.arg3 = estMillis; 21401 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21402 21403 synchronized (mLastStatus) { 21404 mLastStatus.put(moveId, status); 21405 } 21406 } 21407 } 21408 21409 private final static class OnPermissionChangeListeners extends Handler { 21410 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21411 21412 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21413 new RemoteCallbackList<>(); 21414 21415 public OnPermissionChangeListeners(Looper looper) { 21416 super(looper); 21417 } 21418 21419 @Override 21420 public void handleMessage(Message msg) { 21421 switch (msg.what) { 21422 case MSG_ON_PERMISSIONS_CHANGED: { 21423 final int uid = msg.arg1; 21424 handleOnPermissionsChanged(uid); 21425 } break; 21426 } 21427 } 21428 21429 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21430 mPermissionListeners.register(listener); 21431 21432 } 21433 21434 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21435 mPermissionListeners.unregister(listener); 21436 } 21437 21438 public void onPermissionsChanged(int uid) { 21439 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21440 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21441 } 21442 } 21443 21444 private void handleOnPermissionsChanged(int uid) { 21445 final int count = mPermissionListeners.beginBroadcast(); 21446 try { 21447 for (int i = 0; i < count; i++) { 21448 IOnPermissionsChangeListener callback = mPermissionListeners 21449 .getBroadcastItem(i); 21450 try { 21451 callback.onPermissionsChanged(uid); 21452 } catch (RemoteException e) { 21453 Log.e(TAG, "Permission listener is dead", e); 21454 } 21455 } 21456 } finally { 21457 mPermissionListeners.finishBroadcast(); 21458 } 21459 } 21460 } 21461 21462 private class PackageManagerInternalImpl extends PackageManagerInternal { 21463 @Override 21464 public void setLocationPackagesProvider(PackagesProvider provider) { 21465 synchronized (mPackages) { 21466 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21467 } 21468 } 21469 21470 @Override 21471 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21472 synchronized (mPackages) { 21473 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21474 } 21475 } 21476 21477 @Override 21478 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21479 synchronized (mPackages) { 21480 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21481 } 21482 } 21483 21484 @Override 21485 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21486 synchronized (mPackages) { 21487 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21488 } 21489 } 21490 21491 @Override 21492 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21493 synchronized (mPackages) { 21494 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21495 } 21496 } 21497 21498 @Override 21499 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21500 synchronized (mPackages) { 21501 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21502 } 21503 } 21504 21505 @Override 21506 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21507 synchronized (mPackages) { 21508 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21509 packageName, userId); 21510 } 21511 } 21512 21513 @Override 21514 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21515 synchronized (mPackages) { 21516 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21517 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21518 packageName, userId); 21519 } 21520 } 21521 21522 @Override 21523 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21524 synchronized (mPackages) { 21525 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21526 packageName, userId); 21527 } 21528 } 21529 21530 @Override 21531 public void setKeepUninstalledPackages(final List<String> packageList) { 21532 Preconditions.checkNotNull(packageList); 21533 List<String> removedFromList = null; 21534 synchronized (mPackages) { 21535 if (mKeepUninstalledPackages != null) { 21536 final int packagesCount = mKeepUninstalledPackages.size(); 21537 for (int i = 0; i < packagesCount; i++) { 21538 String oldPackage = mKeepUninstalledPackages.get(i); 21539 if (packageList != null && packageList.contains(oldPackage)) { 21540 continue; 21541 } 21542 if (removedFromList == null) { 21543 removedFromList = new ArrayList<>(); 21544 } 21545 removedFromList.add(oldPackage); 21546 } 21547 } 21548 mKeepUninstalledPackages = new ArrayList<>(packageList); 21549 if (removedFromList != null) { 21550 final int removedCount = removedFromList.size(); 21551 for (int i = 0; i < removedCount; i++) { 21552 deletePackageIfUnusedLPr(removedFromList.get(i)); 21553 } 21554 } 21555 } 21556 } 21557 21558 @Override 21559 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21560 synchronized (mPackages) { 21561 // If we do not support permission review, done. 21562 if (!mPermissionReviewRequired) { 21563 return false; 21564 } 21565 21566 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21567 if (packageSetting == null) { 21568 return false; 21569 } 21570 21571 // Permission review applies only to apps not supporting the new permission model. 21572 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21573 return false; 21574 } 21575 21576 // Legacy apps have the permission and get user consent on launch. 21577 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21578 return permissionsState.isPermissionReviewRequired(userId); 21579 } 21580 } 21581 21582 @Override 21583 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21584 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21585 } 21586 21587 @Override 21588 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21589 int userId) { 21590 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21591 } 21592 21593 @Override 21594 public void setDeviceAndProfileOwnerPackages( 21595 int deviceOwnerUserId, String deviceOwnerPackage, 21596 SparseArray<String> profileOwnerPackages) { 21597 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21598 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21599 } 21600 21601 @Override 21602 public boolean isPackageDataProtected(int userId, String packageName) { 21603 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21604 } 21605 21606 @Override 21607 public boolean isPackageEphemeral(int userId, String packageName) { 21608 synchronized (mPackages) { 21609 PackageParser.Package p = mPackages.get(packageName); 21610 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21611 } 21612 } 21613 21614 @Override 21615 public boolean wasPackageEverLaunched(String packageName, int userId) { 21616 synchronized (mPackages) { 21617 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21618 } 21619 } 21620 21621 @Override 21622 public void grantRuntimePermission(String packageName, String name, int userId, 21623 boolean overridePolicy) { 21624 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21625 overridePolicy); 21626 } 21627 21628 @Override 21629 public void revokeRuntimePermission(String packageName, String name, int userId, 21630 boolean overridePolicy) { 21631 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21632 overridePolicy); 21633 } 21634 21635 @Override 21636 public String getNameForUid(int uid) { 21637 return PackageManagerService.this.getNameForUid(uid); 21638 } 21639 21640 @Override 21641 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21642 Intent origIntent, String resolvedType, Intent launchIntent, 21643 String callingPackage, int userId) { 21644 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21645 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21646 } 21647 21648 public String getSetupWizardPackageName() { 21649 return mSetupWizardPackage; 21650 } 21651 } 21652 21653 @Override 21654 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21655 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21656 synchronized (mPackages) { 21657 final long identity = Binder.clearCallingIdentity(); 21658 try { 21659 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21660 packageNames, userId); 21661 } finally { 21662 Binder.restoreCallingIdentity(identity); 21663 } 21664 } 21665 } 21666 21667 private static void enforceSystemOrPhoneCaller(String tag) { 21668 int callingUid = Binder.getCallingUid(); 21669 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21670 throw new SecurityException( 21671 "Cannot call " + tag + " from UID " + callingUid); 21672 } 21673 } 21674 21675 boolean isHistoricalPackageUsageAvailable() { 21676 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21677 } 21678 21679 /** 21680 * Return a <b>copy</b> of the collection of packages known to the package manager. 21681 * @return A copy of the values of mPackages. 21682 */ 21683 Collection<PackageParser.Package> getPackages() { 21684 synchronized (mPackages) { 21685 return new ArrayList<>(mPackages.values()); 21686 } 21687 } 21688 21689 /** 21690 * Logs process start information (including base APK hash) to the security log. 21691 * @hide 21692 */ 21693 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21694 String apkFile, int pid) { 21695 if (!SecurityLog.isLoggingEnabled()) { 21696 return; 21697 } 21698 Bundle data = new Bundle(); 21699 data.putLong("startTimestamp", System.currentTimeMillis()); 21700 data.putString("processName", processName); 21701 data.putInt("uid", uid); 21702 data.putString("seinfo", seinfo); 21703 data.putString("apkFile", apkFile); 21704 data.putInt("pid", pid); 21705 Message msg = mProcessLoggingHandler.obtainMessage( 21706 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21707 msg.setData(data); 21708 mProcessLoggingHandler.sendMessage(msg); 21709 } 21710 21711 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21712 return mCompilerStats.getPackageStats(pkgName); 21713 } 21714 21715 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21716 return getOrCreateCompilerPackageStats(pkg.packageName); 21717 } 21718 21719 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21720 return mCompilerStats.getOrCreatePackageStats(pkgName); 21721 } 21722 21723 public void deleteCompilerPackageStats(String pkgName) { 21724 mCompilerStats.deletePackageStats(pkgName); 21725 } 21726} 21727