PackageManagerService.java revision 5b95d07725b629272f202993f3620a7b0f1dd6fb
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 // Read and update the usage of dex files. 2626 // At this point we know the code paths of the packages, so we can validate 2627 // the disk file and build the internal cache. 2628 // The usage file is expected to be small so loading and verifying it 2629 // should take a fairly small time compare to the other activities (e.g. package 2630 // scanning). 2631 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2632 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2633 for (int userId : currentUserIds) { 2634 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2635 } 2636 mDexManager.load(userPackages); 2637 2638 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2639 SystemClock.uptimeMillis()); 2640 Slog.i(TAG, "Time to scan packages: " 2641 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2642 + " seconds"); 2643 2644 // If the platform SDK has changed since the last time we booted, 2645 // we need to re-grant app permission to catch any new ones that 2646 // appear. This is really a hack, and means that apps can in some 2647 // cases get permissions that the user didn't initially explicitly 2648 // allow... it would be nice to have some better way to handle 2649 // this situation. 2650 int updateFlags = UPDATE_PERMISSIONS_ALL; 2651 if (ver.sdkVersion != mSdkVersion) { 2652 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2653 + mSdkVersion + "; regranting permissions for internal storage"); 2654 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2655 } 2656 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2657 ver.sdkVersion = mSdkVersion; 2658 2659 // If this is the first boot or an update from pre-M, and it is a normal 2660 // boot, then we need to initialize the default preferred apps across 2661 // all defined users. 2662 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2663 for (UserInfo user : sUserManager.getUsers(true)) { 2664 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2665 applyFactoryDefaultBrowserLPw(user.id); 2666 primeDomainVerificationsLPw(user.id); 2667 } 2668 } 2669 2670 // Prepare storage for system user really early during boot, 2671 // since core system apps like SettingsProvider and SystemUI 2672 // can't wait for user to start 2673 final int storageFlags; 2674 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2675 storageFlags = StorageManager.FLAG_STORAGE_DE; 2676 } else { 2677 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2678 } 2679 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2680 storageFlags, true /* migrateAppData */); 2681 2682 // If this is first boot after an OTA, and a normal boot, then 2683 // we need to clear code cache directories. 2684 // Note that we do *not* clear the application profiles. These remain valid 2685 // across OTAs and are used to drive profile verification (post OTA) and 2686 // profile compilation (without waiting to collect a fresh set of profiles). 2687 if (mIsUpgrade && !onlyCore) { 2688 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2689 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2690 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2691 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2692 // No apps are running this early, so no need to freeze 2693 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2694 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2695 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2696 } 2697 } 2698 ver.fingerprint = Build.FINGERPRINT; 2699 } 2700 2701 checkDefaultBrowser(); 2702 2703 // clear only after permissions and other defaults have been updated 2704 mExistingSystemPackages.clear(); 2705 mPromoteSystemApps = false; 2706 2707 // All the changes are done during package scanning. 2708 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2709 2710 // can downgrade to reader 2711 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2712 mSettings.writeLPr(); 2713 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2714 2715 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2716 // early on (before the package manager declares itself as early) because other 2717 // components in the system server might ask for package contexts for these apps. 2718 // 2719 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2720 // (i.e, that the data partition is unavailable). 2721 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2722 long start = System.nanoTime(); 2723 List<PackageParser.Package> coreApps = new ArrayList<>(); 2724 for (PackageParser.Package pkg : mPackages.values()) { 2725 if (pkg.coreApp) { 2726 coreApps.add(pkg); 2727 } 2728 } 2729 2730 int[] stats = performDexOptUpgrade(coreApps, false, 2731 getCompilerFilterForReason(REASON_CORE_APP)); 2732 2733 final int elapsedTimeSeconds = 2734 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2735 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2736 2737 if (DEBUG_DEXOPT) { 2738 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2739 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2740 } 2741 2742 2743 // TODO: Should we log these stats to tron too ? 2744 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2745 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2746 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2747 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2748 } 2749 2750 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2751 SystemClock.uptimeMillis()); 2752 2753 if (!mOnlyCore) { 2754 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2755 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2756 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2757 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2758 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2759 mIntentFilterVerifierComponent); 2760 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2761 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2762 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2763 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2764 } else { 2765 mRequiredVerifierPackage = null; 2766 mRequiredInstallerPackage = null; 2767 mRequiredUninstallerPackage = null; 2768 mIntentFilterVerifierComponent = null; 2769 mIntentFilterVerifier = null; 2770 mServicesSystemSharedLibraryPackageName = null; 2771 mSharedSystemSharedLibraryPackageName = null; 2772 } 2773 2774 mInstallerService = new PackageInstallerService(context, this); 2775 2776 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2777 if (ephemeralResolverComponent != null) { 2778 if (DEBUG_EPHEMERAL) { 2779 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2780 } 2781 mEphemeralResolverConnection = 2782 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2783 } else { 2784 mEphemeralResolverConnection = null; 2785 } 2786 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2787 if (mEphemeralInstallerComponent != null) { 2788 if (DEBUG_EPHEMERAL) { 2789 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2790 } 2791 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2792 } 2793 2794 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2795 } // synchronized (mPackages) 2796 } // synchronized (mInstallLock) 2797 2798 // Now after opening every single application zip, make sure they 2799 // are all flushed. Not really needed, but keeps things nice and 2800 // tidy. 2801 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2802 Runtime.getRuntime().gc(); 2803 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2804 2805 // The initial scanning above does many calls into installd while 2806 // holding the mPackages lock, but we're mostly interested in yelling 2807 // once we have a booted system. 2808 mInstaller.setWarnIfHeld(mPackages); 2809 2810 // Expose private service for system components to use. 2811 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2813 } 2814 2815 @Override 2816 public boolean isFirstBoot() { 2817 return mFirstBoot; 2818 } 2819 2820 @Override 2821 public boolean isOnlyCoreApps() { 2822 return mOnlyCore; 2823 } 2824 2825 @Override 2826 public boolean isUpgrade() { 2827 return mIsUpgrade; 2828 } 2829 2830 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2831 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2832 2833 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2834 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2835 UserHandle.USER_SYSTEM); 2836 if (matches.size() == 1) { 2837 return matches.get(0).getComponentInfo().packageName; 2838 } else if (matches.size() == 0) { 2839 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2840 return null; 2841 } 2842 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2843 } 2844 2845 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2846 synchronized (mPackages) { 2847 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2848 if (libraryEntry == null) { 2849 throw new IllegalStateException("Missing required shared library:" + libraryName); 2850 } 2851 return libraryEntry.apk; 2852 } 2853 } 2854 2855 private @NonNull String getRequiredInstallerLPr() { 2856 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2857 intent.addCategory(Intent.CATEGORY_DEFAULT); 2858 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2859 2860 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2861 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2862 UserHandle.USER_SYSTEM); 2863 if (matches.size() == 1) { 2864 ResolveInfo resolveInfo = matches.get(0); 2865 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2866 throw new RuntimeException("The installer must be a privileged app"); 2867 } 2868 return matches.get(0).getComponentInfo().packageName; 2869 } else { 2870 throw new RuntimeException("There must be exactly one installer; found " + matches); 2871 } 2872 } 2873 2874 private @NonNull String getRequiredUninstallerLPr() { 2875 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2876 intent.addCategory(Intent.CATEGORY_DEFAULT); 2877 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2878 2879 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2880 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2881 UserHandle.USER_SYSTEM); 2882 if (resolveInfo == null || 2883 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2884 throw new RuntimeException("There must be exactly one uninstaller; found " 2885 + resolveInfo); 2886 } 2887 return resolveInfo.getComponentInfo().packageName; 2888 } 2889 2890 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2891 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2892 2893 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2894 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2895 UserHandle.USER_SYSTEM); 2896 ResolveInfo best = null; 2897 final int N = matches.size(); 2898 for (int i = 0; i < N; i++) { 2899 final ResolveInfo cur = matches.get(i); 2900 final String packageName = cur.getComponentInfo().packageName; 2901 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2902 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2903 continue; 2904 } 2905 2906 if (best == null || cur.priority > best.priority) { 2907 best = cur; 2908 } 2909 } 2910 2911 if (best != null) { 2912 return best.getComponentInfo().getComponentName(); 2913 } else { 2914 throw new RuntimeException("There must be at least one intent filter verifier"); 2915 } 2916 } 2917 2918 private @Nullable ComponentName getEphemeralResolverLPr() { 2919 final String[] packageArray = 2920 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2921 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2922 if (DEBUG_EPHEMERAL) { 2923 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2924 } 2925 return null; 2926 } 2927 2928 final int resolveFlags = 2929 MATCH_DIRECT_BOOT_AWARE 2930 | MATCH_DIRECT_BOOT_UNAWARE 2931 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2932 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2933 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2934 resolveFlags, UserHandle.USER_SYSTEM); 2935 2936 final int N = resolvers.size(); 2937 if (N == 0) { 2938 if (DEBUG_EPHEMERAL) { 2939 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2940 } 2941 return null; 2942 } 2943 2944 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2945 for (int i = 0; i < N; i++) { 2946 final ResolveInfo info = resolvers.get(i); 2947 2948 if (info.serviceInfo == null) { 2949 continue; 2950 } 2951 2952 final String packageName = info.serviceInfo.packageName; 2953 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2954 if (DEBUG_EPHEMERAL) { 2955 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2956 + " pkg: " + packageName + ", info:" + info); 2957 } 2958 continue; 2959 } 2960 2961 if (DEBUG_EPHEMERAL) { 2962 Slog.v(TAG, "Ephemeral resolver found;" 2963 + " pkg: " + packageName + ", info:" + info); 2964 } 2965 return new ComponentName(packageName, info.serviceInfo.name); 2966 } 2967 if (DEBUG_EPHEMERAL) { 2968 Slog.v(TAG, "Ephemeral resolver NOT found"); 2969 } 2970 return null; 2971 } 2972 2973 private @Nullable ComponentName getEphemeralInstallerLPr() { 2974 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2975 intent.addCategory(Intent.CATEGORY_DEFAULT); 2976 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2977 2978 final int resolveFlags = 2979 MATCH_DIRECT_BOOT_AWARE 2980 | MATCH_DIRECT_BOOT_UNAWARE 2981 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2982 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2983 resolveFlags, UserHandle.USER_SYSTEM); 2984 Iterator<ResolveInfo> iter = matches.iterator(); 2985 while (iter.hasNext()) { 2986 final ResolveInfo rInfo = iter.next(); 2987 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 2988 if (ps != null) { 2989 final PermissionsState permissionsState = ps.getPermissionsState(); 2990 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 2991 continue; 2992 } 2993 } 2994 iter.remove(); 2995 } 2996 if (matches.size() == 0) { 2997 return null; 2998 } else if (matches.size() == 1) { 2999 return matches.get(0).getComponentInfo().getComponentName(); 3000 } else { 3001 throw new RuntimeException( 3002 "There must be at most one ephemeral installer; found " + matches); 3003 } 3004 } 3005 3006 private void primeDomainVerificationsLPw(int userId) { 3007 if (DEBUG_DOMAIN_VERIFICATION) { 3008 Slog.d(TAG, "Priming domain verifications in user " + userId); 3009 } 3010 3011 SystemConfig systemConfig = SystemConfig.getInstance(); 3012 ArraySet<String> packages = systemConfig.getLinkedApps(); 3013 3014 for (String packageName : packages) { 3015 PackageParser.Package pkg = mPackages.get(packageName); 3016 if (pkg != null) { 3017 if (!pkg.isSystemApp()) { 3018 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3019 continue; 3020 } 3021 3022 ArraySet<String> domains = null; 3023 for (PackageParser.Activity a : pkg.activities) { 3024 for (ActivityIntentInfo filter : a.intents) { 3025 if (hasValidDomains(filter)) { 3026 if (domains == null) { 3027 domains = new ArraySet<String>(); 3028 } 3029 domains.addAll(filter.getHostsList()); 3030 } 3031 } 3032 } 3033 3034 if (domains != null && domains.size() > 0) { 3035 if (DEBUG_DOMAIN_VERIFICATION) { 3036 Slog.v(TAG, " + " + packageName); 3037 } 3038 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3039 // state w.r.t. the formal app-linkage "no verification attempted" state; 3040 // and then 'always' in the per-user state actually used for intent resolution. 3041 final IntentFilterVerificationInfo ivi; 3042 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3043 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3044 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3045 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3046 } else { 3047 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3048 + "' does not handle web links"); 3049 } 3050 } else { 3051 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3052 } 3053 } 3054 3055 scheduleWritePackageRestrictionsLocked(userId); 3056 scheduleWriteSettingsLocked(); 3057 } 3058 3059 private void applyFactoryDefaultBrowserLPw(int userId) { 3060 // The default browser app's package name is stored in a string resource, 3061 // with a product-specific overlay used for vendor customization. 3062 String browserPkg = mContext.getResources().getString( 3063 com.android.internal.R.string.default_browser); 3064 if (!TextUtils.isEmpty(browserPkg)) { 3065 // non-empty string => required to be a known package 3066 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3067 if (ps == null) { 3068 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3069 browserPkg = null; 3070 } else { 3071 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3072 } 3073 } 3074 3075 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3076 // default. If there's more than one, just leave everything alone. 3077 if (browserPkg == null) { 3078 calculateDefaultBrowserLPw(userId); 3079 } 3080 } 3081 3082 private void calculateDefaultBrowserLPw(int userId) { 3083 List<String> allBrowsers = resolveAllBrowserApps(userId); 3084 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3085 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3086 } 3087 3088 private List<String> resolveAllBrowserApps(int userId) { 3089 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3090 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3091 PackageManager.MATCH_ALL, userId); 3092 3093 final int count = list.size(); 3094 List<String> result = new ArrayList<String>(count); 3095 for (int i=0; i<count; i++) { 3096 ResolveInfo info = list.get(i); 3097 if (info.activityInfo == null 3098 || !info.handleAllWebDataURI 3099 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3100 || result.contains(info.activityInfo.packageName)) { 3101 continue; 3102 } 3103 result.add(info.activityInfo.packageName); 3104 } 3105 3106 return result; 3107 } 3108 3109 private boolean packageIsBrowser(String packageName, int userId) { 3110 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3111 PackageManager.MATCH_ALL, userId); 3112 final int N = list.size(); 3113 for (int i = 0; i < N; i++) { 3114 ResolveInfo info = list.get(i); 3115 if (packageName.equals(info.activityInfo.packageName)) { 3116 return true; 3117 } 3118 } 3119 return false; 3120 } 3121 3122 private void checkDefaultBrowser() { 3123 final int myUserId = UserHandle.myUserId(); 3124 final String packageName = getDefaultBrowserPackageName(myUserId); 3125 if (packageName != null) { 3126 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3127 if (info == null) { 3128 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3129 synchronized (mPackages) { 3130 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3131 } 3132 } 3133 } 3134 } 3135 3136 @Override 3137 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3138 throws RemoteException { 3139 try { 3140 return super.onTransact(code, data, reply, flags); 3141 } catch (RuntimeException e) { 3142 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3143 Slog.wtf(TAG, "Package Manager Crash", e); 3144 } 3145 throw e; 3146 } 3147 } 3148 3149 static int[] appendInts(int[] cur, int[] add) { 3150 if (add == null) return cur; 3151 if (cur == null) return add; 3152 final int N = add.length; 3153 for (int i=0; i<N; i++) { 3154 cur = appendInt(cur, add[i]); 3155 } 3156 return cur; 3157 } 3158 3159 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3160 if (!sUserManager.exists(userId)) return null; 3161 if (ps == null) { 3162 return null; 3163 } 3164 final PackageParser.Package p = ps.pkg; 3165 if (p == null) { 3166 return null; 3167 } 3168 3169 final PermissionsState permissionsState = ps.getPermissionsState(); 3170 3171 // Compute GIDs only if requested 3172 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3173 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3174 // Compute granted permissions only if package has requested permissions 3175 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3176 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3177 final PackageUserState state = ps.readUserState(userId); 3178 3179 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3180 && ps.isSystem()) { 3181 flags |= MATCH_ANY_USER; 3182 } 3183 3184 return PackageParser.generatePackageInfo(p, gids, flags, 3185 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3186 } 3187 3188 @Override 3189 public void checkPackageStartable(String packageName, int userId) { 3190 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3191 3192 synchronized (mPackages) { 3193 final PackageSetting ps = mSettings.mPackages.get(packageName); 3194 if (ps == null) { 3195 throw new SecurityException("Package " + packageName + " was not found!"); 3196 } 3197 3198 if (!ps.getInstalled(userId)) { 3199 throw new SecurityException( 3200 "Package " + packageName + " was not installed for user " + userId + "!"); 3201 } 3202 3203 if (mSafeMode && !ps.isSystem()) { 3204 throw new SecurityException("Package " + packageName + " not a system app!"); 3205 } 3206 3207 if (mFrozenPackages.contains(packageName)) { 3208 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3209 } 3210 3211 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3212 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3213 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3214 } 3215 } 3216 } 3217 3218 @Override 3219 public boolean isPackageAvailable(String packageName, int userId) { 3220 if (!sUserManager.exists(userId)) return false; 3221 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3222 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3223 synchronized (mPackages) { 3224 PackageParser.Package p = mPackages.get(packageName); 3225 if (p != null) { 3226 final PackageSetting ps = (PackageSetting) p.mExtras; 3227 if (ps != null) { 3228 final PackageUserState state = ps.readUserState(userId); 3229 if (state != null) { 3230 return PackageParser.isAvailable(state); 3231 } 3232 } 3233 } 3234 } 3235 return false; 3236 } 3237 3238 @Override 3239 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3240 if (!sUserManager.exists(userId)) return null; 3241 flags = updateFlagsForPackage(flags, userId, packageName); 3242 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3243 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3244 3245 // reader 3246 synchronized (mPackages) { 3247 // Normalize package name to hanlde renamed packages 3248 packageName = normalizePackageNameLPr(packageName); 3249 3250 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3251 PackageParser.Package p = null; 3252 if (matchFactoryOnly) { 3253 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3254 if (ps != null) { 3255 return generatePackageInfo(ps, flags, userId); 3256 } 3257 } 3258 if (p == null) { 3259 p = mPackages.get(packageName); 3260 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3261 return null; 3262 } 3263 } 3264 if (DEBUG_PACKAGE_INFO) 3265 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3266 if (p != null) { 3267 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3268 } 3269 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3270 final PackageSetting ps = mSettings.mPackages.get(packageName); 3271 return generatePackageInfo(ps, flags, userId); 3272 } 3273 } 3274 return null; 3275 } 3276 3277 @Override 3278 public String[] currentToCanonicalPackageNames(String[] names) { 3279 String[] out = new String[names.length]; 3280 // reader 3281 synchronized (mPackages) { 3282 for (int i=names.length-1; i>=0; i--) { 3283 PackageSetting ps = mSettings.mPackages.get(names[i]); 3284 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3285 } 3286 } 3287 return out; 3288 } 3289 3290 @Override 3291 public String[] canonicalToCurrentPackageNames(String[] names) { 3292 String[] out = new String[names.length]; 3293 // reader 3294 synchronized (mPackages) { 3295 for (int i=names.length-1; i>=0; i--) { 3296 String cur = mSettings.getRenamedPackageLPr(names[i]); 3297 out[i] = cur != null ? cur : names[i]; 3298 } 3299 } 3300 return out; 3301 } 3302 3303 @Override 3304 public int getPackageUid(String packageName, int flags, int userId) { 3305 if (!sUserManager.exists(userId)) return -1; 3306 flags = updateFlagsForPackage(flags, userId, packageName); 3307 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3308 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3309 3310 // reader 3311 synchronized (mPackages) { 3312 final PackageParser.Package p = mPackages.get(packageName); 3313 if (p != null && p.isMatch(flags)) { 3314 return UserHandle.getUid(userId, p.applicationInfo.uid); 3315 } 3316 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3317 final PackageSetting ps = mSettings.mPackages.get(packageName); 3318 if (ps != null && ps.isMatch(flags)) { 3319 return UserHandle.getUid(userId, ps.appId); 3320 } 3321 } 3322 } 3323 3324 return -1; 3325 } 3326 3327 @Override 3328 public int[] getPackageGids(String packageName, int flags, int userId) { 3329 if (!sUserManager.exists(userId)) return null; 3330 flags = updateFlagsForPackage(flags, userId, packageName); 3331 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3332 false /* requireFullPermission */, false /* checkShell */, 3333 "getPackageGids"); 3334 3335 // reader 3336 synchronized (mPackages) { 3337 final PackageParser.Package p = mPackages.get(packageName); 3338 if (p != null && p.isMatch(flags)) { 3339 PackageSetting ps = (PackageSetting) p.mExtras; 3340 // TODO: Shouldn't this be checking for package installed state for userId and 3341 // return null? 3342 return ps.getPermissionsState().computeGids(userId); 3343 } 3344 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3345 final PackageSetting ps = mSettings.mPackages.get(packageName); 3346 if (ps != null && ps.isMatch(flags)) { 3347 return ps.getPermissionsState().computeGids(userId); 3348 } 3349 } 3350 } 3351 3352 return null; 3353 } 3354 3355 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3356 if (bp.perm != null) { 3357 return PackageParser.generatePermissionInfo(bp.perm, flags); 3358 } 3359 PermissionInfo pi = new PermissionInfo(); 3360 pi.name = bp.name; 3361 pi.packageName = bp.sourcePackage; 3362 pi.nonLocalizedLabel = bp.name; 3363 pi.protectionLevel = bp.protectionLevel; 3364 return pi; 3365 } 3366 3367 @Override 3368 public PermissionInfo getPermissionInfo(String name, int flags) { 3369 // reader 3370 synchronized (mPackages) { 3371 final BasePermission p = mSettings.mPermissions.get(name); 3372 if (p != null) { 3373 return generatePermissionInfo(p, flags); 3374 } 3375 return null; 3376 } 3377 } 3378 3379 @Override 3380 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3381 int flags) { 3382 // reader 3383 synchronized (mPackages) { 3384 if (group != null && !mPermissionGroups.containsKey(group)) { 3385 // This is thrown as NameNotFoundException 3386 return null; 3387 } 3388 3389 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3390 for (BasePermission p : mSettings.mPermissions.values()) { 3391 if (group == null) { 3392 if (p.perm == null || p.perm.info.group == null) { 3393 out.add(generatePermissionInfo(p, flags)); 3394 } 3395 } else { 3396 if (p.perm != null && group.equals(p.perm.info.group)) { 3397 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3398 } 3399 } 3400 } 3401 return new ParceledListSlice<>(out); 3402 } 3403 } 3404 3405 @Override 3406 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3407 // reader 3408 synchronized (mPackages) { 3409 return PackageParser.generatePermissionGroupInfo( 3410 mPermissionGroups.get(name), flags); 3411 } 3412 } 3413 3414 @Override 3415 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3416 // reader 3417 synchronized (mPackages) { 3418 final int N = mPermissionGroups.size(); 3419 ArrayList<PermissionGroupInfo> out 3420 = new ArrayList<PermissionGroupInfo>(N); 3421 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3422 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3423 } 3424 return new ParceledListSlice<>(out); 3425 } 3426 } 3427 3428 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3429 int userId) { 3430 if (!sUserManager.exists(userId)) return null; 3431 PackageSetting ps = mSettings.mPackages.get(packageName); 3432 if (ps != null) { 3433 if (ps.pkg == null) { 3434 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3435 if (pInfo != null) { 3436 return pInfo.applicationInfo; 3437 } 3438 return null; 3439 } 3440 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3441 ps.readUserState(userId), userId); 3442 } 3443 return null; 3444 } 3445 3446 @Override 3447 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3448 if (!sUserManager.exists(userId)) return null; 3449 flags = updateFlagsForApplication(flags, userId, packageName); 3450 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3451 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3452 3453 // writer 3454 synchronized (mPackages) { 3455 // Normalize package name to hanlde renamed packages 3456 packageName = normalizePackageNameLPr(packageName); 3457 3458 PackageParser.Package p = mPackages.get(packageName); 3459 if (DEBUG_PACKAGE_INFO) Log.v( 3460 TAG, "getApplicationInfo " + packageName 3461 + ": " + p); 3462 if (p != null) { 3463 PackageSetting ps = mSettings.mPackages.get(packageName); 3464 if (ps == null) return null; 3465 // Note: isEnabledLP() does not apply here - always return info 3466 return PackageParser.generateApplicationInfo( 3467 p, flags, ps.readUserState(userId), userId); 3468 } 3469 if ("android".equals(packageName)||"system".equals(packageName)) { 3470 return mAndroidApplication; 3471 } 3472 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3473 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3474 } 3475 } 3476 return null; 3477 } 3478 3479 private String normalizePackageNameLPr(String packageName) { 3480 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3481 return normalizedPackageName != null ? normalizedPackageName : packageName; 3482 } 3483 3484 @Override 3485 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3486 final IPackageDataObserver observer) { 3487 mContext.enforceCallingOrSelfPermission( 3488 android.Manifest.permission.CLEAR_APP_CACHE, null); 3489 // Queue up an async operation since clearing cache may take a little while. 3490 mHandler.post(new Runnable() { 3491 public void run() { 3492 mHandler.removeCallbacks(this); 3493 boolean success = true; 3494 synchronized (mInstallLock) { 3495 try { 3496 mInstaller.freeCache(volumeUuid, freeStorageSize); 3497 } catch (InstallerException e) { 3498 Slog.w(TAG, "Couldn't clear application caches: " + e); 3499 success = false; 3500 } 3501 } 3502 if (observer != null) { 3503 try { 3504 observer.onRemoveCompleted(null, success); 3505 } catch (RemoteException e) { 3506 Slog.w(TAG, "RemoveException when invoking call back"); 3507 } 3508 } 3509 } 3510 }); 3511 } 3512 3513 @Override 3514 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3515 final IntentSender pi) { 3516 mContext.enforceCallingOrSelfPermission( 3517 android.Manifest.permission.CLEAR_APP_CACHE, null); 3518 // Queue up an async operation since clearing cache may take a little while. 3519 mHandler.post(new Runnable() { 3520 public void run() { 3521 mHandler.removeCallbacks(this); 3522 boolean success = true; 3523 synchronized (mInstallLock) { 3524 try { 3525 mInstaller.freeCache(volumeUuid, freeStorageSize); 3526 } catch (InstallerException e) { 3527 Slog.w(TAG, "Couldn't clear application caches: " + e); 3528 success = false; 3529 } 3530 } 3531 if(pi != null) { 3532 try { 3533 // Callback via pending intent 3534 int code = success ? 1 : 0; 3535 pi.sendIntent(null, code, null, 3536 null, null); 3537 } catch (SendIntentException e1) { 3538 Slog.i(TAG, "Failed to send pending intent"); 3539 } 3540 } 3541 } 3542 }); 3543 } 3544 3545 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3546 synchronized (mInstallLock) { 3547 try { 3548 mInstaller.freeCache(volumeUuid, freeStorageSize); 3549 } catch (InstallerException e) { 3550 throw new IOException("Failed to free enough space", e); 3551 } 3552 } 3553 } 3554 3555 /** 3556 * Update given flags based on encryption status of current user. 3557 */ 3558 private int updateFlags(int flags, int userId) { 3559 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3560 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3561 // Caller expressed an explicit opinion about what encryption 3562 // aware/unaware components they want to see, so fall through and 3563 // give them what they want 3564 } else { 3565 // Caller expressed no opinion, so match based on user state 3566 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3567 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3568 } else { 3569 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3570 } 3571 } 3572 return flags; 3573 } 3574 3575 private UserManagerInternal getUserManagerInternal() { 3576 if (mUserManagerInternal == null) { 3577 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3578 } 3579 return mUserManagerInternal; 3580 } 3581 3582 /** 3583 * Update given flags when being used to request {@link PackageInfo}. 3584 */ 3585 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3586 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3587 boolean triaged = true; 3588 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3589 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3590 // Caller is asking for component details, so they'd better be 3591 // asking for specific encryption matching behavior, or be triaged 3592 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3593 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3594 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3595 triaged = false; 3596 } 3597 } 3598 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3599 | PackageManager.MATCH_SYSTEM_ONLY 3600 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3601 triaged = false; 3602 } 3603 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3604 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3605 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3606 + Debug.getCallers(5)); 3607 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3608 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3609 // If the caller wants all packages and has a restricted profile associated with it, 3610 // then match all users. This is to make sure that launchers that need to access work 3611 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3612 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3613 flags |= PackageManager.MATCH_ANY_USER; 3614 } 3615 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3616 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3617 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3618 } 3619 return updateFlags(flags, userId); 3620 } 3621 3622 /** 3623 * Update given flags when being used to request {@link ApplicationInfo}. 3624 */ 3625 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3626 return updateFlagsForPackage(flags, userId, cookie); 3627 } 3628 3629 /** 3630 * Update given flags when being used to request {@link ComponentInfo}. 3631 */ 3632 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3633 if (cookie instanceof Intent) { 3634 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3635 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3636 } 3637 } 3638 3639 boolean triaged = true; 3640 // Caller is asking for component details, so they'd better be 3641 // asking for specific encryption matching behavior, or be triaged 3642 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3643 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3644 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3645 triaged = false; 3646 } 3647 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3648 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3649 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3650 } 3651 3652 return updateFlags(flags, userId); 3653 } 3654 3655 /** 3656 * Update given flags when being used to request {@link ResolveInfo}. 3657 */ 3658 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3659 // Safe mode means we shouldn't match any third-party components 3660 if (mSafeMode) { 3661 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3662 } 3663 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 3664 if (ephemeralPkgName != null) { 3665 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3666 flags |= PackageManager.MATCH_EPHEMERAL; 3667 } 3668 3669 return updateFlagsForComponent(flags, userId, cookie); 3670 } 3671 3672 @Override 3673 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3674 if (!sUserManager.exists(userId)) return null; 3675 flags = updateFlagsForComponent(flags, userId, component); 3676 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3677 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3678 synchronized (mPackages) { 3679 PackageParser.Activity a = mActivities.mActivities.get(component); 3680 3681 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3682 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3683 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3684 if (ps == null) return null; 3685 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3686 userId); 3687 } 3688 if (mResolveComponentName.equals(component)) { 3689 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3690 new PackageUserState(), userId); 3691 } 3692 } 3693 return null; 3694 } 3695 3696 @Override 3697 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3698 String resolvedType) { 3699 synchronized (mPackages) { 3700 if (component.equals(mResolveComponentName)) { 3701 // The resolver supports EVERYTHING! 3702 return true; 3703 } 3704 PackageParser.Activity a = mActivities.mActivities.get(component); 3705 if (a == null) { 3706 return false; 3707 } 3708 for (int i=0; i<a.intents.size(); i++) { 3709 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3710 intent.getData(), intent.getCategories(), TAG) >= 0) { 3711 return true; 3712 } 3713 } 3714 return false; 3715 } 3716 } 3717 3718 @Override 3719 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3720 if (!sUserManager.exists(userId)) return null; 3721 flags = updateFlagsForComponent(flags, userId, component); 3722 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3723 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3724 synchronized (mPackages) { 3725 PackageParser.Activity a = mReceivers.mActivities.get(component); 3726 if (DEBUG_PACKAGE_INFO) Log.v( 3727 TAG, "getReceiverInfo " + component + ": " + a); 3728 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3729 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3730 if (ps == null) return null; 3731 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3732 userId); 3733 } 3734 } 3735 return null; 3736 } 3737 3738 @Override 3739 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3740 if (!sUserManager.exists(userId)) return null; 3741 flags = updateFlagsForComponent(flags, userId, component); 3742 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3743 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3744 synchronized (mPackages) { 3745 PackageParser.Service s = mServices.mServices.get(component); 3746 if (DEBUG_PACKAGE_INFO) Log.v( 3747 TAG, "getServiceInfo " + component + ": " + s); 3748 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3749 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3750 if (ps == null) return null; 3751 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3752 userId); 3753 } 3754 } 3755 return null; 3756 } 3757 3758 @Override 3759 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3760 if (!sUserManager.exists(userId)) return null; 3761 flags = updateFlagsForComponent(flags, userId, component); 3762 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3763 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3764 synchronized (mPackages) { 3765 PackageParser.Provider p = mProviders.mProviders.get(component); 3766 if (DEBUG_PACKAGE_INFO) Log.v( 3767 TAG, "getProviderInfo " + component + ": " + p); 3768 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3769 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3770 if (ps == null) return null; 3771 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3772 userId); 3773 } 3774 } 3775 return null; 3776 } 3777 3778 @Override 3779 public String[] getSystemSharedLibraryNames() { 3780 Set<String> libSet; 3781 synchronized (mPackages) { 3782 libSet = mSharedLibraries.keySet(); 3783 int size = libSet.size(); 3784 if (size > 0) { 3785 String[] libs = new String[size]; 3786 libSet.toArray(libs); 3787 return libs; 3788 } 3789 } 3790 return null; 3791 } 3792 3793 @Override 3794 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3795 synchronized (mPackages) { 3796 return mServicesSystemSharedLibraryPackageName; 3797 } 3798 } 3799 3800 @Override 3801 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3802 synchronized (mPackages) { 3803 return mSharedSystemSharedLibraryPackageName; 3804 } 3805 } 3806 3807 @Override 3808 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3809 synchronized (mPackages) { 3810 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3811 3812 final FeatureInfo fi = new FeatureInfo(); 3813 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3814 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3815 res.add(fi); 3816 3817 return new ParceledListSlice<>(res); 3818 } 3819 } 3820 3821 @Override 3822 public boolean hasSystemFeature(String name, int version) { 3823 synchronized (mPackages) { 3824 final FeatureInfo feat = mAvailableFeatures.get(name); 3825 if (feat == null) { 3826 return false; 3827 } else { 3828 return feat.version >= version; 3829 } 3830 } 3831 } 3832 3833 @Override 3834 public int checkPermission(String permName, String pkgName, int userId) { 3835 if (!sUserManager.exists(userId)) { 3836 return PackageManager.PERMISSION_DENIED; 3837 } 3838 3839 synchronized (mPackages) { 3840 final PackageParser.Package p = mPackages.get(pkgName); 3841 if (p != null && p.mExtras != null) { 3842 final PackageSetting ps = (PackageSetting) p.mExtras; 3843 final PermissionsState permissionsState = ps.getPermissionsState(); 3844 if (permissionsState.hasPermission(permName, userId)) { 3845 return PackageManager.PERMISSION_GRANTED; 3846 } 3847 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3848 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3849 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3850 return PackageManager.PERMISSION_GRANTED; 3851 } 3852 } 3853 } 3854 3855 return PackageManager.PERMISSION_DENIED; 3856 } 3857 3858 @Override 3859 public int checkUidPermission(String permName, int uid) { 3860 final int userId = UserHandle.getUserId(uid); 3861 3862 if (!sUserManager.exists(userId)) { 3863 return PackageManager.PERMISSION_DENIED; 3864 } 3865 3866 synchronized (mPackages) { 3867 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3868 if (obj != null) { 3869 final SettingBase ps = (SettingBase) obj; 3870 final PermissionsState permissionsState = ps.getPermissionsState(); 3871 if (permissionsState.hasPermission(permName, userId)) { 3872 return PackageManager.PERMISSION_GRANTED; 3873 } 3874 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3875 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3876 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3877 return PackageManager.PERMISSION_GRANTED; 3878 } 3879 } else { 3880 ArraySet<String> perms = mSystemPermissions.get(uid); 3881 if (perms != null) { 3882 if (perms.contains(permName)) { 3883 return PackageManager.PERMISSION_GRANTED; 3884 } 3885 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3886 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3887 return PackageManager.PERMISSION_GRANTED; 3888 } 3889 } 3890 } 3891 } 3892 3893 return PackageManager.PERMISSION_DENIED; 3894 } 3895 3896 @Override 3897 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3898 if (UserHandle.getCallingUserId() != userId) { 3899 mContext.enforceCallingPermission( 3900 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3901 "isPermissionRevokedByPolicy for user " + userId); 3902 } 3903 3904 if (checkPermission(permission, packageName, userId) 3905 == PackageManager.PERMISSION_GRANTED) { 3906 return false; 3907 } 3908 3909 final long identity = Binder.clearCallingIdentity(); 3910 try { 3911 final int flags = getPermissionFlags(permission, packageName, userId); 3912 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3913 } finally { 3914 Binder.restoreCallingIdentity(identity); 3915 } 3916 } 3917 3918 @Override 3919 public String getPermissionControllerPackageName() { 3920 synchronized (mPackages) { 3921 return mRequiredInstallerPackage; 3922 } 3923 } 3924 3925 /** 3926 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3927 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3928 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3929 * @param message the message to log on security exception 3930 */ 3931 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3932 boolean checkShell, String message) { 3933 if (userId < 0) { 3934 throw new IllegalArgumentException("Invalid userId " + userId); 3935 } 3936 if (checkShell) { 3937 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3938 } 3939 if (userId == UserHandle.getUserId(callingUid)) return; 3940 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3941 if (requireFullPermission) { 3942 mContext.enforceCallingOrSelfPermission( 3943 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3944 } else { 3945 try { 3946 mContext.enforceCallingOrSelfPermission( 3947 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3948 } catch (SecurityException se) { 3949 mContext.enforceCallingOrSelfPermission( 3950 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3951 } 3952 } 3953 } 3954 } 3955 3956 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3957 if (callingUid == Process.SHELL_UID) { 3958 if (userHandle >= 0 3959 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3960 throw new SecurityException("Shell does not have permission to access user " 3961 + userHandle); 3962 } else if (userHandle < 0) { 3963 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3964 + Debug.getCallers(3)); 3965 } 3966 } 3967 } 3968 3969 private BasePermission findPermissionTreeLP(String permName) { 3970 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3971 if (permName.startsWith(bp.name) && 3972 permName.length() > bp.name.length() && 3973 permName.charAt(bp.name.length()) == '.') { 3974 return bp; 3975 } 3976 } 3977 return null; 3978 } 3979 3980 private BasePermission checkPermissionTreeLP(String permName) { 3981 if (permName != null) { 3982 BasePermission bp = findPermissionTreeLP(permName); 3983 if (bp != null) { 3984 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3985 return bp; 3986 } 3987 throw new SecurityException("Calling uid " 3988 + Binder.getCallingUid() 3989 + " is not allowed to add to permission tree " 3990 + bp.name + " owned by uid " + bp.uid); 3991 } 3992 } 3993 throw new SecurityException("No permission tree found for " + permName); 3994 } 3995 3996 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3997 if (s1 == null) { 3998 return s2 == null; 3999 } 4000 if (s2 == null) { 4001 return false; 4002 } 4003 if (s1.getClass() != s2.getClass()) { 4004 return false; 4005 } 4006 return s1.equals(s2); 4007 } 4008 4009 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4010 if (pi1.icon != pi2.icon) return false; 4011 if (pi1.logo != pi2.logo) return false; 4012 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4013 if (!compareStrings(pi1.name, pi2.name)) return false; 4014 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4015 // We'll take care of setting this one. 4016 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4017 // These are not currently stored in settings. 4018 //if (!compareStrings(pi1.group, pi2.group)) return false; 4019 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4020 //if (pi1.labelRes != pi2.labelRes) return false; 4021 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4022 return true; 4023 } 4024 4025 int permissionInfoFootprint(PermissionInfo info) { 4026 int size = info.name.length(); 4027 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4028 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4029 return size; 4030 } 4031 4032 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4033 int size = 0; 4034 for (BasePermission perm : mSettings.mPermissions.values()) { 4035 if (perm.uid == tree.uid) { 4036 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4037 } 4038 } 4039 return size; 4040 } 4041 4042 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4043 // We calculate the max size of permissions defined by this uid and throw 4044 // if that plus the size of 'info' would exceed our stated maximum. 4045 if (tree.uid != Process.SYSTEM_UID) { 4046 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4047 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4048 throw new SecurityException("Permission tree size cap exceeded"); 4049 } 4050 } 4051 } 4052 4053 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4054 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4055 throw new SecurityException("Label must be specified in permission"); 4056 } 4057 BasePermission tree = checkPermissionTreeLP(info.name); 4058 BasePermission bp = mSettings.mPermissions.get(info.name); 4059 boolean added = bp == null; 4060 boolean changed = true; 4061 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4062 if (added) { 4063 enforcePermissionCapLocked(info, tree); 4064 bp = new BasePermission(info.name, tree.sourcePackage, 4065 BasePermission.TYPE_DYNAMIC); 4066 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4067 throw new SecurityException( 4068 "Not allowed to modify non-dynamic permission " 4069 + info.name); 4070 } else { 4071 if (bp.protectionLevel == fixedLevel 4072 && bp.perm.owner.equals(tree.perm.owner) 4073 && bp.uid == tree.uid 4074 && comparePermissionInfos(bp.perm.info, info)) { 4075 changed = false; 4076 } 4077 } 4078 bp.protectionLevel = fixedLevel; 4079 info = new PermissionInfo(info); 4080 info.protectionLevel = fixedLevel; 4081 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4082 bp.perm.info.packageName = tree.perm.info.packageName; 4083 bp.uid = tree.uid; 4084 if (added) { 4085 mSettings.mPermissions.put(info.name, bp); 4086 } 4087 if (changed) { 4088 if (!async) { 4089 mSettings.writeLPr(); 4090 } else { 4091 scheduleWriteSettingsLocked(); 4092 } 4093 } 4094 return added; 4095 } 4096 4097 @Override 4098 public boolean addPermission(PermissionInfo info) { 4099 synchronized (mPackages) { 4100 return addPermissionLocked(info, false); 4101 } 4102 } 4103 4104 @Override 4105 public boolean addPermissionAsync(PermissionInfo info) { 4106 synchronized (mPackages) { 4107 return addPermissionLocked(info, true); 4108 } 4109 } 4110 4111 @Override 4112 public void removePermission(String name) { 4113 synchronized (mPackages) { 4114 checkPermissionTreeLP(name); 4115 BasePermission bp = mSettings.mPermissions.get(name); 4116 if (bp != null) { 4117 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4118 throw new SecurityException( 4119 "Not allowed to modify non-dynamic permission " 4120 + name); 4121 } 4122 mSettings.mPermissions.remove(name); 4123 mSettings.writeLPr(); 4124 } 4125 } 4126 } 4127 4128 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4129 BasePermission bp) { 4130 int index = pkg.requestedPermissions.indexOf(bp.name); 4131 if (index == -1) { 4132 throw new SecurityException("Package " + pkg.packageName 4133 + " has not requested permission " + bp.name); 4134 } 4135 if (!bp.isRuntime() && !bp.isDevelopment()) { 4136 throw new SecurityException("Permission " + bp.name 4137 + " is not a changeable permission type"); 4138 } 4139 } 4140 4141 @Override 4142 public void grantRuntimePermission(String packageName, String name, final int userId) { 4143 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4144 } 4145 4146 private void grantRuntimePermission(String packageName, String name, final int userId, 4147 boolean overridePolicy) { 4148 if (!sUserManager.exists(userId)) { 4149 Log.e(TAG, "No such user:" + userId); 4150 return; 4151 } 4152 4153 mContext.enforceCallingOrSelfPermission( 4154 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4155 "grantRuntimePermission"); 4156 4157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4158 true /* requireFullPermission */, true /* checkShell */, 4159 "grantRuntimePermission"); 4160 4161 final int uid; 4162 final SettingBase sb; 4163 4164 synchronized (mPackages) { 4165 final PackageParser.Package pkg = mPackages.get(packageName); 4166 if (pkg == null) { 4167 throw new IllegalArgumentException("Unknown package: " + packageName); 4168 } 4169 4170 final BasePermission bp = mSettings.mPermissions.get(name); 4171 if (bp == null) { 4172 throw new IllegalArgumentException("Unknown permission: " + name); 4173 } 4174 4175 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4176 4177 // If a permission review is required for legacy apps we represent 4178 // their permissions as always granted runtime ones since we need 4179 // to keep the review required permission flag per user while an 4180 // install permission's state is shared across all users. 4181 if (mPermissionReviewRequired 4182 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4183 && bp.isRuntime()) { 4184 return; 4185 } 4186 4187 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4188 sb = (SettingBase) pkg.mExtras; 4189 if (sb == null) { 4190 throw new IllegalArgumentException("Unknown package: " + packageName); 4191 } 4192 4193 final PermissionsState permissionsState = sb.getPermissionsState(); 4194 4195 final int flags = permissionsState.getPermissionFlags(name, userId); 4196 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4197 throw new SecurityException("Cannot grant system fixed permission " 4198 + name + " for package " + packageName); 4199 } 4200 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4201 throw new SecurityException("Cannot grant policy fixed permission " 4202 + name + " for package " + packageName); 4203 } 4204 4205 if (bp.isDevelopment()) { 4206 // Development permissions must be handled specially, since they are not 4207 // normal runtime permissions. For now they apply to all users. 4208 if (permissionsState.grantInstallPermission(bp) != 4209 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4210 scheduleWriteSettingsLocked(); 4211 } 4212 return; 4213 } 4214 4215 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4216 throw new SecurityException("Cannot grant non-ephemeral permission" 4217 + name + " for package " + packageName); 4218 } 4219 4220 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4221 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4222 return; 4223 } 4224 4225 final int result = permissionsState.grantRuntimePermission(bp, userId); 4226 switch (result) { 4227 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4228 return; 4229 } 4230 4231 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4232 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4233 mHandler.post(new Runnable() { 4234 @Override 4235 public void run() { 4236 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4237 } 4238 }); 4239 } 4240 break; 4241 } 4242 4243 if (bp.isRuntime()) { 4244 logPermissionGranted(mContext, name, packageName); 4245 } 4246 4247 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4248 4249 // Not critical if that is lost - app has to request again. 4250 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4251 } 4252 4253 // Only need to do this if user is initialized. Otherwise it's a new user 4254 // and there are no processes running as the user yet and there's no need 4255 // to make an expensive call to remount processes for the changed permissions. 4256 if (READ_EXTERNAL_STORAGE.equals(name) 4257 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4258 final long token = Binder.clearCallingIdentity(); 4259 try { 4260 if (sUserManager.isInitialized(userId)) { 4261 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4262 StorageManagerInternal.class); 4263 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4264 } 4265 } finally { 4266 Binder.restoreCallingIdentity(token); 4267 } 4268 } 4269 } 4270 4271 @Override 4272 public void revokeRuntimePermission(String packageName, String name, int userId) { 4273 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4274 } 4275 4276 private void revokeRuntimePermission(String packageName, String name, int userId, 4277 boolean overridePolicy) { 4278 if (!sUserManager.exists(userId)) { 4279 Log.e(TAG, "No such user:" + userId); 4280 return; 4281 } 4282 4283 mContext.enforceCallingOrSelfPermission( 4284 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4285 "revokeRuntimePermission"); 4286 4287 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4288 true /* requireFullPermission */, true /* checkShell */, 4289 "revokeRuntimePermission"); 4290 4291 final int appId; 4292 4293 synchronized (mPackages) { 4294 final PackageParser.Package pkg = mPackages.get(packageName); 4295 if (pkg == null) { 4296 throw new IllegalArgumentException("Unknown package: " + packageName); 4297 } 4298 4299 final BasePermission bp = mSettings.mPermissions.get(name); 4300 if (bp == null) { 4301 throw new IllegalArgumentException("Unknown permission: " + name); 4302 } 4303 4304 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4305 4306 // If a permission review is required for legacy apps we represent 4307 // their permissions as always granted runtime ones since we need 4308 // to keep the review required permission flag per user while an 4309 // install permission's state is shared across all users. 4310 if (mPermissionReviewRequired 4311 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4312 && bp.isRuntime()) { 4313 return; 4314 } 4315 4316 SettingBase sb = (SettingBase) pkg.mExtras; 4317 if (sb == null) { 4318 throw new IllegalArgumentException("Unknown package: " + packageName); 4319 } 4320 4321 final PermissionsState permissionsState = sb.getPermissionsState(); 4322 4323 final int flags = permissionsState.getPermissionFlags(name, userId); 4324 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4325 throw new SecurityException("Cannot revoke system fixed permission " 4326 + name + " for package " + packageName); 4327 } 4328 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4329 throw new SecurityException("Cannot revoke policy fixed permission " 4330 + name + " for package " + packageName); 4331 } 4332 4333 if (bp.isDevelopment()) { 4334 // Development permissions must be handled specially, since they are not 4335 // normal runtime permissions. For now they apply to all users. 4336 if (permissionsState.revokeInstallPermission(bp) != 4337 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4338 scheduleWriteSettingsLocked(); 4339 } 4340 return; 4341 } 4342 4343 if (permissionsState.revokeRuntimePermission(bp, userId) == 4344 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4345 return; 4346 } 4347 4348 if (bp.isRuntime()) { 4349 logPermissionRevoked(mContext, name, packageName); 4350 } 4351 4352 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4353 4354 // Critical, after this call app should never have the permission. 4355 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4356 4357 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4358 } 4359 4360 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4361 } 4362 4363 /** 4364 * Get the first event id for the permission. 4365 * 4366 * <p>There are four events for each permission: <ul> 4367 * <li>Request permission: first id + 0</li> 4368 * <li>Grant permission: first id + 1</li> 4369 * <li>Request for permission denied: first id + 2</li> 4370 * <li>Revoke permission: first id + 3</li> 4371 * </ul></p> 4372 * 4373 * @param name name of the permission 4374 * 4375 * @return The first event id for the permission 4376 */ 4377 private static int getBaseEventId(@NonNull String name) { 4378 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4379 4380 if (eventIdIndex == -1) { 4381 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4382 || "user".equals(Build.TYPE)) { 4383 Log.i(TAG, "Unknown permission " + name); 4384 4385 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4386 } else { 4387 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4388 // 4389 // Also update 4390 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4391 // - metrics_constants.proto 4392 throw new IllegalStateException("Unknown permission " + name); 4393 } 4394 } 4395 4396 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4397 } 4398 4399 /** 4400 * Log that a permission was revoked. 4401 * 4402 * @param context Context of the caller 4403 * @param name name of the permission 4404 * @param packageName package permission if for 4405 */ 4406 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4407 @NonNull String packageName) { 4408 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4409 } 4410 4411 /** 4412 * Log that a permission request was granted. 4413 * 4414 * @param context Context of the caller 4415 * @param name name of the permission 4416 * @param packageName package permission if for 4417 */ 4418 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4419 @NonNull String packageName) { 4420 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4421 } 4422 4423 @Override 4424 public void resetRuntimePermissions() { 4425 mContext.enforceCallingOrSelfPermission( 4426 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4427 "revokeRuntimePermission"); 4428 4429 int callingUid = Binder.getCallingUid(); 4430 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4431 mContext.enforceCallingOrSelfPermission( 4432 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4433 "resetRuntimePermissions"); 4434 } 4435 4436 synchronized (mPackages) { 4437 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4438 for (int userId : UserManagerService.getInstance().getUserIds()) { 4439 final int packageCount = mPackages.size(); 4440 for (int i = 0; i < packageCount; i++) { 4441 PackageParser.Package pkg = mPackages.valueAt(i); 4442 if (!(pkg.mExtras instanceof PackageSetting)) { 4443 continue; 4444 } 4445 PackageSetting ps = (PackageSetting) pkg.mExtras; 4446 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4447 } 4448 } 4449 } 4450 } 4451 4452 @Override 4453 public int getPermissionFlags(String name, String packageName, int userId) { 4454 if (!sUserManager.exists(userId)) { 4455 return 0; 4456 } 4457 4458 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4459 4460 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4461 true /* requireFullPermission */, false /* checkShell */, 4462 "getPermissionFlags"); 4463 4464 synchronized (mPackages) { 4465 final PackageParser.Package pkg = mPackages.get(packageName); 4466 if (pkg == null) { 4467 return 0; 4468 } 4469 4470 final BasePermission bp = mSettings.mPermissions.get(name); 4471 if (bp == null) { 4472 return 0; 4473 } 4474 4475 SettingBase sb = (SettingBase) pkg.mExtras; 4476 if (sb == null) { 4477 return 0; 4478 } 4479 4480 PermissionsState permissionsState = sb.getPermissionsState(); 4481 return permissionsState.getPermissionFlags(name, userId); 4482 } 4483 } 4484 4485 @Override 4486 public void updatePermissionFlags(String name, String packageName, int flagMask, 4487 int flagValues, int userId) { 4488 if (!sUserManager.exists(userId)) { 4489 return; 4490 } 4491 4492 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4493 4494 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4495 true /* requireFullPermission */, true /* checkShell */, 4496 "updatePermissionFlags"); 4497 4498 // Only the system can change these flags and nothing else. 4499 if (getCallingUid() != Process.SYSTEM_UID) { 4500 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4501 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4502 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4503 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4504 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4505 } 4506 4507 synchronized (mPackages) { 4508 final PackageParser.Package pkg = mPackages.get(packageName); 4509 if (pkg == null) { 4510 throw new IllegalArgumentException("Unknown package: " + packageName); 4511 } 4512 4513 final BasePermission bp = mSettings.mPermissions.get(name); 4514 if (bp == null) { 4515 throw new IllegalArgumentException("Unknown permission: " + name); 4516 } 4517 4518 SettingBase sb = (SettingBase) pkg.mExtras; 4519 if (sb == null) { 4520 throw new IllegalArgumentException("Unknown package: " + packageName); 4521 } 4522 4523 PermissionsState permissionsState = sb.getPermissionsState(); 4524 4525 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4526 4527 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4528 // Install and runtime permissions are stored in different places, 4529 // so figure out what permission changed and persist the change. 4530 if (permissionsState.getInstallPermissionState(name) != null) { 4531 scheduleWriteSettingsLocked(); 4532 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4533 || hadState) { 4534 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4535 } 4536 } 4537 } 4538 } 4539 4540 /** 4541 * Update the permission flags for all packages and runtime permissions of a user in order 4542 * to allow device or profile owner to remove POLICY_FIXED. 4543 */ 4544 @Override 4545 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4546 if (!sUserManager.exists(userId)) { 4547 return; 4548 } 4549 4550 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4551 4552 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4553 true /* requireFullPermission */, true /* checkShell */, 4554 "updatePermissionFlagsForAllApps"); 4555 4556 // Only the system can change system fixed flags. 4557 if (getCallingUid() != Process.SYSTEM_UID) { 4558 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4559 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4560 } 4561 4562 synchronized (mPackages) { 4563 boolean changed = false; 4564 final int packageCount = mPackages.size(); 4565 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4566 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4567 SettingBase sb = (SettingBase) pkg.mExtras; 4568 if (sb == null) { 4569 continue; 4570 } 4571 PermissionsState permissionsState = sb.getPermissionsState(); 4572 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4573 userId, flagMask, flagValues); 4574 } 4575 if (changed) { 4576 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4577 } 4578 } 4579 } 4580 4581 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4582 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4583 != PackageManager.PERMISSION_GRANTED 4584 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4585 != PackageManager.PERMISSION_GRANTED) { 4586 throw new SecurityException(message + " requires " 4587 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4588 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4589 } 4590 } 4591 4592 @Override 4593 public boolean shouldShowRequestPermissionRationale(String permissionName, 4594 String packageName, int userId) { 4595 if (UserHandle.getCallingUserId() != userId) { 4596 mContext.enforceCallingPermission( 4597 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4598 "canShowRequestPermissionRationale for user " + userId); 4599 } 4600 4601 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4602 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4603 return false; 4604 } 4605 4606 if (checkPermission(permissionName, packageName, userId) 4607 == PackageManager.PERMISSION_GRANTED) { 4608 return false; 4609 } 4610 4611 final int flags; 4612 4613 final long identity = Binder.clearCallingIdentity(); 4614 try { 4615 flags = getPermissionFlags(permissionName, 4616 packageName, userId); 4617 } finally { 4618 Binder.restoreCallingIdentity(identity); 4619 } 4620 4621 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4622 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4623 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4624 4625 if ((flags & fixedFlags) != 0) { 4626 return false; 4627 } 4628 4629 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4630 } 4631 4632 @Override 4633 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4634 mContext.enforceCallingOrSelfPermission( 4635 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4636 "addOnPermissionsChangeListener"); 4637 4638 synchronized (mPackages) { 4639 mOnPermissionChangeListeners.addListenerLocked(listener); 4640 } 4641 } 4642 4643 @Override 4644 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4645 synchronized (mPackages) { 4646 mOnPermissionChangeListeners.removeListenerLocked(listener); 4647 } 4648 } 4649 4650 @Override 4651 public boolean isProtectedBroadcast(String actionName) { 4652 synchronized (mPackages) { 4653 if (mProtectedBroadcasts.contains(actionName)) { 4654 return true; 4655 } else if (actionName != null) { 4656 // TODO: remove these terrible hacks 4657 if (actionName.startsWith("android.net.netmon.lingerExpired") 4658 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4659 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4660 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4661 return true; 4662 } 4663 } 4664 } 4665 return false; 4666 } 4667 4668 @Override 4669 public int checkSignatures(String pkg1, String pkg2) { 4670 synchronized (mPackages) { 4671 final PackageParser.Package p1 = mPackages.get(pkg1); 4672 final PackageParser.Package p2 = mPackages.get(pkg2); 4673 if (p1 == null || p1.mExtras == null 4674 || p2 == null || p2.mExtras == null) { 4675 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4676 } 4677 return compareSignatures(p1.mSignatures, p2.mSignatures); 4678 } 4679 } 4680 4681 @Override 4682 public int checkUidSignatures(int uid1, int uid2) { 4683 // Map to base uids. 4684 uid1 = UserHandle.getAppId(uid1); 4685 uid2 = UserHandle.getAppId(uid2); 4686 // reader 4687 synchronized (mPackages) { 4688 Signature[] s1; 4689 Signature[] s2; 4690 Object obj = mSettings.getUserIdLPr(uid1); 4691 if (obj != null) { 4692 if (obj instanceof SharedUserSetting) { 4693 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4694 } else if (obj instanceof PackageSetting) { 4695 s1 = ((PackageSetting)obj).signatures.mSignatures; 4696 } else { 4697 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4698 } 4699 } else { 4700 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4701 } 4702 obj = mSettings.getUserIdLPr(uid2); 4703 if (obj != null) { 4704 if (obj instanceof SharedUserSetting) { 4705 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4706 } else if (obj instanceof PackageSetting) { 4707 s2 = ((PackageSetting)obj).signatures.mSignatures; 4708 } else { 4709 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4710 } 4711 } else { 4712 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4713 } 4714 return compareSignatures(s1, s2); 4715 } 4716 } 4717 4718 /** 4719 * This method should typically only be used when granting or revoking 4720 * permissions, since the app may immediately restart after this call. 4721 * <p> 4722 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4723 * guard your work against the app being relaunched. 4724 */ 4725 private void killUid(int appId, int userId, String reason) { 4726 final long identity = Binder.clearCallingIdentity(); 4727 try { 4728 IActivityManager am = ActivityManager.getService(); 4729 if (am != null) { 4730 try { 4731 am.killUid(appId, userId, reason); 4732 } catch (RemoteException e) { 4733 /* ignore - same process */ 4734 } 4735 } 4736 } finally { 4737 Binder.restoreCallingIdentity(identity); 4738 } 4739 } 4740 4741 /** 4742 * Compares two sets of signatures. Returns: 4743 * <br /> 4744 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4745 * <br /> 4746 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4747 * <br /> 4748 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4749 * <br /> 4750 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4751 * <br /> 4752 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4753 */ 4754 static int compareSignatures(Signature[] s1, Signature[] s2) { 4755 if (s1 == null) { 4756 return s2 == null 4757 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4758 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4759 } 4760 4761 if (s2 == null) { 4762 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4763 } 4764 4765 if (s1.length != s2.length) { 4766 return PackageManager.SIGNATURE_NO_MATCH; 4767 } 4768 4769 // Since both signature sets are of size 1, we can compare without HashSets. 4770 if (s1.length == 1) { 4771 return s1[0].equals(s2[0]) ? 4772 PackageManager.SIGNATURE_MATCH : 4773 PackageManager.SIGNATURE_NO_MATCH; 4774 } 4775 4776 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4777 for (Signature sig : s1) { 4778 set1.add(sig); 4779 } 4780 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4781 for (Signature sig : s2) { 4782 set2.add(sig); 4783 } 4784 // Make sure s2 contains all signatures in s1. 4785 if (set1.equals(set2)) { 4786 return PackageManager.SIGNATURE_MATCH; 4787 } 4788 return PackageManager.SIGNATURE_NO_MATCH; 4789 } 4790 4791 /** 4792 * If the database version for this type of package (internal storage or 4793 * external storage) is less than the version where package signatures 4794 * were updated, return true. 4795 */ 4796 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4797 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4798 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4799 } 4800 4801 /** 4802 * Used for backward compatibility to make sure any packages with 4803 * certificate chains get upgraded to the new style. {@code existingSigs} 4804 * will be in the old format (since they were stored on disk from before the 4805 * system upgrade) and {@code scannedSigs} will be in the newer format. 4806 */ 4807 private int compareSignaturesCompat(PackageSignatures existingSigs, 4808 PackageParser.Package scannedPkg) { 4809 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4810 return PackageManager.SIGNATURE_NO_MATCH; 4811 } 4812 4813 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4814 for (Signature sig : existingSigs.mSignatures) { 4815 existingSet.add(sig); 4816 } 4817 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4818 for (Signature sig : scannedPkg.mSignatures) { 4819 try { 4820 Signature[] chainSignatures = sig.getChainSignatures(); 4821 for (Signature chainSig : chainSignatures) { 4822 scannedCompatSet.add(chainSig); 4823 } 4824 } catch (CertificateEncodingException e) { 4825 scannedCompatSet.add(sig); 4826 } 4827 } 4828 /* 4829 * Make sure the expanded scanned set contains all signatures in the 4830 * existing one. 4831 */ 4832 if (scannedCompatSet.equals(existingSet)) { 4833 // Migrate the old signatures to the new scheme. 4834 existingSigs.assignSignatures(scannedPkg.mSignatures); 4835 // The new KeySets will be re-added later in the scanning process. 4836 synchronized (mPackages) { 4837 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4838 } 4839 return PackageManager.SIGNATURE_MATCH; 4840 } 4841 return PackageManager.SIGNATURE_NO_MATCH; 4842 } 4843 4844 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4845 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4846 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4847 } 4848 4849 private int compareSignaturesRecover(PackageSignatures existingSigs, 4850 PackageParser.Package scannedPkg) { 4851 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4852 return PackageManager.SIGNATURE_NO_MATCH; 4853 } 4854 4855 String msg = null; 4856 try { 4857 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4858 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4859 + scannedPkg.packageName); 4860 return PackageManager.SIGNATURE_MATCH; 4861 } 4862 } catch (CertificateException e) { 4863 msg = e.getMessage(); 4864 } 4865 4866 logCriticalInfo(Log.INFO, 4867 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4868 return PackageManager.SIGNATURE_NO_MATCH; 4869 } 4870 4871 @Override 4872 public List<String> getAllPackages() { 4873 synchronized (mPackages) { 4874 return new ArrayList<String>(mPackages.keySet()); 4875 } 4876 } 4877 4878 @Override 4879 public String[] getPackagesForUid(int uid) { 4880 final int userId = UserHandle.getUserId(uid); 4881 uid = UserHandle.getAppId(uid); 4882 // reader 4883 synchronized (mPackages) { 4884 Object obj = mSettings.getUserIdLPr(uid); 4885 if (obj instanceof SharedUserSetting) { 4886 final SharedUserSetting sus = (SharedUserSetting) obj; 4887 final int N = sus.packages.size(); 4888 String[] res = new String[N]; 4889 final Iterator<PackageSetting> it = sus.packages.iterator(); 4890 int i = 0; 4891 while (it.hasNext()) { 4892 PackageSetting ps = it.next(); 4893 if (ps.getInstalled(userId)) { 4894 res[i++] = ps.name; 4895 } else { 4896 res = ArrayUtils.removeElement(String.class, res, res[i]); 4897 } 4898 } 4899 return res; 4900 } else if (obj instanceof PackageSetting) { 4901 final PackageSetting ps = (PackageSetting) obj; 4902 return new String[] { ps.name }; 4903 } 4904 } 4905 return null; 4906 } 4907 4908 @Override 4909 public String getNameForUid(int uid) { 4910 // reader 4911 synchronized (mPackages) { 4912 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4913 if (obj instanceof SharedUserSetting) { 4914 final SharedUserSetting sus = (SharedUserSetting) obj; 4915 return sus.name + ":" + sus.userId; 4916 } else if (obj instanceof PackageSetting) { 4917 final PackageSetting ps = (PackageSetting) obj; 4918 return ps.name; 4919 } 4920 } 4921 return null; 4922 } 4923 4924 @Override 4925 public int getUidForSharedUser(String sharedUserName) { 4926 if(sharedUserName == null) { 4927 return -1; 4928 } 4929 // reader 4930 synchronized (mPackages) { 4931 SharedUserSetting suid; 4932 try { 4933 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4934 if (suid != null) { 4935 return suid.userId; 4936 } 4937 } catch (PackageManagerException ignore) { 4938 // can't happen, but, still need to catch it 4939 } 4940 return -1; 4941 } 4942 } 4943 4944 @Override 4945 public int getFlagsForUid(int uid) { 4946 synchronized (mPackages) { 4947 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4948 if (obj instanceof SharedUserSetting) { 4949 final SharedUserSetting sus = (SharedUserSetting) obj; 4950 return sus.pkgFlags; 4951 } else if (obj instanceof PackageSetting) { 4952 final PackageSetting ps = (PackageSetting) obj; 4953 return ps.pkgFlags; 4954 } 4955 } 4956 return 0; 4957 } 4958 4959 @Override 4960 public int getPrivateFlagsForUid(int uid) { 4961 synchronized (mPackages) { 4962 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4963 if (obj instanceof SharedUserSetting) { 4964 final SharedUserSetting sus = (SharedUserSetting) obj; 4965 return sus.pkgPrivateFlags; 4966 } else if (obj instanceof PackageSetting) { 4967 final PackageSetting ps = (PackageSetting) obj; 4968 return ps.pkgPrivateFlags; 4969 } 4970 } 4971 return 0; 4972 } 4973 4974 @Override 4975 public boolean isUidPrivileged(int uid) { 4976 uid = UserHandle.getAppId(uid); 4977 // reader 4978 synchronized (mPackages) { 4979 Object obj = mSettings.getUserIdLPr(uid); 4980 if (obj instanceof SharedUserSetting) { 4981 final SharedUserSetting sus = (SharedUserSetting) obj; 4982 final Iterator<PackageSetting> it = sus.packages.iterator(); 4983 while (it.hasNext()) { 4984 if (it.next().isPrivileged()) { 4985 return true; 4986 } 4987 } 4988 } else if (obj instanceof PackageSetting) { 4989 final PackageSetting ps = (PackageSetting) obj; 4990 return ps.isPrivileged(); 4991 } 4992 } 4993 return false; 4994 } 4995 4996 @Override 4997 public String[] getAppOpPermissionPackages(String permissionName) { 4998 synchronized (mPackages) { 4999 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5000 if (pkgs == null) { 5001 return null; 5002 } 5003 return pkgs.toArray(new String[pkgs.size()]); 5004 } 5005 } 5006 5007 @Override 5008 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5009 int flags, int userId) { 5010 try { 5011 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5012 5013 if (!sUserManager.exists(userId)) return null; 5014 flags = updateFlagsForResolve(flags, userId, intent); 5015 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5016 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5017 5018 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5019 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5020 flags, userId); 5021 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5022 5023 final ResolveInfo bestChoice = 5024 chooseBestActivity(intent, resolvedType, flags, query, userId); 5025 return bestChoice; 5026 } finally { 5027 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5028 } 5029 } 5030 5031 @Override 5032 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5033 IntentFilter filter, int match, ComponentName activity) { 5034 final int userId = UserHandle.getCallingUserId(); 5035 if (DEBUG_PREFERRED) { 5036 Log.v(TAG, "setLastChosenActivity intent=" + intent 5037 + " resolvedType=" + resolvedType 5038 + " flags=" + flags 5039 + " filter=" + filter 5040 + " match=" + match 5041 + " activity=" + activity); 5042 filter.dump(new PrintStreamPrinter(System.out), " "); 5043 } 5044 intent.setComponent(null); 5045 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5046 userId); 5047 // Find any earlier preferred or last chosen entries and nuke them 5048 findPreferredActivity(intent, resolvedType, 5049 flags, query, 0, false, true, false, userId); 5050 // Add the new activity as the last chosen for this filter 5051 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5052 "Setting last chosen"); 5053 } 5054 5055 @Override 5056 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5057 final int userId = UserHandle.getCallingUserId(); 5058 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5059 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5060 userId); 5061 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5062 false, false, false, userId); 5063 } 5064 5065 private boolean isEphemeralDisabled() { 5066 // ephemeral apps have been disabled across the board 5067 if (DISABLE_EPHEMERAL_APPS) { 5068 return true; 5069 } 5070 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5071 if (!mSystemReady) { 5072 return true; 5073 } 5074 // we can't get a content resolver until the system is ready; these checks must happen last 5075 final ContentResolver resolver = mContext.getContentResolver(); 5076 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5077 return true; 5078 } 5079 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5080 } 5081 5082 private boolean isEphemeralAllowed( 5083 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5084 boolean skipPackageCheck) { 5085 // Short circuit and return early if possible. 5086 if (isEphemeralDisabled()) { 5087 return false; 5088 } 5089 final int callingUser = UserHandle.getCallingUserId(); 5090 if (callingUser != UserHandle.USER_SYSTEM) { 5091 return false; 5092 } 5093 if (mEphemeralResolverConnection == null) { 5094 return false; 5095 } 5096 if (mEphemeralInstallerComponent == null) { 5097 return false; 5098 } 5099 if (intent.getComponent() != null) { 5100 return false; 5101 } 5102 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5103 return false; 5104 } 5105 if (!skipPackageCheck && intent.getPackage() != null) { 5106 return false; 5107 } 5108 final boolean isWebUri = hasWebURI(intent); 5109 if (!isWebUri || intent.getData().getHost() == null) { 5110 return false; 5111 } 5112 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5113 synchronized (mPackages) { 5114 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5115 for (int n = 0; n < count; n++) { 5116 ResolveInfo info = resolvedActivities.get(n); 5117 String packageName = info.activityInfo.packageName; 5118 PackageSetting ps = mSettings.mPackages.get(packageName); 5119 if (ps != null) { 5120 // Try to get the status from User settings first 5121 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5122 int status = (int) (packedStatus >> 32); 5123 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5124 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5125 if (DEBUG_EPHEMERAL) { 5126 Slog.v(TAG, "DENY ephemeral apps;" 5127 + " pkg: " + packageName + ", status: " + status); 5128 } 5129 return false; 5130 } 5131 } 5132 } 5133 } 5134 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5135 return true; 5136 } 5137 5138 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5139 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5140 int userId) { 5141 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5142 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5143 callingPackage, userId)); 5144 mHandler.sendMessage(msg); 5145 } 5146 5147 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5148 int flags, List<ResolveInfo> query, int userId) { 5149 if (query != null) { 5150 final int N = query.size(); 5151 if (N == 1) { 5152 return query.get(0); 5153 } else if (N > 1) { 5154 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5155 // If there is more than one activity with the same priority, 5156 // then let the user decide between them. 5157 ResolveInfo r0 = query.get(0); 5158 ResolveInfo r1 = query.get(1); 5159 if (DEBUG_INTENT_MATCHING || debug) { 5160 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5161 + r1.activityInfo.name + "=" + r1.priority); 5162 } 5163 // If the first activity has a higher priority, or a different 5164 // default, then it is always desirable to pick it. 5165 if (r0.priority != r1.priority 5166 || r0.preferredOrder != r1.preferredOrder 5167 || r0.isDefault != r1.isDefault) { 5168 return query.get(0); 5169 } 5170 // If we have saved a preference for a preferred activity for 5171 // this Intent, use that. 5172 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5173 flags, query, r0.priority, true, false, debug, userId); 5174 if (ri != null) { 5175 return ri; 5176 } 5177 ri = new ResolveInfo(mResolveInfo); 5178 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5179 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5180 // If all of the options come from the same package, show the application's 5181 // label and icon instead of the generic resolver's. 5182 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5183 // and then throw away the ResolveInfo itself, meaning that the caller loses 5184 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5185 // a fallback for this case; we only set the target package's resources on 5186 // the ResolveInfo, not the ActivityInfo. 5187 final String intentPackage = intent.getPackage(); 5188 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5189 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5190 ri.resolvePackageName = intentPackage; 5191 if (userNeedsBadging(userId)) { 5192 ri.noResourceId = true; 5193 } else { 5194 ri.icon = appi.icon; 5195 } 5196 ri.iconResourceId = appi.icon; 5197 ri.labelRes = appi.labelRes; 5198 } 5199 ri.activityInfo.applicationInfo = new ApplicationInfo( 5200 ri.activityInfo.applicationInfo); 5201 if (userId != 0) { 5202 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5203 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5204 } 5205 // Make sure that the resolver is displayable in car mode 5206 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5207 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5208 return ri; 5209 } 5210 } 5211 return null; 5212 } 5213 5214 /** 5215 * Return true if the given list is not empty and all of its contents have 5216 * an activityInfo with the given package name. 5217 */ 5218 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5219 if (ArrayUtils.isEmpty(list)) { 5220 return false; 5221 } 5222 for (int i = 0, N = list.size(); i < N; i++) { 5223 final ResolveInfo ri = list.get(i); 5224 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5225 if (ai == null || !packageName.equals(ai.packageName)) { 5226 return false; 5227 } 5228 } 5229 return true; 5230 } 5231 5232 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5233 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5234 final int N = query.size(); 5235 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5236 .get(userId); 5237 // Get the list of persistent preferred activities that handle the intent 5238 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5239 List<PersistentPreferredActivity> pprefs = ppir != null 5240 ? ppir.queryIntent(intent, resolvedType, 5241 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5242 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5243 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5244 : null; 5245 if (pprefs != null && pprefs.size() > 0) { 5246 final int M = pprefs.size(); 5247 for (int i=0; i<M; i++) { 5248 final PersistentPreferredActivity ppa = pprefs.get(i); 5249 if (DEBUG_PREFERRED || debug) { 5250 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5251 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5252 + "\n component=" + ppa.mComponent); 5253 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5254 } 5255 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5256 flags | MATCH_DISABLED_COMPONENTS, userId); 5257 if (DEBUG_PREFERRED || debug) { 5258 Slog.v(TAG, "Found persistent preferred activity:"); 5259 if (ai != null) { 5260 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5261 } else { 5262 Slog.v(TAG, " null"); 5263 } 5264 } 5265 if (ai == null) { 5266 // This previously registered persistent preferred activity 5267 // component is no longer known. Ignore it and do NOT remove it. 5268 continue; 5269 } 5270 for (int j=0; j<N; j++) { 5271 final ResolveInfo ri = query.get(j); 5272 if (!ri.activityInfo.applicationInfo.packageName 5273 .equals(ai.applicationInfo.packageName)) { 5274 continue; 5275 } 5276 if (!ri.activityInfo.name.equals(ai.name)) { 5277 continue; 5278 } 5279 // Found a persistent preference that can handle the intent. 5280 if (DEBUG_PREFERRED || debug) { 5281 Slog.v(TAG, "Returning persistent preferred activity: " + 5282 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5283 } 5284 return ri; 5285 } 5286 } 5287 } 5288 return null; 5289 } 5290 5291 // TODO: handle preferred activities missing while user has amnesia 5292 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5293 List<ResolveInfo> query, int priority, boolean always, 5294 boolean removeMatches, boolean debug, int userId) { 5295 if (!sUserManager.exists(userId)) return null; 5296 flags = updateFlagsForResolve(flags, userId, intent); 5297 // writer 5298 synchronized (mPackages) { 5299 if (intent.getSelector() != null) { 5300 intent = intent.getSelector(); 5301 } 5302 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5303 5304 // Try to find a matching persistent preferred activity. 5305 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5306 debug, userId); 5307 5308 // If a persistent preferred activity matched, use it. 5309 if (pri != null) { 5310 return pri; 5311 } 5312 5313 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5314 // Get the list of preferred activities that handle the intent 5315 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5316 List<PreferredActivity> prefs = pir != null 5317 ? pir.queryIntent(intent, resolvedType, 5318 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5319 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5320 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5321 : null; 5322 if (prefs != null && prefs.size() > 0) { 5323 boolean changed = false; 5324 try { 5325 // First figure out how good the original match set is. 5326 // We will only allow preferred activities that came 5327 // from the same match quality. 5328 int match = 0; 5329 5330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5331 5332 final int N = query.size(); 5333 for (int j=0; j<N; j++) { 5334 final ResolveInfo ri = query.get(j); 5335 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5336 + ": 0x" + Integer.toHexString(match)); 5337 if (ri.match > match) { 5338 match = ri.match; 5339 } 5340 } 5341 5342 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5343 + Integer.toHexString(match)); 5344 5345 match &= IntentFilter.MATCH_CATEGORY_MASK; 5346 final int M = prefs.size(); 5347 for (int i=0; i<M; i++) { 5348 final PreferredActivity pa = prefs.get(i); 5349 if (DEBUG_PREFERRED || debug) { 5350 Slog.v(TAG, "Checking PreferredActivity ds=" 5351 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5352 + "\n component=" + pa.mPref.mComponent); 5353 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5354 } 5355 if (pa.mPref.mMatch != match) { 5356 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5357 + Integer.toHexString(pa.mPref.mMatch)); 5358 continue; 5359 } 5360 // If it's not an "always" type preferred activity and that's what we're 5361 // looking for, skip it. 5362 if (always && !pa.mPref.mAlways) { 5363 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5364 continue; 5365 } 5366 final ActivityInfo ai = getActivityInfo( 5367 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5368 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5369 userId); 5370 if (DEBUG_PREFERRED || debug) { 5371 Slog.v(TAG, "Found preferred activity:"); 5372 if (ai != null) { 5373 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5374 } else { 5375 Slog.v(TAG, " null"); 5376 } 5377 } 5378 if (ai == null) { 5379 // This previously registered preferred activity 5380 // component is no longer known. Most likely an update 5381 // to the app was installed and in the new version this 5382 // component no longer exists. Clean it up by removing 5383 // it from the preferred activities list, and skip it. 5384 Slog.w(TAG, "Removing dangling preferred activity: " 5385 + pa.mPref.mComponent); 5386 pir.removeFilter(pa); 5387 changed = true; 5388 continue; 5389 } 5390 for (int j=0; j<N; j++) { 5391 final ResolveInfo ri = query.get(j); 5392 if (!ri.activityInfo.applicationInfo.packageName 5393 .equals(ai.applicationInfo.packageName)) { 5394 continue; 5395 } 5396 if (!ri.activityInfo.name.equals(ai.name)) { 5397 continue; 5398 } 5399 5400 if (removeMatches) { 5401 pir.removeFilter(pa); 5402 changed = true; 5403 if (DEBUG_PREFERRED) { 5404 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5405 } 5406 break; 5407 } 5408 5409 // Okay we found a previously set preferred or last chosen app. 5410 // If the result set is different from when this 5411 // was created, we need to clear it and re-ask the 5412 // user their preference, if we're looking for an "always" type entry. 5413 if (always && !pa.mPref.sameSet(query)) { 5414 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5415 + intent + " type " + resolvedType); 5416 if (DEBUG_PREFERRED) { 5417 Slog.v(TAG, "Removing preferred activity since set changed " 5418 + pa.mPref.mComponent); 5419 } 5420 pir.removeFilter(pa); 5421 // Re-add the filter as a "last chosen" entry (!always) 5422 PreferredActivity lastChosen = new PreferredActivity( 5423 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5424 pir.addFilter(lastChosen); 5425 changed = true; 5426 return null; 5427 } 5428 5429 // Yay! Either the set matched or we're looking for the last chosen 5430 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5431 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5432 return ri; 5433 } 5434 } 5435 } finally { 5436 if (changed) { 5437 if (DEBUG_PREFERRED) { 5438 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5439 } 5440 scheduleWritePackageRestrictionsLocked(userId); 5441 } 5442 } 5443 } 5444 } 5445 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5446 return null; 5447 } 5448 5449 /* 5450 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5451 */ 5452 @Override 5453 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5454 int targetUserId) { 5455 mContext.enforceCallingOrSelfPermission( 5456 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5457 List<CrossProfileIntentFilter> matches = 5458 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5459 if (matches != null) { 5460 int size = matches.size(); 5461 for (int i = 0; i < size; i++) { 5462 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5463 } 5464 } 5465 if (hasWebURI(intent)) { 5466 // cross-profile app linking works only towards the parent. 5467 final UserInfo parent = getProfileParent(sourceUserId); 5468 synchronized(mPackages) { 5469 int flags = updateFlagsForResolve(0, parent.id, intent); 5470 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5471 intent, resolvedType, flags, sourceUserId, parent.id); 5472 return xpDomainInfo != null; 5473 } 5474 } 5475 return false; 5476 } 5477 5478 private UserInfo getProfileParent(int userId) { 5479 final long identity = Binder.clearCallingIdentity(); 5480 try { 5481 return sUserManager.getProfileParent(userId); 5482 } finally { 5483 Binder.restoreCallingIdentity(identity); 5484 } 5485 } 5486 5487 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5488 String resolvedType, int userId) { 5489 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5490 if (resolver != null) { 5491 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5492 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5493 } 5494 return null; 5495 } 5496 5497 @Override 5498 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5499 String resolvedType, int flags, int userId) { 5500 try { 5501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5502 5503 return new ParceledListSlice<>( 5504 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5505 } finally { 5506 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5507 } 5508 } 5509 5510 /** 5511 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5512 * ephemeral, returns {@code null}. 5513 */ 5514 private String getEphemeralPackageName(int callingUid) { 5515 final int appId = UserHandle.getAppId(callingUid); 5516 synchronized (mPackages) { 5517 final Object obj = mSettings.getUserIdLPr(appId); 5518 if (obj instanceof PackageSetting) { 5519 final PackageSetting ps = (PackageSetting) obj; 5520 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5521 } 5522 } 5523 return null; 5524 } 5525 5526 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5527 String resolvedType, int flags, int userId) { 5528 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5529 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5530 flags = updateFlagsForResolve(flags, userId, intent); 5531 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5532 false /* requireFullPermission */, false /* checkShell */, 5533 "query intent activities"); 5534 ComponentName comp = intent.getComponent(); 5535 if (comp == null) { 5536 if (intent.getSelector() != null) { 5537 intent = intent.getSelector(); 5538 comp = intent.getComponent(); 5539 } 5540 } 5541 5542 if (comp != null) { 5543 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5544 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5545 if (ai != null) { 5546 // When specifying an explicit component, we prevent the activity from being 5547 // used when either 1) the calling package is normal and the activity is within 5548 // an ephemeral application or 2) the calling package is ephemeral and the 5549 // activity is not visible to ephemeral applications. 5550 boolean blockResolution = 5551 (ephemeralPkgName == null 5552 && (ai.applicationInfo.privateFlags 5553 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5554 || (ephemeralPkgName != null 5555 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5556 if (!blockResolution) { 5557 final ResolveInfo ri = new ResolveInfo(); 5558 ri.activityInfo = ai; 5559 list.add(ri); 5560 } 5561 } 5562 return list; 5563 } 5564 5565 // reader 5566 boolean sortResult = false; 5567 boolean addEphemeral = false; 5568 List<ResolveInfo> result; 5569 final String pkgName = intent.getPackage(); 5570 synchronized (mPackages) { 5571 if (pkgName == null) { 5572 List<CrossProfileIntentFilter> matchingFilters = 5573 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5574 // Check for results that need to skip the current profile. 5575 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5576 resolvedType, flags, userId); 5577 if (xpResolveInfo != null) { 5578 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5579 xpResult.add(xpResolveInfo); 5580 return filterForEphemeral( 5581 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5582 } 5583 5584 // Check for results in the current profile. 5585 result = filterIfNotSystemUser(mActivities.queryIntent( 5586 intent, resolvedType, flags, userId), userId); 5587 addEphemeral = 5588 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5589 5590 // Check for cross profile results. 5591 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5592 xpResolveInfo = queryCrossProfileIntents( 5593 matchingFilters, intent, resolvedType, flags, userId, 5594 hasNonNegativePriorityResult); 5595 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5596 boolean isVisibleToUser = filterIfNotSystemUser( 5597 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5598 if (isVisibleToUser) { 5599 result.add(xpResolveInfo); 5600 sortResult = true; 5601 } 5602 } 5603 if (hasWebURI(intent)) { 5604 CrossProfileDomainInfo xpDomainInfo = null; 5605 final UserInfo parent = getProfileParent(userId); 5606 if (parent != null) { 5607 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5608 flags, userId, parent.id); 5609 } 5610 if (xpDomainInfo != null) { 5611 if (xpResolveInfo != null) { 5612 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5613 // in the result. 5614 result.remove(xpResolveInfo); 5615 } 5616 if (result.size() == 0 && !addEphemeral) { 5617 // No result in current profile, but found candidate in parent user. 5618 // And we are not going to add emphemeral app, so we can return the 5619 // result straight away. 5620 result.add(xpDomainInfo.resolveInfo); 5621 return filterForEphemeral(result, ephemeralPkgName); 5622 } 5623 } else if (result.size() <= 1 && !addEphemeral) { 5624 // No result in parent user and <= 1 result in current profile, and we 5625 // are not going to add emphemeral app, so we can return the result without 5626 // further processing. 5627 return filterForEphemeral(result, ephemeralPkgName); 5628 } 5629 // We have more than one candidate (combining results from current and parent 5630 // profile), so we need filtering and sorting. 5631 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5632 intent, flags, result, xpDomainInfo, userId); 5633 sortResult = true; 5634 } 5635 } else { 5636 final PackageParser.Package pkg = mPackages.get(pkgName); 5637 if (pkg != null) { 5638 result = filterForEphemeral(filterIfNotSystemUser( 5639 mActivities.queryIntentForPackage( 5640 intent, resolvedType, flags, pkg.activities, userId), 5641 userId), ephemeralPkgName); 5642 } else { 5643 // the caller wants to resolve for a particular package; however, there 5644 // were no installed results, so, try to find an ephemeral result 5645 addEphemeral = isEphemeralAllowed( 5646 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5647 result = new ArrayList<ResolveInfo>(); 5648 } 5649 } 5650 } 5651 if (addEphemeral) { 5652 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5653 final EphemeralRequest requestObject = new EphemeralRequest( 5654 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5655 null /*launchIntent*/, null /*callingPackage*/, userId); 5656 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5657 mContext, mEphemeralResolverConnection, requestObject); 5658 if (intentInfo != null) { 5659 if (DEBUG_EPHEMERAL) { 5660 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5661 } 5662 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5663 ephemeralInstaller.ephemeralResponse = intentInfo; 5664 // make sure this resolver is the default 5665 ephemeralInstaller.isDefault = true; 5666 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5667 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5668 // add a non-generic filter 5669 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5670 ephemeralInstaller.filter.addDataPath( 5671 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5672 result.add(ephemeralInstaller); 5673 } 5674 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5675 } 5676 if (sortResult) { 5677 Collections.sort(result, mResolvePrioritySorter); 5678 } 5679 return filterForEphemeral(result, ephemeralPkgName); 5680 } 5681 5682 private static class CrossProfileDomainInfo { 5683 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5684 ResolveInfo resolveInfo; 5685 /* Best domain verification status of the activities found in the other profile */ 5686 int bestDomainVerificationStatus; 5687 } 5688 5689 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5690 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5691 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5692 sourceUserId)) { 5693 return null; 5694 } 5695 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5696 resolvedType, flags, parentUserId); 5697 5698 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5699 return null; 5700 } 5701 CrossProfileDomainInfo result = null; 5702 int size = resultTargetUser.size(); 5703 for (int i = 0; i < size; i++) { 5704 ResolveInfo riTargetUser = resultTargetUser.get(i); 5705 // Intent filter verification is only for filters that specify a host. So don't return 5706 // those that handle all web uris. 5707 if (riTargetUser.handleAllWebDataURI) { 5708 continue; 5709 } 5710 String packageName = riTargetUser.activityInfo.packageName; 5711 PackageSetting ps = mSettings.mPackages.get(packageName); 5712 if (ps == null) { 5713 continue; 5714 } 5715 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5716 int status = (int)(verificationState >> 32); 5717 if (result == null) { 5718 result = new CrossProfileDomainInfo(); 5719 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5720 sourceUserId, parentUserId); 5721 result.bestDomainVerificationStatus = status; 5722 } else { 5723 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5724 result.bestDomainVerificationStatus); 5725 } 5726 } 5727 // Don't consider matches with status NEVER across profiles. 5728 if (result != null && result.bestDomainVerificationStatus 5729 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5730 return null; 5731 } 5732 return result; 5733 } 5734 5735 /** 5736 * Verification statuses are ordered from the worse to the best, except for 5737 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5738 */ 5739 private int bestDomainVerificationStatus(int status1, int status2) { 5740 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5741 return status2; 5742 } 5743 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5744 return status1; 5745 } 5746 return (int) MathUtils.max(status1, status2); 5747 } 5748 5749 private boolean isUserEnabled(int userId) { 5750 long callingId = Binder.clearCallingIdentity(); 5751 try { 5752 UserInfo userInfo = sUserManager.getUserInfo(userId); 5753 return userInfo != null && userInfo.isEnabled(); 5754 } finally { 5755 Binder.restoreCallingIdentity(callingId); 5756 } 5757 } 5758 5759 /** 5760 * Filter out activities with systemUserOnly flag set, when current user is not System. 5761 * 5762 * @return filtered list 5763 */ 5764 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5765 if (userId == UserHandle.USER_SYSTEM) { 5766 return resolveInfos; 5767 } 5768 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5769 ResolveInfo info = resolveInfos.get(i); 5770 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5771 resolveInfos.remove(i); 5772 } 5773 } 5774 return resolveInfos; 5775 } 5776 5777 /** 5778 * Filters out ephemeral activities. 5779 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 5780 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 5781 * 5782 * @param resolveInfos The pre-filtered list of resolved activities 5783 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 5784 * is performed. 5785 * @return A filtered list of resolved activities. 5786 */ 5787 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 5788 String ephemeralPkgName) { 5789 if (ephemeralPkgName == null) { 5790 return resolveInfos; 5791 } 5792 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5793 ResolveInfo info = resolveInfos.get(i); 5794 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 5795 // allow activities that are defined in the provided package 5796 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 5797 continue; 5798 } 5799 // allow activities that have been explicitly exposed to ephemeral apps 5800 if (!isEphemeralApp 5801 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 5802 continue; 5803 } 5804 resolveInfos.remove(i); 5805 } 5806 return resolveInfos; 5807 } 5808 5809 /** 5810 * @param resolveInfos list of resolve infos in descending priority order 5811 * @return if the list contains a resolve info with non-negative priority 5812 */ 5813 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5814 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5815 } 5816 5817 private static boolean hasWebURI(Intent intent) { 5818 if (intent.getData() == null) { 5819 return false; 5820 } 5821 final String scheme = intent.getScheme(); 5822 if (TextUtils.isEmpty(scheme)) { 5823 return false; 5824 } 5825 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5826 } 5827 5828 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5829 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5830 int userId) { 5831 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5832 5833 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5834 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5835 candidates.size()); 5836 } 5837 5838 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5839 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5840 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5841 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5842 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5843 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5844 5845 synchronized (mPackages) { 5846 final int count = candidates.size(); 5847 // First, try to use linked apps. Partition the candidates into four lists: 5848 // one for the final results, one for the "do not use ever", one for "undefined status" 5849 // and finally one for "browser app type". 5850 for (int n=0; n<count; n++) { 5851 ResolveInfo info = candidates.get(n); 5852 String packageName = info.activityInfo.packageName; 5853 PackageSetting ps = mSettings.mPackages.get(packageName); 5854 if (ps != null) { 5855 // Add to the special match all list (Browser use case) 5856 if (info.handleAllWebDataURI) { 5857 matchAllList.add(info); 5858 continue; 5859 } 5860 // Try to get the status from User settings first 5861 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5862 int status = (int)(packedStatus >> 32); 5863 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5864 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5865 if (DEBUG_DOMAIN_VERIFICATION) { 5866 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5867 + " : linkgen=" + linkGeneration); 5868 } 5869 // Use link-enabled generation as preferredOrder, i.e. 5870 // prefer newly-enabled over earlier-enabled. 5871 info.preferredOrder = linkGeneration; 5872 alwaysList.add(info); 5873 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5874 if (DEBUG_DOMAIN_VERIFICATION) { 5875 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5876 } 5877 neverList.add(info); 5878 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5879 if (DEBUG_DOMAIN_VERIFICATION) { 5880 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5881 } 5882 alwaysAskList.add(info); 5883 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5884 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5885 if (DEBUG_DOMAIN_VERIFICATION) { 5886 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5887 } 5888 undefinedList.add(info); 5889 } 5890 } 5891 } 5892 5893 // We'll want to include browser possibilities in a few cases 5894 boolean includeBrowser = false; 5895 5896 // First try to add the "always" resolution(s) for the current user, if any 5897 if (alwaysList.size() > 0) { 5898 result.addAll(alwaysList); 5899 } else { 5900 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5901 result.addAll(undefinedList); 5902 // Maybe add one for the other profile. 5903 if (xpDomainInfo != null && ( 5904 xpDomainInfo.bestDomainVerificationStatus 5905 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5906 result.add(xpDomainInfo.resolveInfo); 5907 } 5908 includeBrowser = true; 5909 } 5910 5911 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5912 // If there were 'always' entries their preferred order has been set, so we also 5913 // back that off to make the alternatives equivalent 5914 if (alwaysAskList.size() > 0) { 5915 for (ResolveInfo i : result) { 5916 i.preferredOrder = 0; 5917 } 5918 result.addAll(alwaysAskList); 5919 includeBrowser = true; 5920 } 5921 5922 if (includeBrowser) { 5923 // Also add browsers (all of them or only the default one) 5924 if (DEBUG_DOMAIN_VERIFICATION) { 5925 Slog.v(TAG, " ...including browsers in candidate set"); 5926 } 5927 if ((matchFlags & MATCH_ALL) != 0) { 5928 result.addAll(matchAllList); 5929 } else { 5930 // Browser/generic handling case. If there's a default browser, go straight 5931 // to that (but only if there is no other higher-priority match). 5932 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5933 int maxMatchPrio = 0; 5934 ResolveInfo defaultBrowserMatch = null; 5935 final int numCandidates = matchAllList.size(); 5936 for (int n = 0; n < numCandidates; n++) { 5937 ResolveInfo info = matchAllList.get(n); 5938 // track the highest overall match priority... 5939 if (info.priority > maxMatchPrio) { 5940 maxMatchPrio = info.priority; 5941 } 5942 // ...and the highest-priority default browser match 5943 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5944 if (defaultBrowserMatch == null 5945 || (defaultBrowserMatch.priority < info.priority)) { 5946 if (debug) { 5947 Slog.v(TAG, "Considering default browser match " + info); 5948 } 5949 defaultBrowserMatch = info; 5950 } 5951 } 5952 } 5953 if (defaultBrowserMatch != null 5954 && defaultBrowserMatch.priority >= maxMatchPrio 5955 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5956 { 5957 if (debug) { 5958 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5959 } 5960 result.add(defaultBrowserMatch); 5961 } else { 5962 result.addAll(matchAllList); 5963 } 5964 } 5965 5966 // If there is nothing selected, add all candidates and remove the ones that the user 5967 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5968 if (result.size() == 0) { 5969 result.addAll(candidates); 5970 result.removeAll(neverList); 5971 } 5972 } 5973 } 5974 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5975 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5976 result.size()); 5977 for (ResolveInfo info : result) { 5978 Slog.v(TAG, " + " + info.activityInfo); 5979 } 5980 } 5981 return result; 5982 } 5983 5984 // Returns a packed value as a long: 5985 // 5986 // high 'int'-sized word: link status: undefined/ask/never/always. 5987 // low 'int'-sized word: relative priority among 'always' results. 5988 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5989 long result = ps.getDomainVerificationStatusForUser(userId); 5990 // if none available, get the master status 5991 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5992 if (ps.getIntentFilterVerificationInfo() != null) { 5993 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5994 } 5995 } 5996 return result; 5997 } 5998 5999 private ResolveInfo querySkipCurrentProfileIntents( 6000 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6001 int flags, int sourceUserId) { 6002 if (matchingFilters != null) { 6003 int size = matchingFilters.size(); 6004 for (int i = 0; i < size; i ++) { 6005 CrossProfileIntentFilter filter = matchingFilters.get(i); 6006 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6007 // Checking if there are activities in the target user that can handle the 6008 // intent. 6009 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6010 resolvedType, flags, sourceUserId); 6011 if (resolveInfo != null) { 6012 return resolveInfo; 6013 } 6014 } 6015 } 6016 } 6017 return null; 6018 } 6019 6020 // Return matching ResolveInfo in target user if any. 6021 private ResolveInfo queryCrossProfileIntents( 6022 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6023 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6024 if (matchingFilters != null) { 6025 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6026 // match the same intent. For performance reasons, it is better not to 6027 // run queryIntent twice for the same userId 6028 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6029 int size = matchingFilters.size(); 6030 for (int i = 0; i < size; i++) { 6031 CrossProfileIntentFilter filter = matchingFilters.get(i); 6032 int targetUserId = filter.getTargetUserId(); 6033 boolean skipCurrentProfile = 6034 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6035 boolean skipCurrentProfileIfNoMatchFound = 6036 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6037 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6038 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6039 // Checking if there are activities in the target user that can handle the 6040 // intent. 6041 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6042 resolvedType, flags, sourceUserId); 6043 if (resolveInfo != null) return resolveInfo; 6044 alreadyTriedUserIds.put(targetUserId, true); 6045 } 6046 } 6047 } 6048 return null; 6049 } 6050 6051 /** 6052 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6053 * will forward the intent to the filter's target user. 6054 * Otherwise, returns null. 6055 */ 6056 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6057 String resolvedType, int flags, int sourceUserId) { 6058 int targetUserId = filter.getTargetUserId(); 6059 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6060 resolvedType, flags, targetUserId); 6061 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6062 // If all the matches in the target profile are suspended, return null. 6063 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6064 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6065 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6066 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6067 targetUserId); 6068 } 6069 } 6070 } 6071 return null; 6072 } 6073 6074 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6075 int sourceUserId, int targetUserId) { 6076 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6077 long ident = Binder.clearCallingIdentity(); 6078 boolean targetIsProfile; 6079 try { 6080 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6081 } finally { 6082 Binder.restoreCallingIdentity(ident); 6083 } 6084 String className; 6085 if (targetIsProfile) { 6086 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6087 } else { 6088 className = FORWARD_INTENT_TO_PARENT; 6089 } 6090 ComponentName forwardingActivityComponentName = new ComponentName( 6091 mAndroidApplication.packageName, className); 6092 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6093 sourceUserId); 6094 if (!targetIsProfile) { 6095 forwardingActivityInfo.showUserIcon = targetUserId; 6096 forwardingResolveInfo.noResourceId = true; 6097 } 6098 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6099 forwardingResolveInfo.priority = 0; 6100 forwardingResolveInfo.preferredOrder = 0; 6101 forwardingResolveInfo.match = 0; 6102 forwardingResolveInfo.isDefault = true; 6103 forwardingResolveInfo.filter = filter; 6104 forwardingResolveInfo.targetUserId = targetUserId; 6105 return forwardingResolveInfo; 6106 } 6107 6108 @Override 6109 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6110 Intent[] specifics, String[] specificTypes, Intent intent, 6111 String resolvedType, int flags, int userId) { 6112 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6113 specificTypes, intent, resolvedType, flags, userId)); 6114 } 6115 6116 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6117 Intent[] specifics, String[] specificTypes, Intent intent, 6118 String resolvedType, int flags, int userId) { 6119 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6120 flags = updateFlagsForResolve(flags, userId, intent); 6121 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6122 false /* requireFullPermission */, false /* checkShell */, 6123 "query intent activity options"); 6124 final String resultsAction = intent.getAction(); 6125 6126 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6127 | PackageManager.GET_RESOLVED_FILTER, userId); 6128 6129 if (DEBUG_INTENT_MATCHING) { 6130 Log.v(TAG, "Query " + intent + ": " + results); 6131 } 6132 6133 int specificsPos = 0; 6134 int N; 6135 6136 // todo: note that the algorithm used here is O(N^2). This 6137 // isn't a problem in our current environment, but if we start running 6138 // into situations where we have more than 5 or 10 matches then this 6139 // should probably be changed to something smarter... 6140 6141 // First we go through and resolve each of the specific items 6142 // that were supplied, taking care of removing any corresponding 6143 // duplicate items in the generic resolve list. 6144 if (specifics != null) { 6145 for (int i=0; i<specifics.length; i++) { 6146 final Intent sintent = specifics[i]; 6147 if (sintent == null) { 6148 continue; 6149 } 6150 6151 if (DEBUG_INTENT_MATCHING) { 6152 Log.v(TAG, "Specific #" + i + ": " + sintent); 6153 } 6154 6155 String action = sintent.getAction(); 6156 if (resultsAction != null && resultsAction.equals(action)) { 6157 // If this action was explicitly requested, then don't 6158 // remove things that have it. 6159 action = null; 6160 } 6161 6162 ResolveInfo ri = null; 6163 ActivityInfo ai = null; 6164 6165 ComponentName comp = sintent.getComponent(); 6166 if (comp == null) { 6167 ri = resolveIntent( 6168 sintent, 6169 specificTypes != null ? specificTypes[i] : null, 6170 flags, userId); 6171 if (ri == null) { 6172 continue; 6173 } 6174 if (ri == mResolveInfo) { 6175 // ACK! Must do something better with this. 6176 } 6177 ai = ri.activityInfo; 6178 comp = new ComponentName(ai.applicationInfo.packageName, 6179 ai.name); 6180 } else { 6181 ai = getActivityInfo(comp, flags, userId); 6182 if (ai == null) { 6183 continue; 6184 } 6185 } 6186 6187 // Look for any generic query activities that are duplicates 6188 // of this specific one, and remove them from the results. 6189 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6190 N = results.size(); 6191 int j; 6192 for (j=specificsPos; j<N; j++) { 6193 ResolveInfo sri = results.get(j); 6194 if ((sri.activityInfo.name.equals(comp.getClassName()) 6195 && sri.activityInfo.applicationInfo.packageName.equals( 6196 comp.getPackageName())) 6197 || (action != null && sri.filter.matchAction(action))) { 6198 results.remove(j); 6199 if (DEBUG_INTENT_MATCHING) Log.v( 6200 TAG, "Removing duplicate item from " + j 6201 + " due to specific " + specificsPos); 6202 if (ri == null) { 6203 ri = sri; 6204 } 6205 j--; 6206 N--; 6207 } 6208 } 6209 6210 // Add this specific item to its proper place. 6211 if (ri == null) { 6212 ri = new ResolveInfo(); 6213 ri.activityInfo = ai; 6214 } 6215 results.add(specificsPos, ri); 6216 ri.specificIndex = i; 6217 specificsPos++; 6218 } 6219 } 6220 6221 // Now we go through the remaining generic results and remove any 6222 // duplicate actions that are found here. 6223 N = results.size(); 6224 for (int i=specificsPos; i<N-1; i++) { 6225 final ResolveInfo rii = results.get(i); 6226 if (rii.filter == null) { 6227 continue; 6228 } 6229 6230 // Iterate over all of the actions of this result's intent 6231 // filter... typically this should be just one. 6232 final Iterator<String> it = rii.filter.actionsIterator(); 6233 if (it == null) { 6234 continue; 6235 } 6236 while (it.hasNext()) { 6237 final String action = it.next(); 6238 if (resultsAction != null && resultsAction.equals(action)) { 6239 // If this action was explicitly requested, then don't 6240 // remove things that have it. 6241 continue; 6242 } 6243 for (int j=i+1; j<N; j++) { 6244 final ResolveInfo rij = results.get(j); 6245 if (rij.filter != null && rij.filter.hasAction(action)) { 6246 results.remove(j); 6247 if (DEBUG_INTENT_MATCHING) Log.v( 6248 TAG, "Removing duplicate item from " + j 6249 + " due to action " + action + " at " + i); 6250 j--; 6251 N--; 6252 } 6253 } 6254 } 6255 6256 // If the caller didn't request filter information, drop it now 6257 // so we don't have to marshall/unmarshall it. 6258 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6259 rii.filter = null; 6260 } 6261 } 6262 6263 // Filter out the caller activity if so requested. 6264 if (caller != null) { 6265 N = results.size(); 6266 for (int i=0; i<N; i++) { 6267 ActivityInfo ainfo = results.get(i).activityInfo; 6268 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6269 && caller.getClassName().equals(ainfo.name)) { 6270 results.remove(i); 6271 break; 6272 } 6273 } 6274 } 6275 6276 // If the caller didn't request filter information, 6277 // drop them now so we don't have to 6278 // marshall/unmarshall it. 6279 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6280 N = results.size(); 6281 for (int i=0; i<N; i++) { 6282 results.get(i).filter = null; 6283 } 6284 } 6285 6286 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6287 return results; 6288 } 6289 6290 @Override 6291 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6292 String resolvedType, int flags, int userId) { 6293 return new ParceledListSlice<>( 6294 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6295 } 6296 6297 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6298 String resolvedType, int flags, int userId) { 6299 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6300 flags = updateFlagsForResolve(flags, userId, intent); 6301 ComponentName comp = intent.getComponent(); 6302 if (comp == null) { 6303 if (intent.getSelector() != null) { 6304 intent = intent.getSelector(); 6305 comp = intent.getComponent(); 6306 } 6307 } 6308 if (comp != null) { 6309 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6310 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6311 if (ai != null) { 6312 ResolveInfo ri = new ResolveInfo(); 6313 ri.activityInfo = ai; 6314 list.add(ri); 6315 } 6316 return list; 6317 } 6318 6319 // reader 6320 synchronized (mPackages) { 6321 String pkgName = intent.getPackage(); 6322 if (pkgName == null) { 6323 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6324 } 6325 final PackageParser.Package pkg = mPackages.get(pkgName); 6326 if (pkg != null) { 6327 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6328 userId); 6329 } 6330 return Collections.emptyList(); 6331 } 6332 } 6333 6334 @Override 6335 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6336 if (!sUserManager.exists(userId)) return null; 6337 flags = updateFlagsForResolve(flags, userId, intent); 6338 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6339 if (query != null) { 6340 if (query.size() >= 1) { 6341 // If there is more than one service with the same priority, 6342 // just arbitrarily pick the first one. 6343 return query.get(0); 6344 } 6345 } 6346 return null; 6347 } 6348 6349 @Override 6350 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6351 String resolvedType, int flags, int userId) { 6352 return new ParceledListSlice<>( 6353 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6354 } 6355 6356 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6357 String resolvedType, int flags, int userId) { 6358 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6359 flags = updateFlagsForResolve(flags, userId, intent); 6360 ComponentName comp = intent.getComponent(); 6361 if (comp == null) { 6362 if (intent.getSelector() != null) { 6363 intent = intent.getSelector(); 6364 comp = intent.getComponent(); 6365 } 6366 } 6367 if (comp != null) { 6368 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6369 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6370 if (si != null) { 6371 final ResolveInfo ri = new ResolveInfo(); 6372 ri.serviceInfo = si; 6373 list.add(ri); 6374 } 6375 return list; 6376 } 6377 6378 // reader 6379 synchronized (mPackages) { 6380 String pkgName = intent.getPackage(); 6381 if (pkgName == null) { 6382 return mServices.queryIntent(intent, resolvedType, flags, userId); 6383 } 6384 final PackageParser.Package pkg = mPackages.get(pkgName); 6385 if (pkg != null) { 6386 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6387 userId); 6388 } 6389 return Collections.emptyList(); 6390 } 6391 } 6392 6393 @Override 6394 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6395 String resolvedType, int flags, int userId) { 6396 return new ParceledListSlice<>( 6397 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6398 } 6399 6400 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6401 Intent intent, String resolvedType, int flags, int userId) { 6402 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6403 flags = updateFlagsForResolve(flags, userId, intent); 6404 ComponentName comp = intent.getComponent(); 6405 if (comp == null) { 6406 if (intent.getSelector() != null) { 6407 intent = intent.getSelector(); 6408 comp = intent.getComponent(); 6409 } 6410 } 6411 if (comp != null) { 6412 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6413 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6414 if (pi != null) { 6415 final ResolveInfo ri = new ResolveInfo(); 6416 ri.providerInfo = pi; 6417 list.add(ri); 6418 } 6419 return list; 6420 } 6421 6422 // reader 6423 synchronized (mPackages) { 6424 String pkgName = intent.getPackage(); 6425 if (pkgName == null) { 6426 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6427 } 6428 final PackageParser.Package pkg = mPackages.get(pkgName); 6429 if (pkg != null) { 6430 return mProviders.queryIntentForPackage( 6431 intent, resolvedType, flags, pkg.providers, userId); 6432 } 6433 return Collections.emptyList(); 6434 } 6435 } 6436 6437 @Override 6438 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6439 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6440 flags = updateFlagsForPackage(flags, userId, null); 6441 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6442 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6443 true /* requireFullPermission */, false /* checkShell */, 6444 "get installed packages"); 6445 6446 // writer 6447 synchronized (mPackages) { 6448 ArrayList<PackageInfo> list; 6449 if (listUninstalled) { 6450 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6451 for (PackageSetting ps : mSettings.mPackages.values()) { 6452 final PackageInfo pi; 6453 if (ps.pkg != null) { 6454 pi = generatePackageInfo(ps, flags, userId); 6455 } else { 6456 pi = generatePackageInfo(ps, flags, userId); 6457 } 6458 if (pi != null) { 6459 list.add(pi); 6460 } 6461 } 6462 } else { 6463 list = new ArrayList<PackageInfo>(mPackages.size()); 6464 for (PackageParser.Package p : mPackages.values()) { 6465 final PackageInfo pi = 6466 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6467 if (pi != null) { 6468 list.add(pi); 6469 } 6470 } 6471 } 6472 6473 return new ParceledListSlice<PackageInfo>(list); 6474 } 6475 } 6476 6477 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6478 String[] permissions, boolean[] tmp, int flags, int userId) { 6479 int numMatch = 0; 6480 final PermissionsState permissionsState = ps.getPermissionsState(); 6481 for (int i=0; i<permissions.length; i++) { 6482 final String permission = permissions[i]; 6483 if (permissionsState.hasPermission(permission, userId)) { 6484 tmp[i] = true; 6485 numMatch++; 6486 } else { 6487 tmp[i] = false; 6488 } 6489 } 6490 if (numMatch == 0) { 6491 return; 6492 } 6493 final PackageInfo pi; 6494 if (ps.pkg != null) { 6495 pi = generatePackageInfo(ps, flags, userId); 6496 } else { 6497 pi = generatePackageInfo(ps, flags, userId); 6498 } 6499 // The above might return null in cases of uninstalled apps or install-state 6500 // skew across users/profiles. 6501 if (pi != null) { 6502 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6503 if (numMatch == permissions.length) { 6504 pi.requestedPermissions = permissions; 6505 } else { 6506 pi.requestedPermissions = new String[numMatch]; 6507 numMatch = 0; 6508 for (int i=0; i<permissions.length; i++) { 6509 if (tmp[i]) { 6510 pi.requestedPermissions[numMatch] = permissions[i]; 6511 numMatch++; 6512 } 6513 } 6514 } 6515 } 6516 list.add(pi); 6517 } 6518 } 6519 6520 @Override 6521 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6522 String[] permissions, int flags, int userId) { 6523 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6524 flags = updateFlagsForPackage(flags, userId, permissions); 6525 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6526 true /* requireFullPermission */, false /* checkShell */, 6527 "get packages holding permissions"); 6528 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6529 6530 // writer 6531 synchronized (mPackages) { 6532 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6533 boolean[] tmpBools = new boolean[permissions.length]; 6534 if (listUninstalled) { 6535 for (PackageSetting ps : mSettings.mPackages.values()) { 6536 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6537 userId); 6538 } 6539 } else { 6540 for (PackageParser.Package pkg : mPackages.values()) { 6541 PackageSetting ps = (PackageSetting)pkg.mExtras; 6542 if (ps != null) { 6543 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6544 userId); 6545 } 6546 } 6547 } 6548 6549 return new ParceledListSlice<PackageInfo>(list); 6550 } 6551 } 6552 6553 @Override 6554 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6555 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6556 flags = updateFlagsForApplication(flags, userId, null); 6557 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6558 6559 // writer 6560 synchronized (mPackages) { 6561 ArrayList<ApplicationInfo> list; 6562 if (listUninstalled) { 6563 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6564 for (PackageSetting ps : mSettings.mPackages.values()) { 6565 ApplicationInfo ai; 6566 int effectiveFlags = flags; 6567 if (ps.isSystem()) { 6568 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6569 } 6570 if (ps.pkg != null) { 6571 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6572 ps.readUserState(userId), userId); 6573 } else { 6574 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6575 userId); 6576 } 6577 if (ai != null) { 6578 list.add(ai); 6579 } 6580 } 6581 } else { 6582 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6583 for (PackageParser.Package p : mPackages.values()) { 6584 if (p.mExtras != null) { 6585 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6586 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6587 if (ai != null) { 6588 list.add(ai); 6589 } 6590 } 6591 } 6592 } 6593 6594 return new ParceledListSlice<ApplicationInfo>(list); 6595 } 6596 } 6597 6598 @Override 6599 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6600 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6601 return null; 6602 } 6603 6604 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6605 "getEphemeralApplications"); 6606 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6607 true /* requireFullPermission */, false /* checkShell */, 6608 "getEphemeralApplications"); 6609 synchronized (mPackages) { 6610 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6611 .getEphemeralApplicationsLPw(userId); 6612 if (ephemeralApps != null) { 6613 return new ParceledListSlice<>(ephemeralApps); 6614 } 6615 } 6616 return null; 6617 } 6618 6619 @Override 6620 public boolean isEphemeralApplication(String packageName, int userId) { 6621 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6622 true /* requireFullPermission */, false /* checkShell */, 6623 "isEphemeral"); 6624 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6625 return false; 6626 } 6627 6628 if (!isCallerSameApp(packageName)) { 6629 return false; 6630 } 6631 synchronized (mPackages) { 6632 PackageParser.Package pkg = mPackages.get(packageName); 6633 if (pkg != null) { 6634 return pkg.applicationInfo.isEphemeralApp(); 6635 } 6636 } 6637 return false; 6638 } 6639 6640 @Override 6641 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6642 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6643 return null; 6644 } 6645 6646 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6647 true /* requireFullPermission */, false /* checkShell */, 6648 "getCookie"); 6649 if (!isCallerSameApp(packageName)) { 6650 return null; 6651 } 6652 synchronized (mPackages) { 6653 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6654 packageName, userId); 6655 } 6656 } 6657 6658 @Override 6659 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6660 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6661 return true; 6662 } 6663 6664 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6665 true /* requireFullPermission */, true /* checkShell */, 6666 "setCookie"); 6667 if (!isCallerSameApp(packageName)) { 6668 return false; 6669 } 6670 synchronized (mPackages) { 6671 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6672 packageName, cookie, userId); 6673 } 6674 } 6675 6676 @Override 6677 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6678 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6679 return null; 6680 } 6681 6682 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6683 "getEphemeralApplicationIcon"); 6684 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6685 true /* requireFullPermission */, false /* checkShell */, 6686 "getEphemeralApplicationIcon"); 6687 synchronized (mPackages) { 6688 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6689 packageName, userId); 6690 } 6691 } 6692 6693 private boolean isCallerSameApp(String packageName) { 6694 PackageParser.Package pkg = mPackages.get(packageName); 6695 return pkg != null 6696 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6697 } 6698 6699 @Override 6700 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6701 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6702 } 6703 6704 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6705 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6706 6707 // reader 6708 synchronized (mPackages) { 6709 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6710 final int userId = UserHandle.getCallingUserId(); 6711 while (i.hasNext()) { 6712 final PackageParser.Package p = i.next(); 6713 if (p.applicationInfo == null) continue; 6714 6715 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6716 && !p.applicationInfo.isDirectBootAware(); 6717 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6718 && p.applicationInfo.isDirectBootAware(); 6719 6720 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6721 && (!mSafeMode || isSystemApp(p)) 6722 && (matchesUnaware || matchesAware)) { 6723 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6724 if (ps != null) { 6725 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6726 ps.readUserState(userId), userId); 6727 if (ai != null) { 6728 finalList.add(ai); 6729 } 6730 } 6731 } 6732 } 6733 } 6734 6735 return finalList; 6736 } 6737 6738 @Override 6739 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6740 if (!sUserManager.exists(userId)) return null; 6741 flags = updateFlagsForComponent(flags, userId, name); 6742 // reader 6743 synchronized (mPackages) { 6744 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6745 PackageSetting ps = provider != null 6746 ? mSettings.mPackages.get(provider.owner.packageName) 6747 : null; 6748 return ps != null 6749 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6750 ? PackageParser.generateProviderInfo(provider, flags, 6751 ps.readUserState(userId), userId) 6752 : null; 6753 } 6754 } 6755 6756 /** 6757 * @deprecated 6758 */ 6759 @Deprecated 6760 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6761 // reader 6762 synchronized (mPackages) { 6763 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6764 .entrySet().iterator(); 6765 final int userId = UserHandle.getCallingUserId(); 6766 while (i.hasNext()) { 6767 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6768 PackageParser.Provider p = entry.getValue(); 6769 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6770 6771 if (ps != null && p.syncable 6772 && (!mSafeMode || (p.info.applicationInfo.flags 6773 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6774 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6775 ps.readUserState(userId), userId); 6776 if (info != null) { 6777 outNames.add(entry.getKey()); 6778 outInfo.add(info); 6779 } 6780 } 6781 } 6782 } 6783 } 6784 6785 @Override 6786 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6787 int uid, int flags) { 6788 final int userId = processName != null ? UserHandle.getUserId(uid) 6789 : UserHandle.getCallingUserId(); 6790 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6791 flags = updateFlagsForComponent(flags, userId, processName); 6792 6793 ArrayList<ProviderInfo> finalList = null; 6794 // reader 6795 synchronized (mPackages) { 6796 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6797 while (i.hasNext()) { 6798 final PackageParser.Provider p = i.next(); 6799 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6800 if (ps != null && p.info.authority != null 6801 && (processName == null 6802 || (p.info.processName.equals(processName) 6803 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6804 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6805 if (finalList == null) { 6806 finalList = new ArrayList<ProviderInfo>(3); 6807 } 6808 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6809 ps.readUserState(userId), userId); 6810 if (info != null) { 6811 finalList.add(info); 6812 } 6813 } 6814 } 6815 } 6816 6817 if (finalList != null) { 6818 Collections.sort(finalList, mProviderInitOrderSorter); 6819 return new ParceledListSlice<ProviderInfo>(finalList); 6820 } 6821 6822 return ParceledListSlice.emptyList(); 6823 } 6824 6825 @Override 6826 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6827 // reader 6828 synchronized (mPackages) { 6829 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6830 return PackageParser.generateInstrumentationInfo(i, flags); 6831 } 6832 } 6833 6834 @Override 6835 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6836 String targetPackage, int flags) { 6837 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6838 } 6839 6840 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6841 int flags) { 6842 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6843 6844 // reader 6845 synchronized (mPackages) { 6846 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6847 while (i.hasNext()) { 6848 final PackageParser.Instrumentation p = i.next(); 6849 if (targetPackage == null 6850 || targetPackage.equals(p.info.targetPackage)) { 6851 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6852 flags); 6853 if (ii != null) { 6854 finalList.add(ii); 6855 } 6856 } 6857 } 6858 } 6859 6860 return finalList; 6861 } 6862 6863 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6864 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6865 if (overlays == null) { 6866 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6867 return; 6868 } 6869 for (PackageParser.Package opkg : overlays.values()) { 6870 // Not much to do if idmap fails: we already logged the error 6871 // and we certainly don't want to abort installation of pkg simply 6872 // because an overlay didn't fit properly. For these reasons, 6873 // ignore the return value of createIdmapForPackagePairLI. 6874 createIdmapForPackagePairLI(pkg, opkg); 6875 } 6876 } 6877 6878 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6879 PackageParser.Package opkg) { 6880 if (!opkg.mTrustedOverlay) { 6881 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6882 opkg.baseCodePath + ": overlay not trusted"); 6883 return false; 6884 } 6885 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6886 if (overlaySet == null) { 6887 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6888 opkg.baseCodePath + " but target package has no known overlays"); 6889 return false; 6890 } 6891 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6892 // TODO: generate idmap for split APKs 6893 try { 6894 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6895 } catch (InstallerException e) { 6896 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6897 + opkg.baseCodePath); 6898 return false; 6899 } 6900 PackageParser.Package[] overlayArray = 6901 overlaySet.values().toArray(new PackageParser.Package[0]); 6902 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6903 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6904 return p1.mOverlayPriority - p2.mOverlayPriority; 6905 } 6906 }; 6907 Arrays.sort(overlayArray, cmp); 6908 6909 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6910 int i = 0; 6911 for (PackageParser.Package p : overlayArray) { 6912 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6913 } 6914 return true; 6915 } 6916 6917 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6918 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6919 try { 6920 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6921 } finally { 6922 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6923 } 6924 } 6925 6926 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6927 final File[] files = dir.listFiles(); 6928 if (ArrayUtils.isEmpty(files)) { 6929 Log.d(TAG, "No files in app dir " + dir); 6930 return; 6931 } 6932 6933 if (DEBUG_PACKAGE_SCANNING) { 6934 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6935 + " flags=0x" + Integer.toHexString(parseFlags)); 6936 } 6937 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6938 mSeparateProcesses, mOnlyCore, mMetrics); 6939 6940 // Submit files for parsing in parallel 6941 int fileCount = 0; 6942 for (File file : files) { 6943 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6944 && !PackageInstallerService.isStageName(file.getName()); 6945 if (!isPackage) { 6946 // Ignore entries which are not packages 6947 continue; 6948 } 6949 parallelPackageParser.submit(file, parseFlags); 6950 fileCount++; 6951 } 6952 6953 // Process results one by one 6954 for (; fileCount > 0; fileCount--) { 6955 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 6956 Throwable throwable = parseResult.throwable; 6957 int errorCode = PackageManager.INSTALL_SUCCEEDED; 6958 6959 if (throwable == null) { 6960 try { 6961 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 6962 currentTime, null); 6963 } catch (PackageManagerException e) { 6964 errorCode = e.error; 6965 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 6966 } 6967 } else if (throwable instanceof PackageParser.PackageParserException) { 6968 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 6969 throwable; 6970 errorCode = e.error; 6971 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 6972 } else { 6973 throw new IllegalStateException("Unexpected exception occurred while parsing " 6974 + parseResult.scanFile, throwable); 6975 } 6976 6977 // Delete invalid userdata apps 6978 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6979 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 6980 logCriticalInfo(Log.WARN, 6981 "Deleting invalid package at " + parseResult.scanFile); 6982 removeCodePathLI(parseResult.scanFile); 6983 } 6984 } 6985 parallelPackageParser.close(); 6986 } 6987 6988 private static File getSettingsProblemFile() { 6989 File dataDir = Environment.getDataDirectory(); 6990 File systemDir = new File(dataDir, "system"); 6991 File fname = new File(systemDir, "uiderrors.txt"); 6992 return fname; 6993 } 6994 6995 static void reportSettingsProblem(int priority, String msg) { 6996 logCriticalInfo(priority, msg); 6997 } 6998 6999 static void logCriticalInfo(int priority, String msg) { 7000 Slog.println(priority, TAG, msg); 7001 EventLogTags.writePmCriticalInfo(msg); 7002 try { 7003 File fname = getSettingsProblemFile(); 7004 FileOutputStream out = new FileOutputStream(fname, true); 7005 PrintWriter pw = new FastPrintWriter(out); 7006 SimpleDateFormat formatter = new SimpleDateFormat(); 7007 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7008 pw.println(dateString + ": " + msg); 7009 pw.close(); 7010 FileUtils.setPermissions( 7011 fname.toString(), 7012 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7013 -1, -1); 7014 } catch (java.io.IOException e) { 7015 } 7016 } 7017 7018 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7019 if (srcFile.isDirectory()) { 7020 final File baseFile = new File(pkg.baseCodePath); 7021 long maxModifiedTime = baseFile.lastModified(); 7022 if (pkg.splitCodePaths != null) { 7023 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7024 final File splitFile = new File(pkg.splitCodePaths[i]); 7025 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7026 } 7027 } 7028 return maxModifiedTime; 7029 } 7030 return srcFile.lastModified(); 7031 } 7032 7033 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7034 final int policyFlags) throws PackageManagerException { 7035 // When upgrading from pre-N MR1, verify the package time stamp using the package 7036 // directory and not the APK file. 7037 final long lastModifiedTime = mIsPreNMR1Upgrade 7038 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7039 if (ps != null 7040 && ps.codePath.equals(srcFile) 7041 && ps.timeStamp == lastModifiedTime 7042 && !isCompatSignatureUpdateNeeded(pkg) 7043 && !isRecoverSignatureUpdateNeeded(pkg)) { 7044 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7045 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7046 ArraySet<PublicKey> signingKs; 7047 synchronized (mPackages) { 7048 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7049 } 7050 if (ps.signatures.mSignatures != null 7051 && ps.signatures.mSignatures.length != 0 7052 && signingKs != null) { 7053 // Optimization: reuse the existing cached certificates 7054 // if the package appears to be unchanged. 7055 pkg.mSignatures = ps.signatures.mSignatures; 7056 pkg.mSigningKeys = signingKs; 7057 return; 7058 } 7059 7060 Slog.w(TAG, "PackageSetting for " + ps.name 7061 + " is missing signatures. Collecting certs again to recover them."); 7062 } else { 7063 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7064 } 7065 7066 try { 7067 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7068 PackageParser.collectCertificates(pkg, policyFlags); 7069 } catch (PackageParserException e) { 7070 throw PackageManagerException.from(e); 7071 } finally { 7072 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7073 } 7074 } 7075 7076 /** 7077 * Traces a package scan. 7078 * @see #scanPackageLI(File, int, int, long, UserHandle) 7079 */ 7080 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7081 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7082 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7083 try { 7084 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7085 } finally { 7086 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7087 } 7088 } 7089 7090 /** 7091 * Scans a package and returns the newly parsed package. 7092 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7093 */ 7094 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7095 long currentTime, UserHandle user) throws PackageManagerException { 7096 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7097 PackageParser pp = new PackageParser(); 7098 pp.setSeparateProcesses(mSeparateProcesses); 7099 pp.setOnlyCoreApps(mOnlyCore); 7100 pp.setDisplayMetrics(mMetrics); 7101 7102 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7103 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7104 } 7105 7106 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7107 final PackageParser.Package pkg; 7108 try { 7109 pkg = pp.parsePackage(scanFile, parseFlags); 7110 } catch (PackageParserException e) { 7111 throw PackageManagerException.from(e); 7112 } finally { 7113 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7114 } 7115 7116 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7117 } 7118 7119 /** 7120 * Scans a package and returns the newly parsed package. 7121 * @throws PackageManagerException on a parse error. 7122 */ 7123 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7124 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7125 throws PackageManagerException { 7126 // If the package has children and this is the first dive in the function 7127 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7128 // packages (parent and children) would be successfully scanned before the 7129 // actual scan since scanning mutates internal state and we want to atomically 7130 // install the package and its children. 7131 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7132 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7133 scanFlags |= SCAN_CHECK_ONLY; 7134 } 7135 } else { 7136 scanFlags &= ~SCAN_CHECK_ONLY; 7137 } 7138 7139 // Scan the parent 7140 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7141 scanFlags, currentTime, user); 7142 7143 // Scan the children 7144 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7145 for (int i = 0; i < childCount; i++) { 7146 PackageParser.Package childPackage = pkg.childPackages.get(i); 7147 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7148 currentTime, user); 7149 } 7150 7151 7152 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7153 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7154 } 7155 7156 return scannedPkg; 7157 } 7158 7159 /** 7160 * Scans a package and returns the newly parsed package. 7161 * @throws PackageManagerException on a parse error. 7162 */ 7163 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7164 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7165 throws PackageManagerException { 7166 PackageSetting ps = null; 7167 PackageSetting updatedPkg; 7168 // reader 7169 synchronized (mPackages) { 7170 // Look to see if we already know about this package. 7171 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7172 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7173 // This package has been renamed to its original name. Let's 7174 // use that. 7175 ps = mSettings.getPackageLPr(oldName); 7176 } 7177 // If there was no original package, see one for the real package name. 7178 if (ps == null) { 7179 ps = mSettings.getPackageLPr(pkg.packageName); 7180 } 7181 // Check to see if this package could be hiding/updating a system 7182 // package. Must look for it either under the original or real 7183 // package name depending on our state. 7184 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7185 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7186 7187 // If this is a package we don't know about on the system partition, we 7188 // may need to remove disabled child packages on the system partition 7189 // or may need to not add child packages if the parent apk is updated 7190 // on the data partition and no longer defines this child package. 7191 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7192 // If this is a parent package for an updated system app and this system 7193 // app got an OTA update which no longer defines some of the child packages 7194 // we have to prune them from the disabled system packages. 7195 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7196 if (disabledPs != null) { 7197 final int scannedChildCount = (pkg.childPackages != null) 7198 ? pkg.childPackages.size() : 0; 7199 final int disabledChildCount = disabledPs.childPackageNames != null 7200 ? disabledPs.childPackageNames.size() : 0; 7201 for (int i = 0; i < disabledChildCount; i++) { 7202 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7203 boolean disabledPackageAvailable = false; 7204 for (int j = 0; j < scannedChildCount; j++) { 7205 PackageParser.Package childPkg = pkg.childPackages.get(j); 7206 if (childPkg.packageName.equals(disabledChildPackageName)) { 7207 disabledPackageAvailable = true; 7208 break; 7209 } 7210 } 7211 if (!disabledPackageAvailable) { 7212 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7213 } 7214 } 7215 } 7216 } 7217 } 7218 7219 boolean updatedPkgBetter = false; 7220 // First check if this is a system package that may involve an update 7221 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7222 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7223 // it needs to drop FLAG_PRIVILEGED. 7224 if (locationIsPrivileged(scanFile)) { 7225 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7226 } else { 7227 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7228 } 7229 7230 if (ps != null && !ps.codePath.equals(scanFile)) { 7231 // The path has changed from what was last scanned... check the 7232 // version of the new path against what we have stored to determine 7233 // what to do. 7234 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7235 if (pkg.mVersionCode <= ps.versionCode) { 7236 // The system package has been updated and the code path does not match 7237 // Ignore entry. Skip it. 7238 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7239 + " ignored: updated version " + ps.versionCode 7240 + " better than this " + pkg.mVersionCode); 7241 if (!updatedPkg.codePath.equals(scanFile)) { 7242 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7243 + ps.name + " changing from " + updatedPkg.codePathString 7244 + " to " + scanFile); 7245 updatedPkg.codePath = scanFile; 7246 updatedPkg.codePathString = scanFile.toString(); 7247 updatedPkg.resourcePath = scanFile; 7248 updatedPkg.resourcePathString = scanFile.toString(); 7249 } 7250 updatedPkg.pkg = pkg; 7251 updatedPkg.versionCode = pkg.mVersionCode; 7252 7253 // Update the disabled system child packages to point to the package too. 7254 final int childCount = updatedPkg.childPackageNames != null 7255 ? updatedPkg.childPackageNames.size() : 0; 7256 for (int i = 0; i < childCount; i++) { 7257 String childPackageName = updatedPkg.childPackageNames.get(i); 7258 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7259 childPackageName); 7260 if (updatedChildPkg != null) { 7261 updatedChildPkg.pkg = pkg; 7262 updatedChildPkg.versionCode = pkg.mVersionCode; 7263 } 7264 } 7265 7266 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7267 + scanFile + " ignored: updated version " + ps.versionCode 7268 + " better than this " + pkg.mVersionCode); 7269 } else { 7270 // The current app on the system partition is better than 7271 // what we have updated to on the data partition; switch 7272 // back to the system partition version. 7273 // At this point, its safely assumed that package installation for 7274 // apps in system partition will go through. If not there won't be a working 7275 // version of the app 7276 // writer 7277 synchronized (mPackages) { 7278 // Just remove the loaded entries from package lists. 7279 mPackages.remove(ps.name); 7280 } 7281 7282 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7283 + " reverting from " + ps.codePathString 7284 + ": new version " + pkg.mVersionCode 7285 + " better than installed " + ps.versionCode); 7286 7287 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7288 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7289 synchronized (mInstallLock) { 7290 args.cleanUpResourcesLI(); 7291 } 7292 synchronized (mPackages) { 7293 mSettings.enableSystemPackageLPw(ps.name); 7294 } 7295 updatedPkgBetter = true; 7296 } 7297 } 7298 } 7299 7300 if (updatedPkg != null) { 7301 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7302 // initially 7303 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7304 7305 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7306 // flag set initially 7307 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7308 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7309 } 7310 } 7311 7312 // Verify certificates against what was last scanned 7313 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7314 7315 /* 7316 * A new system app appeared, but we already had a non-system one of the 7317 * same name installed earlier. 7318 */ 7319 boolean shouldHideSystemApp = false; 7320 if (updatedPkg == null && ps != null 7321 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7322 /* 7323 * Check to make sure the signatures match first. If they don't, 7324 * wipe the installed application and its data. 7325 */ 7326 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7327 != PackageManager.SIGNATURE_MATCH) { 7328 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7329 + " signatures don't match existing userdata copy; removing"); 7330 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7331 "scanPackageInternalLI")) { 7332 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7333 } 7334 ps = null; 7335 } else { 7336 /* 7337 * If the newly-added system app is an older version than the 7338 * already installed version, hide it. It will be scanned later 7339 * and re-added like an update. 7340 */ 7341 if (pkg.mVersionCode <= ps.versionCode) { 7342 shouldHideSystemApp = true; 7343 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7344 + " but new version " + pkg.mVersionCode + " better than installed " 7345 + ps.versionCode + "; hiding system"); 7346 } else { 7347 /* 7348 * The newly found system app is a newer version that the 7349 * one previously installed. Simply remove the 7350 * already-installed application and replace it with our own 7351 * while keeping the application data. 7352 */ 7353 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7354 + " reverting from " + ps.codePathString + ": new version " 7355 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7356 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7357 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7358 synchronized (mInstallLock) { 7359 args.cleanUpResourcesLI(); 7360 } 7361 } 7362 } 7363 } 7364 7365 // The apk is forward locked (not public) if its code and resources 7366 // are kept in different files. (except for app in either system or 7367 // vendor path). 7368 // TODO grab this value from PackageSettings 7369 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7370 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7371 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7372 } 7373 } 7374 7375 // TODO: extend to support forward-locked splits 7376 String resourcePath = null; 7377 String baseResourcePath = null; 7378 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7379 if (ps != null && ps.resourcePathString != null) { 7380 resourcePath = ps.resourcePathString; 7381 baseResourcePath = ps.resourcePathString; 7382 } else { 7383 // Should not happen at all. Just log an error. 7384 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7385 } 7386 } else { 7387 resourcePath = pkg.codePath; 7388 baseResourcePath = pkg.baseCodePath; 7389 } 7390 7391 // Set application objects path explicitly. 7392 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7393 pkg.setApplicationInfoCodePath(pkg.codePath); 7394 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7395 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7396 pkg.setApplicationInfoResourcePath(resourcePath); 7397 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7398 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7399 7400 // Note that we invoke the following method only if we are about to unpack an application 7401 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7402 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7403 7404 /* 7405 * If the system app should be overridden by a previously installed 7406 * data, hide the system app now and let the /data/app scan pick it up 7407 * again. 7408 */ 7409 if (shouldHideSystemApp) { 7410 synchronized (mPackages) { 7411 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7412 } 7413 } 7414 7415 return scannedPkg; 7416 } 7417 7418 private static String fixProcessName(String defProcessName, 7419 String processName) { 7420 if (processName == null) { 7421 return defProcessName; 7422 } 7423 return processName; 7424 } 7425 7426 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7427 throws PackageManagerException { 7428 if (pkgSetting.signatures.mSignatures != null) { 7429 // Already existing package. Make sure signatures match 7430 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7431 == PackageManager.SIGNATURE_MATCH; 7432 if (!match) { 7433 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7434 == PackageManager.SIGNATURE_MATCH; 7435 } 7436 if (!match) { 7437 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7438 == PackageManager.SIGNATURE_MATCH; 7439 } 7440 if (!match) { 7441 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7442 + pkg.packageName + " signatures do not match the " 7443 + "previously installed version; ignoring!"); 7444 } 7445 } 7446 7447 // Check for shared user signatures 7448 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7449 // Already existing package. Make sure signatures match 7450 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7451 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7452 if (!match) { 7453 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7454 == PackageManager.SIGNATURE_MATCH; 7455 } 7456 if (!match) { 7457 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7458 == PackageManager.SIGNATURE_MATCH; 7459 } 7460 if (!match) { 7461 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7462 "Package " + pkg.packageName 7463 + " has no signatures that match those in shared user " 7464 + pkgSetting.sharedUser.name + "; ignoring!"); 7465 } 7466 } 7467 } 7468 7469 /** 7470 * Enforces that only the system UID or root's UID can call a method exposed 7471 * via Binder. 7472 * 7473 * @param message used as message if SecurityException is thrown 7474 * @throws SecurityException if the caller is not system or root 7475 */ 7476 private static final void enforceSystemOrRoot(String message) { 7477 final int uid = Binder.getCallingUid(); 7478 if (uid != Process.SYSTEM_UID && uid != 0) { 7479 throw new SecurityException(message); 7480 } 7481 } 7482 7483 @Override 7484 public void performFstrimIfNeeded() { 7485 enforceSystemOrRoot("Only the system can request fstrim"); 7486 7487 // Before everything else, see whether we need to fstrim. 7488 try { 7489 IStorageManager sm = PackageHelper.getStorageManager(); 7490 if (sm != null) { 7491 boolean doTrim = false; 7492 final long interval = android.provider.Settings.Global.getLong( 7493 mContext.getContentResolver(), 7494 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7495 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7496 if (interval > 0) { 7497 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7498 if (timeSinceLast > interval) { 7499 doTrim = true; 7500 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7501 + "; running immediately"); 7502 } 7503 } 7504 if (doTrim) { 7505 final boolean dexOptDialogShown; 7506 synchronized (mPackages) { 7507 dexOptDialogShown = mDexOptDialogShown; 7508 } 7509 if (!isFirstBoot() && dexOptDialogShown) { 7510 try { 7511 ActivityManager.getService().showBootMessage( 7512 mContext.getResources().getString( 7513 R.string.android_upgrading_fstrim), true); 7514 } catch (RemoteException e) { 7515 } 7516 } 7517 sm.runMaintenance(); 7518 } 7519 } else { 7520 Slog.e(TAG, "storageManager service unavailable!"); 7521 } 7522 } catch (RemoteException e) { 7523 // Can't happen; StorageManagerService is local 7524 } 7525 } 7526 7527 @Override 7528 public void updatePackagesIfNeeded() { 7529 enforceSystemOrRoot("Only the system can request package update"); 7530 7531 // We need to re-extract after an OTA. 7532 boolean causeUpgrade = isUpgrade(); 7533 7534 // First boot or factory reset. 7535 // Note: we also handle devices that are upgrading to N right now as if it is their 7536 // first boot, as they do not have profile data. 7537 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7538 7539 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7540 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7541 7542 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7543 return; 7544 } 7545 7546 List<PackageParser.Package> pkgs; 7547 synchronized (mPackages) { 7548 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7549 } 7550 7551 final long startTime = System.nanoTime(); 7552 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7553 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7554 7555 final int elapsedTimeSeconds = 7556 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7557 7558 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7559 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7560 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7561 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7562 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7563 } 7564 7565 /** 7566 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7567 * containing statistics about the invocation. The array consists of three elements, 7568 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7569 * and {@code numberOfPackagesFailed}. 7570 */ 7571 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7572 String compilerFilter) { 7573 7574 int numberOfPackagesVisited = 0; 7575 int numberOfPackagesOptimized = 0; 7576 int numberOfPackagesSkipped = 0; 7577 int numberOfPackagesFailed = 0; 7578 final int numberOfPackagesToDexopt = pkgs.size(); 7579 7580 for (PackageParser.Package pkg : pkgs) { 7581 numberOfPackagesVisited++; 7582 7583 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7584 if (DEBUG_DEXOPT) { 7585 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7586 } 7587 numberOfPackagesSkipped++; 7588 continue; 7589 } 7590 7591 if (DEBUG_DEXOPT) { 7592 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7593 numberOfPackagesToDexopt + ": " + pkg.packageName); 7594 } 7595 7596 if (showDialog) { 7597 try { 7598 ActivityManager.getService().showBootMessage( 7599 mContext.getResources().getString(R.string.android_upgrading_apk, 7600 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7601 } catch (RemoteException e) { 7602 } 7603 synchronized (mPackages) { 7604 mDexOptDialogShown = true; 7605 } 7606 } 7607 7608 // If the OTA updates a system app which was previously preopted to a non-preopted state 7609 // the app might end up being verified at runtime. That's because by default the apps 7610 // are verify-profile but for preopted apps there's no profile. 7611 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7612 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7613 // filter (by default interpret-only). 7614 // Note that at this stage unused apps are already filtered. 7615 if (isSystemApp(pkg) && 7616 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7617 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7618 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7619 } 7620 7621 // checkProfiles is false to avoid merging profiles during boot which 7622 // might interfere with background compilation (b/28612421). 7623 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7624 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7625 // trade-off worth doing to save boot time work. 7626 int dexOptStatus = performDexOptTraced(pkg.packageName, 7627 false /* checkProfiles */, 7628 compilerFilter, 7629 false /* force */); 7630 switch (dexOptStatus) { 7631 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7632 numberOfPackagesOptimized++; 7633 break; 7634 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7635 numberOfPackagesSkipped++; 7636 break; 7637 case PackageDexOptimizer.DEX_OPT_FAILED: 7638 numberOfPackagesFailed++; 7639 break; 7640 default: 7641 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7642 break; 7643 } 7644 } 7645 7646 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7647 numberOfPackagesFailed }; 7648 } 7649 7650 @Override 7651 public void notifyPackageUse(String packageName, int reason) { 7652 synchronized (mPackages) { 7653 PackageParser.Package p = mPackages.get(packageName); 7654 if (p == null) { 7655 return; 7656 } 7657 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7658 } 7659 } 7660 7661 @Override 7662 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7663 int userId = UserHandle.getCallingUserId(); 7664 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7665 if (ai == null) { 7666 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7667 + loadingPackageName + ", user=" + userId); 7668 return; 7669 } 7670 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7671 } 7672 7673 // TODO: this is not used nor needed. Delete it. 7674 @Override 7675 public boolean performDexOptIfNeeded(String packageName) { 7676 int dexOptStatus = performDexOptTraced(packageName, 7677 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7678 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7679 } 7680 7681 @Override 7682 public boolean performDexOpt(String packageName, 7683 boolean checkProfiles, int compileReason, boolean force) { 7684 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7685 getCompilerFilterForReason(compileReason), force); 7686 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7687 } 7688 7689 @Override 7690 public boolean performDexOptMode(String packageName, 7691 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7692 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7693 targetCompilerFilter, force); 7694 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7695 } 7696 7697 private int performDexOptTraced(String packageName, 7698 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7699 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7700 try { 7701 return performDexOptInternal(packageName, checkProfiles, 7702 targetCompilerFilter, force); 7703 } finally { 7704 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7705 } 7706 } 7707 7708 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7709 // if the package can now be considered up to date for the given filter. 7710 private int performDexOptInternal(String packageName, 7711 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7712 PackageParser.Package p; 7713 synchronized (mPackages) { 7714 p = mPackages.get(packageName); 7715 if (p == null) { 7716 // Package could not be found. Report failure. 7717 return PackageDexOptimizer.DEX_OPT_FAILED; 7718 } 7719 mPackageUsage.maybeWriteAsync(mPackages); 7720 mCompilerStats.maybeWriteAsync(); 7721 } 7722 long callingId = Binder.clearCallingIdentity(); 7723 try { 7724 synchronized (mInstallLock) { 7725 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7726 targetCompilerFilter, force); 7727 } 7728 } finally { 7729 Binder.restoreCallingIdentity(callingId); 7730 } 7731 } 7732 7733 public ArraySet<String> getOptimizablePackages() { 7734 ArraySet<String> pkgs = new ArraySet<String>(); 7735 synchronized (mPackages) { 7736 for (PackageParser.Package p : mPackages.values()) { 7737 if (PackageDexOptimizer.canOptimizePackage(p)) { 7738 pkgs.add(p.packageName); 7739 } 7740 } 7741 } 7742 return pkgs; 7743 } 7744 7745 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7746 boolean checkProfiles, String targetCompilerFilter, 7747 boolean force) { 7748 // Select the dex optimizer based on the force parameter. 7749 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7750 // allocate an object here. 7751 PackageDexOptimizer pdo = force 7752 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7753 : mPackageDexOptimizer; 7754 7755 // Optimize all dependencies first. Note: we ignore the return value and march on 7756 // on errors. 7757 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7758 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7759 if (!deps.isEmpty()) { 7760 for (PackageParser.Package depPackage : deps) { 7761 // TODO: Analyze and investigate if we (should) profile libraries. 7762 // Currently this will do a full compilation of the library by default. 7763 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7764 false /* checkProfiles */, 7765 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7766 getOrCreateCompilerPackageStats(depPackage)); 7767 } 7768 } 7769 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7770 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7771 } 7772 7773 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7774 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7775 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7776 Set<String> collectedNames = new HashSet<>(); 7777 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7778 7779 retValue.remove(p); 7780 7781 return retValue; 7782 } else { 7783 return Collections.emptyList(); 7784 } 7785 } 7786 7787 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7788 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7789 if (!collectedNames.contains(p.packageName)) { 7790 collectedNames.add(p.packageName); 7791 collected.add(p); 7792 7793 if (p.usesLibraries != null) { 7794 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7795 } 7796 if (p.usesOptionalLibraries != null) { 7797 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7798 collectedNames); 7799 } 7800 } 7801 } 7802 7803 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7804 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7805 for (String libName : libs) { 7806 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7807 if (libPkg != null) { 7808 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7809 } 7810 } 7811 } 7812 7813 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7814 synchronized (mPackages) { 7815 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7816 if (lib != null && lib.apk != null) { 7817 return mPackages.get(lib.apk); 7818 } 7819 } 7820 return null; 7821 } 7822 7823 public void shutdown() { 7824 mPackageUsage.writeNow(mPackages); 7825 mCompilerStats.writeNow(); 7826 } 7827 7828 @Override 7829 public void dumpProfiles(String packageName) { 7830 PackageParser.Package pkg; 7831 synchronized (mPackages) { 7832 pkg = mPackages.get(packageName); 7833 if (pkg == null) { 7834 throw new IllegalArgumentException("Unknown package: " + packageName); 7835 } 7836 } 7837 /* Only the shell, root, or the app user should be able to dump profiles. */ 7838 int callingUid = Binder.getCallingUid(); 7839 if (callingUid != Process.SHELL_UID && 7840 callingUid != Process.ROOT_UID && 7841 callingUid != pkg.applicationInfo.uid) { 7842 throw new SecurityException("dumpProfiles"); 7843 } 7844 7845 synchronized (mInstallLock) { 7846 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7847 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7848 try { 7849 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7850 String codePaths = TextUtils.join(";", allCodePaths); 7851 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7852 } catch (InstallerException e) { 7853 Slog.w(TAG, "Failed to dump profiles", e); 7854 } 7855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7856 } 7857 } 7858 7859 @Override 7860 public void forceDexOpt(String packageName) { 7861 enforceSystemOrRoot("forceDexOpt"); 7862 7863 PackageParser.Package pkg; 7864 synchronized (mPackages) { 7865 pkg = mPackages.get(packageName); 7866 if (pkg == null) { 7867 throw new IllegalArgumentException("Unknown package: " + packageName); 7868 } 7869 } 7870 7871 synchronized (mInstallLock) { 7872 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7873 7874 // Whoever is calling forceDexOpt wants a fully compiled package. 7875 // Don't use profiles since that may cause compilation to be skipped. 7876 final int res = performDexOptInternalWithDependenciesLI(pkg, 7877 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7878 true /* force */); 7879 7880 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7881 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7882 throw new IllegalStateException("Failed to dexopt: " + res); 7883 } 7884 } 7885 } 7886 7887 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7888 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7889 Slog.w(TAG, "Unable to update from " + oldPkg.name 7890 + " to " + newPkg.packageName 7891 + ": old package not in system partition"); 7892 return false; 7893 } else if (mPackages.get(oldPkg.name) != null) { 7894 Slog.w(TAG, "Unable to update from " + oldPkg.name 7895 + " to " + newPkg.packageName 7896 + ": old package still exists"); 7897 return false; 7898 } 7899 return true; 7900 } 7901 7902 void removeCodePathLI(File codePath) { 7903 if (codePath.isDirectory()) { 7904 try { 7905 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7906 } catch (InstallerException e) { 7907 Slog.w(TAG, "Failed to remove code path", e); 7908 } 7909 } else { 7910 codePath.delete(); 7911 } 7912 } 7913 7914 private int[] resolveUserIds(int userId) { 7915 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7916 } 7917 7918 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7919 if (pkg == null) { 7920 Slog.wtf(TAG, "Package was null!", new Throwable()); 7921 return; 7922 } 7923 clearAppDataLeafLIF(pkg, userId, flags); 7924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7925 for (int i = 0; i < childCount; i++) { 7926 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7927 } 7928 } 7929 7930 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7931 final PackageSetting ps; 7932 synchronized (mPackages) { 7933 ps = mSettings.mPackages.get(pkg.packageName); 7934 } 7935 for (int realUserId : resolveUserIds(userId)) { 7936 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7937 try { 7938 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7939 ceDataInode); 7940 } catch (InstallerException e) { 7941 Slog.w(TAG, String.valueOf(e)); 7942 } 7943 } 7944 } 7945 7946 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7947 if (pkg == null) { 7948 Slog.wtf(TAG, "Package was null!", new Throwable()); 7949 return; 7950 } 7951 destroyAppDataLeafLIF(pkg, userId, flags); 7952 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7953 for (int i = 0; i < childCount; i++) { 7954 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7955 } 7956 } 7957 7958 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7959 final PackageSetting ps; 7960 synchronized (mPackages) { 7961 ps = mSettings.mPackages.get(pkg.packageName); 7962 } 7963 for (int realUserId : resolveUserIds(userId)) { 7964 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7965 try { 7966 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7967 ceDataInode); 7968 } catch (InstallerException e) { 7969 Slog.w(TAG, String.valueOf(e)); 7970 } 7971 } 7972 } 7973 7974 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7975 if (pkg == null) { 7976 Slog.wtf(TAG, "Package was null!", new Throwable()); 7977 return; 7978 } 7979 destroyAppProfilesLeafLIF(pkg); 7980 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7981 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7982 for (int i = 0; i < childCount; i++) { 7983 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7984 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7985 true /* removeBaseMarker */); 7986 } 7987 } 7988 7989 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7990 boolean removeBaseMarker) { 7991 if (pkg.isForwardLocked()) { 7992 return; 7993 } 7994 7995 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7996 try { 7997 path = PackageManagerServiceUtils.realpath(new File(path)); 7998 } catch (IOException e) { 7999 // TODO: Should we return early here ? 8000 Slog.w(TAG, "Failed to get canonical path", e); 8001 continue; 8002 } 8003 8004 final String useMarker = path.replace('/', '@'); 8005 for (int realUserId : resolveUserIds(userId)) { 8006 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8007 if (removeBaseMarker) { 8008 File foreignUseMark = new File(profileDir, useMarker); 8009 if (foreignUseMark.exists()) { 8010 if (!foreignUseMark.delete()) { 8011 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8012 + pkg.packageName); 8013 } 8014 } 8015 } 8016 8017 File[] markers = profileDir.listFiles(); 8018 if (markers != null) { 8019 final String searchString = "@" + pkg.packageName + "@"; 8020 // We also delete all markers that contain the package name we're 8021 // uninstalling. These are associated with secondary dex-files belonging 8022 // to the package. Reconstructing the path of these dex files is messy 8023 // in general. 8024 for (File marker : markers) { 8025 if (marker.getName().indexOf(searchString) > 0) { 8026 if (!marker.delete()) { 8027 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8028 + pkg.packageName); 8029 } 8030 } 8031 } 8032 } 8033 } 8034 } 8035 } 8036 8037 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8038 try { 8039 mInstaller.destroyAppProfiles(pkg.packageName); 8040 } catch (InstallerException e) { 8041 Slog.w(TAG, String.valueOf(e)); 8042 } 8043 } 8044 8045 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8046 if (pkg == null) { 8047 Slog.wtf(TAG, "Package was null!", new Throwable()); 8048 return; 8049 } 8050 clearAppProfilesLeafLIF(pkg); 8051 // We don't remove the base foreign use marker when clearing profiles because 8052 // we will rename it when the app is updated. Unlike the actual profile contents, 8053 // the foreign use marker is good across installs. 8054 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8055 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8056 for (int i = 0; i < childCount; i++) { 8057 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8058 } 8059 } 8060 8061 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8062 try { 8063 mInstaller.clearAppProfiles(pkg.packageName); 8064 } catch (InstallerException e) { 8065 Slog.w(TAG, String.valueOf(e)); 8066 } 8067 } 8068 8069 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8070 long lastUpdateTime) { 8071 // Set parent install/update time 8072 PackageSetting ps = (PackageSetting) pkg.mExtras; 8073 if (ps != null) { 8074 ps.firstInstallTime = firstInstallTime; 8075 ps.lastUpdateTime = lastUpdateTime; 8076 } 8077 // Set children install/update time 8078 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8079 for (int i = 0; i < childCount; i++) { 8080 PackageParser.Package childPkg = pkg.childPackages.get(i); 8081 ps = (PackageSetting) childPkg.mExtras; 8082 if (ps != null) { 8083 ps.firstInstallTime = firstInstallTime; 8084 ps.lastUpdateTime = lastUpdateTime; 8085 } 8086 } 8087 } 8088 8089 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8090 PackageParser.Package changingLib) { 8091 if (file.path != null) { 8092 usesLibraryFiles.add(file.path); 8093 return; 8094 } 8095 PackageParser.Package p = mPackages.get(file.apk); 8096 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8097 // If we are doing this while in the middle of updating a library apk, 8098 // then we need to make sure to use that new apk for determining the 8099 // dependencies here. (We haven't yet finished committing the new apk 8100 // to the package manager state.) 8101 if (p == null || p.packageName.equals(changingLib.packageName)) { 8102 p = changingLib; 8103 } 8104 } 8105 if (p != null) { 8106 usesLibraryFiles.addAll(p.getAllCodePaths()); 8107 } 8108 } 8109 8110 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8111 PackageParser.Package changingLib) throws PackageManagerException { 8112 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8113 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8114 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8115 for (int i=0; i<N; i++) { 8116 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8117 if (file == null) { 8118 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8119 "Package " + pkg.packageName + " requires unavailable shared library " 8120 + pkg.usesLibraries.get(i) + "; failing!"); 8121 } 8122 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8123 } 8124 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8125 for (int i=0; i<N; i++) { 8126 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8127 if (file == null) { 8128 Slog.w(TAG, "Package " + pkg.packageName 8129 + " desires unavailable shared library " 8130 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8131 } else { 8132 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8133 } 8134 } 8135 N = usesLibraryFiles.size(); 8136 if (N > 0) { 8137 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8138 } else { 8139 pkg.usesLibraryFiles = null; 8140 } 8141 } 8142 } 8143 8144 private static boolean hasString(List<String> list, List<String> which) { 8145 if (list == null) { 8146 return false; 8147 } 8148 for (int i=list.size()-1; i>=0; i--) { 8149 for (int j=which.size()-1; j>=0; j--) { 8150 if (which.get(j).equals(list.get(i))) { 8151 return true; 8152 } 8153 } 8154 } 8155 return false; 8156 } 8157 8158 private void updateAllSharedLibrariesLPw() { 8159 for (PackageParser.Package pkg : mPackages.values()) { 8160 try { 8161 updateSharedLibrariesLPr(pkg, null); 8162 } catch (PackageManagerException e) { 8163 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8164 } 8165 } 8166 } 8167 8168 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8169 PackageParser.Package changingPkg) { 8170 ArrayList<PackageParser.Package> res = null; 8171 for (PackageParser.Package pkg : mPackages.values()) { 8172 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8173 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8174 if (res == null) { 8175 res = new ArrayList<PackageParser.Package>(); 8176 } 8177 res.add(pkg); 8178 try { 8179 updateSharedLibrariesLPr(pkg, changingPkg); 8180 } catch (PackageManagerException e) { 8181 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8182 } 8183 } 8184 } 8185 return res; 8186 } 8187 8188 /** 8189 * Derive the value of the {@code cpuAbiOverride} based on the provided 8190 * value and an optional stored value from the package settings. 8191 */ 8192 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8193 String cpuAbiOverride = null; 8194 8195 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8196 cpuAbiOverride = null; 8197 } else if (abiOverride != null) { 8198 cpuAbiOverride = abiOverride; 8199 } else if (settings != null) { 8200 cpuAbiOverride = settings.cpuAbiOverrideString; 8201 } 8202 8203 return cpuAbiOverride; 8204 } 8205 8206 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8207 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8208 throws PackageManagerException { 8209 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8210 // If the package has children and this is the first dive in the function 8211 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8212 // whether all packages (parent and children) would be successfully scanned 8213 // before the actual scan since scanning mutates internal state and we want 8214 // to atomically install the package and its children. 8215 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8216 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8217 scanFlags |= SCAN_CHECK_ONLY; 8218 } 8219 } else { 8220 scanFlags &= ~SCAN_CHECK_ONLY; 8221 } 8222 8223 final PackageParser.Package scannedPkg; 8224 try { 8225 // Scan the parent 8226 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8227 // Scan the children 8228 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8229 for (int i = 0; i < childCount; i++) { 8230 PackageParser.Package childPkg = pkg.childPackages.get(i); 8231 scanPackageLI(childPkg, policyFlags, 8232 scanFlags, currentTime, user); 8233 } 8234 } finally { 8235 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8236 } 8237 8238 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8239 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8240 } 8241 8242 return scannedPkg; 8243 } 8244 8245 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8246 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8247 boolean success = false; 8248 try { 8249 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8250 currentTime, user); 8251 success = true; 8252 return res; 8253 } finally { 8254 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8255 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8256 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8257 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8258 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8259 } 8260 } 8261 } 8262 8263 /** 8264 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8265 */ 8266 private static boolean apkHasCode(String fileName) { 8267 StrictJarFile jarFile = null; 8268 try { 8269 jarFile = new StrictJarFile(fileName, 8270 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8271 return jarFile.findEntry("classes.dex") != null; 8272 } catch (IOException ignore) { 8273 } finally { 8274 try { 8275 if (jarFile != null) { 8276 jarFile.close(); 8277 } 8278 } catch (IOException ignore) {} 8279 } 8280 return false; 8281 } 8282 8283 /** 8284 * Enforces code policy for the package. This ensures that if an APK has 8285 * declared hasCode="true" in its manifest that the APK actually contains 8286 * code. 8287 * 8288 * @throws PackageManagerException If bytecode could not be found when it should exist 8289 */ 8290 private static void assertCodePolicy(PackageParser.Package pkg) 8291 throws PackageManagerException { 8292 final boolean shouldHaveCode = 8293 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8294 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8295 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8296 "Package " + pkg.baseCodePath + " code is missing"); 8297 } 8298 8299 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8300 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8301 final boolean splitShouldHaveCode = 8302 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8303 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8304 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8305 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8306 } 8307 } 8308 } 8309 } 8310 8311 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8312 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8313 throws PackageManagerException { 8314 if (DEBUG_PACKAGE_SCANNING) { 8315 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8316 Log.d(TAG, "Scanning package " + pkg.packageName); 8317 } 8318 8319 applyPolicy(pkg, policyFlags); 8320 8321 assertPackageIsValid(pkg, policyFlags, scanFlags); 8322 8323 // Initialize package source and resource directories 8324 final File scanFile = new File(pkg.codePath); 8325 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8326 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8327 8328 SharedUserSetting suid = null; 8329 PackageSetting pkgSetting = null; 8330 8331 // Getting the package setting may have a side-effect, so if we 8332 // are only checking if scan would succeed, stash a copy of the 8333 // old setting to restore at the end. 8334 PackageSetting nonMutatedPs = null; 8335 8336 // We keep references to the derived CPU Abis from settings in oder to reuse 8337 // them in the case where we're not upgrading or booting for the first time. 8338 String primaryCpuAbiFromSettings = null; 8339 String secondaryCpuAbiFromSettings = null; 8340 8341 // writer 8342 synchronized (mPackages) { 8343 if (pkg.mSharedUserId != null) { 8344 // SIDE EFFECTS; may potentially allocate a new shared user 8345 suid = mSettings.getSharedUserLPw( 8346 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8347 if (DEBUG_PACKAGE_SCANNING) { 8348 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8349 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8350 + "): packages=" + suid.packages); 8351 } 8352 } 8353 8354 // Check if we are renaming from an original package name. 8355 PackageSetting origPackage = null; 8356 String realName = null; 8357 if (pkg.mOriginalPackages != null) { 8358 // This package may need to be renamed to a previously 8359 // installed name. Let's check on that... 8360 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8361 if (pkg.mOriginalPackages.contains(renamed)) { 8362 // This package had originally been installed as the 8363 // original name, and we have already taken care of 8364 // transitioning to the new one. Just update the new 8365 // one to continue using the old name. 8366 realName = pkg.mRealPackage; 8367 if (!pkg.packageName.equals(renamed)) { 8368 // Callers into this function may have already taken 8369 // care of renaming the package; only do it here if 8370 // it is not already done. 8371 pkg.setPackageName(renamed); 8372 } 8373 } else { 8374 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8375 if ((origPackage = mSettings.getPackageLPr( 8376 pkg.mOriginalPackages.get(i))) != null) { 8377 // We do have the package already installed under its 8378 // original name... should we use it? 8379 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8380 // New package is not compatible with original. 8381 origPackage = null; 8382 continue; 8383 } else if (origPackage.sharedUser != null) { 8384 // Make sure uid is compatible between packages. 8385 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8386 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8387 + " to " + pkg.packageName + ": old uid " 8388 + origPackage.sharedUser.name 8389 + " differs from " + pkg.mSharedUserId); 8390 origPackage = null; 8391 continue; 8392 } 8393 // TODO: Add case when shared user id is added [b/28144775] 8394 } else { 8395 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8396 + pkg.packageName + " to old name " + origPackage.name); 8397 } 8398 break; 8399 } 8400 } 8401 } 8402 } 8403 8404 if (mTransferedPackages.contains(pkg.packageName)) { 8405 Slog.w(TAG, "Package " + pkg.packageName 8406 + " was transferred to another, but its .apk remains"); 8407 } 8408 8409 // See comments in nonMutatedPs declaration 8410 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8411 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8412 if (foundPs != null) { 8413 nonMutatedPs = new PackageSetting(foundPs); 8414 } 8415 } 8416 8417 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8418 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8419 if (foundPs != null) { 8420 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8421 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8422 } 8423 } 8424 8425 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8426 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8427 PackageManagerService.reportSettingsProblem(Log.WARN, 8428 "Package " + pkg.packageName + " shared user changed from " 8429 + (pkgSetting.sharedUser != null 8430 ? pkgSetting.sharedUser.name : "<nothing>") 8431 + " to " 8432 + (suid != null ? suid.name : "<nothing>") 8433 + "; replacing with new"); 8434 pkgSetting = null; 8435 } 8436 final PackageSetting oldPkgSetting = 8437 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8438 final PackageSetting disabledPkgSetting = 8439 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8440 if (pkgSetting == null) { 8441 final String parentPackageName = (pkg.parentPackage != null) 8442 ? pkg.parentPackage.packageName : null; 8443 // REMOVE SharedUserSetting from method; update in a separate call 8444 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8445 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8446 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8447 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8448 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8449 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8450 UserManagerService.getInstance()); 8451 // SIDE EFFECTS; updates system state; move elsewhere 8452 if (origPackage != null) { 8453 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8454 } 8455 mSettings.addUserToSettingLPw(pkgSetting); 8456 } else { 8457 // REMOVE SharedUserSetting from method; update in a separate call. 8458 // 8459 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8460 // secondaryCpuAbi are not known at this point so we always update them 8461 // to null here, only to reset them at a later point. 8462 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8463 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8464 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8465 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8466 UserManagerService.getInstance()); 8467 } 8468 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8469 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8470 8471 // SIDE EFFECTS; modifies system state; move elsewhere 8472 if (pkgSetting.origPackage != null) { 8473 // If we are first transitioning from an original package, 8474 // fix up the new package's name now. We need to do this after 8475 // looking up the package under its new name, so getPackageLP 8476 // can take care of fiddling things correctly. 8477 pkg.setPackageName(origPackage.name); 8478 8479 // File a report about this. 8480 String msg = "New package " + pkgSetting.realName 8481 + " renamed to replace old package " + pkgSetting.name; 8482 reportSettingsProblem(Log.WARN, msg); 8483 8484 // Make a note of it. 8485 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8486 mTransferedPackages.add(origPackage.name); 8487 } 8488 8489 // No longer need to retain this. 8490 pkgSetting.origPackage = null; 8491 } 8492 8493 // SIDE EFFECTS; modifies system state; move elsewhere 8494 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8495 // Make a note of it. 8496 mTransferedPackages.add(pkg.packageName); 8497 } 8498 8499 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8500 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8501 } 8502 8503 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8504 // Check all shared libraries and map to their actual file path. 8505 // We only do this here for apps not on a system dir, because those 8506 // are the only ones that can fail an install due to this. We 8507 // will take care of the system apps by updating all of their 8508 // library paths after the scan is done. 8509 updateSharedLibrariesLPr(pkg, null); 8510 } 8511 8512 if (mFoundPolicyFile) { 8513 SELinuxMMAC.assignSeinfoValue(pkg); 8514 } 8515 8516 pkg.applicationInfo.uid = pkgSetting.appId; 8517 pkg.mExtras = pkgSetting; 8518 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8519 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8520 // We just determined the app is signed correctly, so bring 8521 // over the latest parsed certs. 8522 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8523 } else { 8524 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8525 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8526 "Package " + pkg.packageName + " upgrade keys do not match the " 8527 + "previously installed version"); 8528 } else { 8529 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8530 String msg = "System package " + pkg.packageName 8531 + " signature changed; retaining data."; 8532 reportSettingsProblem(Log.WARN, msg); 8533 } 8534 } 8535 } else { 8536 try { 8537 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8538 verifySignaturesLP(pkgSetting, pkg); 8539 // We just determined the app is signed correctly, so bring 8540 // over the latest parsed certs. 8541 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8542 } catch (PackageManagerException e) { 8543 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8544 throw e; 8545 } 8546 // The signature has changed, but this package is in the system 8547 // image... let's recover! 8548 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8549 // However... if this package is part of a shared user, but it 8550 // doesn't match the signature of the shared user, let's fail. 8551 // What this means is that you can't change the signatures 8552 // associated with an overall shared user, which doesn't seem all 8553 // that unreasonable. 8554 if (pkgSetting.sharedUser != null) { 8555 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8556 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8557 throw new PackageManagerException( 8558 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8559 "Signature mismatch for shared user: " 8560 + pkgSetting.sharedUser); 8561 } 8562 } 8563 // File a report about this. 8564 String msg = "System package " + pkg.packageName 8565 + " signature changed; retaining data."; 8566 reportSettingsProblem(Log.WARN, msg); 8567 } 8568 } 8569 8570 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8571 // This package wants to adopt ownership of permissions from 8572 // another package. 8573 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8574 final String origName = pkg.mAdoptPermissions.get(i); 8575 final PackageSetting orig = mSettings.getPackageLPr(origName); 8576 if (orig != null) { 8577 if (verifyPackageUpdateLPr(orig, pkg)) { 8578 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8579 + pkg.packageName); 8580 // SIDE EFFECTS; updates permissions system state; move elsewhere 8581 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8582 } 8583 } 8584 } 8585 } 8586 } 8587 8588 pkg.applicationInfo.processName = fixProcessName( 8589 pkg.applicationInfo.packageName, 8590 pkg.applicationInfo.processName); 8591 8592 if (pkg != mPlatformPackage) { 8593 // Get all of our default paths setup 8594 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8595 } 8596 8597 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8598 8599 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8600 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8601 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8602 derivePackageAbi( 8603 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8604 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8605 8606 // Some system apps still use directory structure for native libraries 8607 // in which case we might end up not detecting abi solely based on apk 8608 // structure. Try to detect abi based on directory structure. 8609 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8610 pkg.applicationInfo.primaryCpuAbi == null) { 8611 setBundledAppAbisAndRoots(pkg, pkgSetting); 8612 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8613 } 8614 } else { 8615 // This is not a first boot or an upgrade, don't bother deriving the 8616 // ABI during the scan. Instead, trust the value that was stored in the 8617 // package setting. 8618 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8619 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8620 8621 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8622 8623 if (DEBUG_ABI_SELECTION) { 8624 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8625 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8626 pkg.applicationInfo.secondaryCpuAbi); 8627 } 8628 } 8629 } else { 8630 if ((scanFlags & SCAN_MOVE) != 0) { 8631 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8632 // but we already have this packages package info in the PackageSetting. We just 8633 // use that and derive the native library path based on the new codepath. 8634 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8635 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8636 } 8637 8638 // Set native library paths again. For moves, the path will be updated based on the 8639 // ABIs we've determined above. For non-moves, the path will be updated based on the 8640 // ABIs we determined during compilation, but the path will depend on the final 8641 // package path (after the rename away from the stage path). 8642 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8643 } 8644 8645 // This is a special case for the "system" package, where the ABI is 8646 // dictated by the zygote configuration (and init.rc). We should keep track 8647 // of this ABI so that we can deal with "normal" applications that run under 8648 // the same UID correctly. 8649 if (mPlatformPackage == pkg) { 8650 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8651 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8652 } 8653 8654 // If there's a mismatch between the abi-override in the package setting 8655 // and the abiOverride specified for the install. Warn about this because we 8656 // would've already compiled the app without taking the package setting into 8657 // account. 8658 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8659 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8660 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8661 " for package " + pkg.packageName); 8662 } 8663 } 8664 8665 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8666 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8667 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8668 8669 // Copy the derived override back to the parsed package, so that we can 8670 // update the package settings accordingly. 8671 pkg.cpuAbiOverride = cpuAbiOverride; 8672 8673 if (DEBUG_ABI_SELECTION) { 8674 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8675 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8676 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8677 } 8678 8679 // Push the derived path down into PackageSettings so we know what to 8680 // clean up at uninstall time. 8681 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8682 8683 if (DEBUG_ABI_SELECTION) { 8684 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8685 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8686 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8687 } 8688 8689 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8690 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8691 // We don't do this here during boot because we can do it all 8692 // at once after scanning all existing packages. 8693 // 8694 // We also do this *before* we perform dexopt on this package, so that 8695 // we can avoid redundant dexopts, and also to make sure we've got the 8696 // code and package path correct. 8697 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8698 } 8699 8700 if (mFactoryTest && pkg.requestedPermissions.contains( 8701 android.Manifest.permission.FACTORY_TEST)) { 8702 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8703 } 8704 8705 if (isSystemApp(pkg)) { 8706 pkgSetting.isOrphaned = true; 8707 } 8708 8709 // Take care of first install / last update times. 8710 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8711 if (currentTime != 0) { 8712 if (pkgSetting.firstInstallTime == 0) { 8713 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8714 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8715 pkgSetting.lastUpdateTime = currentTime; 8716 } 8717 } else if (pkgSetting.firstInstallTime == 0) { 8718 // We need *something*. Take time time stamp of the file. 8719 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8720 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8721 if (scanFileTime != pkgSetting.timeStamp) { 8722 // A package on the system image has changed; consider this 8723 // to be an update. 8724 pkgSetting.lastUpdateTime = scanFileTime; 8725 } 8726 } 8727 pkgSetting.setTimeStamp(scanFileTime); 8728 8729 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8730 if (nonMutatedPs != null) { 8731 synchronized (mPackages) { 8732 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8733 } 8734 } 8735 } else { 8736 // Modify state for the given package setting 8737 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8738 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8739 } 8740 return pkg; 8741 } 8742 8743 /** 8744 * Applies policy to the parsed package based upon the given policy flags. 8745 * Ensures the package is in a good state. 8746 * <p> 8747 * Implementation detail: This method must NOT have any side effect. It would 8748 * ideally be static, but, it requires locks to read system state. 8749 */ 8750 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8751 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8752 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8753 if (pkg.applicationInfo.isDirectBootAware()) { 8754 // we're direct boot aware; set for all components 8755 for (PackageParser.Service s : pkg.services) { 8756 s.info.encryptionAware = s.info.directBootAware = true; 8757 } 8758 for (PackageParser.Provider p : pkg.providers) { 8759 p.info.encryptionAware = p.info.directBootAware = true; 8760 } 8761 for (PackageParser.Activity a : pkg.activities) { 8762 a.info.encryptionAware = a.info.directBootAware = true; 8763 } 8764 for (PackageParser.Activity r : pkg.receivers) { 8765 r.info.encryptionAware = r.info.directBootAware = true; 8766 } 8767 } 8768 } else { 8769 // Only allow system apps to be flagged as core apps. 8770 pkg.coreApp = false; 8771 // clear flags not applicable to regular apps 8772 pkg.applicationInfo.privateFlags &= 8773 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8774 pkg.applicationInfo.privateFlags &= 8775 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8776 } 8777 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8778 8779 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8780 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8781 } 8782 8783 if (!isSystemApp(pkg)) { 8784 // Only system apps can use these features. 8785 pkg.mOriginalPackages = null; 8786 pkg.mRealPackage = null; 8787 pkg.mAdoptPermissions = null; 8788 } 8789 } 8790 8791 /** 8792 * Asserts the parsed package is valid according to teh given policy. If the 8793 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8794 * <p> 8795 * Implementation detail: This method must NOT have any side effects. It would 8796 * ideally be static, but, it requires locks to read system state. 8797 * 8798 * @throws PackageManagerException If the package fails any of the validation checks 8799 */ 8800 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8801 throws PackageManagerException { 8802 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8803 assertCodePolicy(pkg); 8804 } 8805 8806 if (pkg.applicationInfo.getCodePath() == null || 8807 pkg.applicationInfo.getResourcePath() == null) { 8808 // Bail out. The resource and code paths haven't been set. 8809 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8810 "Code and resource paths haven't been set correctly"); 8811 } 8812 8813 // Make sure we're not adding any bogus keyset info 8814 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8815 ksms.assertScannedPackageValid(pkg); 8816 8817 synchronized (mPackages) { 8818 // The special "android" package can only be defined once 8819 if (pkg.packageName.equals("android")) { 8820 if (mAndroidApplication != null) { 8821 Slog.w(TAG, "*************************************************"); 8822 Slog.w(TAG, "Core android package being redefined. Skipping."); 8823 Slog.w(TAG, " codePath=" + pkg.codePath); 8824 Slog.w(TAG, "*************************************************"); 8825 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8826 "Core android package being redefined. Skipping."); 8827 } 8828 } 8829 8830 // A package name must be unique; don't allow duplicates 8831 if (mPackages.containsKey(pkg.packageName) 8832 || mSharedLibraries.containsKey(pkg.packageName)) { 8833 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8834 "Application package " + pkg.packageName 8835 + " already installed. Skipping duplicate."); 8836 } 8837 8838 // Only privileged apps and updated privileged apps can add child packages. 8839 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8840 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8841 throw new PackageManagerException("Only privileged apps can add child " 8842 + "packages. Ignoring package " + pkg.packageName); 8843 } 8844 final int childCount = pkg.childPackages.size(); 8845 for (int i = 0; i < childCount; i++) { 8846 PackageParser.Package childPkg = pkg.childPackages.get(i); 8847 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8848 childPkg.packageName)) { 8849 throw new PackageManagerException("Can't override child of " 8850 + "another disabled app. Ignoring package " + pkg.packageName); 8851 } 8852 } 8853 } 8854 8855 // If we're only installing presumed-existing packages, require that the 8856 // scanned APK is both already known and at the path previously established 8857 // for it. Previously unknown packages we pick up normally, but if we have an 8858 // a priori expectation about this package's install presence, enforce it. 8859 // With a singular exception for new system packages. When an OTA contains 8860 // a new system package, we allow the codepath to change from a system location 8861 // to the user-installed location. If we don't allow this change, any newer, 8862 // user-installed version of the application will be ignored. 8863 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8864 if (mExpectingBetter.containsKey(pkg.packageName)) { 8865 logCriticalInfo(Log.WARN, 8866 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8867 } else { 8868 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8869 if (known != null) { 8870 if (DEBUG_PACKAGE_SCANNING) { 8871 Log.d(TAG, "Examining " + pkg.codePath 8872 + " and requiring known paths " + known.codePathString 8873 + " & " + known.resourcePathString); 8874 } 8875 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8876 || !pkg.applicationInfo.getResourcePath().equals( 8877 known.resourcePathString)) { 8878 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8879 "Application package " + pkg.packageName 8880 + " found at " + pkg.applicationInfo.getCodePath() 8881 + " but expected at " + known.codePathString 8882 + "; ignoring."); 8883 } 8884 } 8885 } 8886 } 8887 8888 // Verify that this new package doesn't have any content providers 8889 // that conflict with existing packages. Only do this if the 8890 // package isn't already installed, since we don't want to break 8891 // things that are installed. 8892 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8893 final int N = pkg.providers.size(); 8894 int i; 8895 for (i=0; i<N; i++) { 8896 PackageParser.Provider p = pkg.providers.get(i); 8897 if (p.info.authority != null) { 8898 String names[] = p.info.authority.split(";"); 8899 for (int j = 0; j < names.length; j++) { 8900 if (mProvidersByAuthority.containsKey(names[j])) { 8901 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8902 final String otherPackageName = 8903 ((other != null && other.getComponentName() != null) ? 8904 other.getComponentName().getPackageName() : "?"); 8905 throw new PackageManagerException( 8906 INSTALL_FAILED_CONFLICTING_PROVIDER, 8907 "Can't install because provider name " + names[j] 8908 + " (in package " + pkg.applicationInfo.packageName 8909 + ") is already used by " + otherPackageName); 8910 } 8911 } 8912 } 8913 } 8914 } 8915 } 8916 } 8917 8918 /** 8919 * Adds a scanned package to the system. When this method is finished, the package will 8920 * be available for query, resolution, etc... 8921 */ 8922 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8923 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8924 final String pkgName = pkg.packageName; 8925 if (mCustomResolverComponentName != null && 8926 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8927 setUpCustomResolverActivity(pkg); 8928 } 8929 8930 if (pkg.packageName.equals("android")) { 8931 synchronized (mPackages) { 8932 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8933 // Set up information for our fall-back user intent resolution activity. 8934 mPlatformPackage = pkg; 8935 pkg.mVersionCode = mSdkVersion; 8936 mAndroidApplication = pkg.applicationInfo; 8937 8938 if (!mResolverReplaced) { 8939 mResolveActivity.applicationInfo = mAndroidApplication; 8940 mResolveActivity.name = ResolverActivity.class.getName(); 8941 mResolveActivity.packageName = mAndroidApplication.packageName; 8942 mResolveActivity.processName = "system:ui"; 8943 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8944 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8945 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8946 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8947 mResolveActivity.exported = true; 8948 mResolveActivity.enabled = true; 8949 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8950 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8951 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8952 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8953 | ActivityInfo.CONFIG_ORIENTATION 8954 | ActivityInfo.CONFIG_KEYBOARD 8955 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8956 mResolveInfo.activityInfo = mResolveActivity; 8957 mResolveInfo.priority = 0; 8958 mResolveInfo.preferredOrder = 0; 8959 mResolveInfo.match = 0; 8960 mResolveComponentName = new ComponentName( 8961 mAndroidApplication.packageName, mResolveActivity.name); 8962 } 8963 } 8964 } 8965 } 8966 8967 ArrayList<PackageParser.Package> clientLibPkgs = null; 8968 // writer 8969 synchronized (mPackages) { 8970 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8971 // Only system apps can add new shared libraries. 8972 if (pkg.libraryNames != null) { 8973 for (int i=0; i<pkg.libraryNames.size(); i++) { 8974 String name = pkg.libraryNames.get(i); 8975 boolean allowed = false; 8976 if (pkg.isUpdatedSystemApp()) { 8977 // New library entries can only be added through the 8978 // system image. This is important to get rid of a lot 8979 // of nasty edge cases: for example if we allowed a non- 8980 // system update of the app to add a library, then uninstalling 8981 // the update would make the library go away, and assumptions 8982 // we made such as through app install filtering would now 8983 // have allowed apps on the device which aren't compatible 8984 // with it. Better to just have the restriction here, be 8985 // conservative, and create many fewer cases that can negatively 8986 // impact the user experience. 8987 final PackageSetting sysPs = mSettings 8988 .getDisabledSystemPkgLPr(pkg.packageName); 8989 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8990 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8991 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8992 allowed = true; 8993 break; 8994 } 8995 } 8996 } 8997 } else { 8998 allowed = true; 8999 } 9000 if (allowed) { 9001 if (!mSharedLibraries.containsKey(name)) { 9002 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 9003 } else if (!name.equals(pkg.packageName)) { 9004 Slog.w(TAG, "Package " + pkg.packageName + " library " 9005 + name + " already exists; skipping"); 9006 } 9007 } else { 9008 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9009 + name + " that is not declared on system image; skipping"); 9010 } 9011 } 9012 if ((scanFlags & SCAN_BOOTING) == 0) { 9013 // If we are not booting, we need to update any applications 9014 // that are clients of our shared library. If we are booting, 9015 // this will all be done once the scan is complete. 9016 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9017 } 9018 } 9019 } 9020 } 9021 9022 if ((scanFlags & SCAN_BOOTING) != 0) { 9023 // No apps can run during boot scan, so they don't need to be frozen 9024 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9025 // Caller asked to not kill app, so it's probably not frozen 9026 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9027 // Caller asked us to ignore frozen check for some reason; they 9028 // probably didn't know the package name 9029 } else { 9030 // We're doing major surgery on this package, so it better be frozen 9031 // right now to keep it from launching 9032 checkPackageFrozen(pkgName); 9033 } 9034 9035 // Also need to kill any apps that are dependent on the library. 9036 if (clientLibPkgs != null) { 9037 for (int i=0; i<clientLibPkgs.size(); i++) { 9038 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9039 killApplication(clientPkg.applicationInfo.packageName, 9040 clientPkg.applicationInfo.uid, "update lib"); 9041 } 9042 } 9043 9044 // writer 9045 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9046 9047 boolean createIdmapFailed = false; 9048 synchronized (mPackages) { 9049 // We don't expect installation to fail beyond this point 9050 9051 if (pkgSetting.pkg != null) { 9052 // Note that |user| might be null during the initial boot scan. If a codePath 9053 // for an app has changed during a boot scan, it's due to an app update that's 9054 // part of the system partition and marker changes must be applied to all users. 9055 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9056 final int[] userIds = resolveUserIds(userId); 9057 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9058 } 9059 9060 // Add the new setting to mSettings 9061 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9062 // Add the new setting to mPackages 9063 mPackages.put(pkg.applicationInfo.packageName, pkg); 9064 // Make sure we don't accidentally delete its data. 9065 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9066 while (iter.hasNext()) { 9067 PackageCleanItem item = iter.next(); 9068 if (pkgName.equals(item.packageName)) { 9069 iter.remove(); 9070 } 9071 } 9072 9073 // Add the package's KeySets to the global KeySetManagerService 9074 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9075 ksms.addScannedPackageLPw(pkg); 9076 9077 int N = pkg.providers.size(); 9078 StringBuilder r = null; 9079 int i; 9080 for (i=0; i<N; i++) { 9081 PackageParser.Provider p = pkg.providers.get(i); 9082 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9083 p.info.processName); 9084 mProviders.addProvider(p); 9085 p.syncable = p.info.isSyncable; 9086 if (p.info.authority != null) { 9087 String names[] = p.info.authority.split(";"); 9088 p.info.authority = null; 9089 for (int j = 0; j < names.length; j++) { 9090 if (j == 1 && p.syncable) { 9091 // We only want the first authority for a provider to possibly be 9092 // syncable, so if we already added this provider using a different 9093 // authority clear the syncable flag. We copy the provider before 9094 // changing it because the mProviders object contains a reference 9095 // to a provider that we don't want to change. 9096 // Only do this for the second authority since the resulting provider 9097 // object can be the same for all future authorities for this provider. 9098 p = new PackageParser.Provider(p); 9099 p.syncable = false; 9100 } 9101 if (!mProvidersByAuthority.containsKey(names[j])) { 9102 mProvidersByAuthority.put(names[j], p); 9103 if (p.info.authority == null) { 9104 p.info.authority = names[j]; 9105 } else { 9106 p.info.authority = p.info.authority + ";" + names[j]; 9107 } 9108 if (DEBUG_PACKAGE_SCANNING) { 9109 if (chatty) 9110 Log.d(TAG, "Registered content provider: " + names[j] 9111 + ", className = " + p.info.name + ", isSyncable = " 9112 + p.info.isSyncable); 9113 } 9114 } else { 9115 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9116 Slog.w(TAG, "Skipping provider name " + names[j] + 9117 " (in package " + pkg.applicationInfo.packageName + 9118 "): name already used by " 9119 + ((other != null && other.getComponentName() != null) 9120 ? other.getComponentName().getPackageName() : "?")); 9121 } 9122 } 9123 } 9124 if (chatty) { 9125 if (r == null) { 9126 r = new StringBuilder(256); 9127 } else { 9128 r.append(' '); 9129 } 9130 r.append(p.info.name); 9131 } 9132 } 9133 if (r != null) { 9134 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9135 } 9136 9137 N = pkg.services.size(); 9138 r = null; 9139 for (i=0; i<N; i++) { 9140 PackageParser.Service s = pkg.services.get(i); 9141 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9142 s.info.processName); 9143 mServices.addService(s); 9144 if (chatty) { 9145 if (r == null) { 9146 r = new StringBuilder(256); 9147 } else { 9148 r.append(' '); 9149 } 9150 r.append(s.info.name); 9151 } 9152 } 9153 if (r != null) { 9154 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9155 } 9156 9157 N = pkg.receivers.size(); 9158 r = null; 9159 for (i=0; i<N; i++) { 9160 PackageParser.Activity a = pkg.receivers.get(i); 9161 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9162 a.info.processName); 9163 mReceivers.addActivity(a, "receiver"); 9164 if (chatty) { 9165 if (r == null) { 9166 r = new StringBuilder(256); 9167 } else { 9168 r.append(' '); 9169 } 9170 r.append(a.info.name); 9171 } 9172 } 9173 if (r != null) { 9174 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9175 } 9176 9177 N = pkg.activities.size(); 9178 r = null; 9179 for (i=0; i<N; i++) { 9180 PackageParser.Activity a = pkg.activities.get(i); 9181 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9182 a.info.processName); 9183 mActivities.addActivity(a, "activity"); 9184 if (chatty) { 9185 if (r == null) { 9186 r = new StringBuilder(256); 9187 } else { 9188 r.append(' '); 9189 } 9190 r.append(a.info.name); 9191 } 9192 } 9193 if (r != null) { 9194 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9195 } 9196 9197 N = pkg.permissionGroups.size(); 9198 r = null; 9199 for (i=0; i<N; i++) { 9200 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9201 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9202 final String curPackageName = cur == null ? null : cur.info.packageName; 9203 // Dont allow ephemeral apps to define new permission groups. 9204 if (pkg.applicationInfo.isEphemeralApp()) { 9205 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9206 + pg.info.packageName 9207 + " ignored: ephemeral apps cannot define new permission groups."); 9208 continue; 9209 } 9210 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9211 if (cur == null || isPackageUpdate) { 9212 mPermissionGroups.put(pg.info.name, pg); 9213 if (chatty) { 9214 if (r == null) { 9215 r = new StringBuilder(256); 9216 } else { 9217 r.append(' '); 9218 } 9219 if (isPackageUpdate) { 9220 r.append("UPD:"); 9221 } 9222 r.append(pg.info.name); 9223 } 9224 } else { 9225 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9226 + pg.info.packageName + " ignored: original from " 9227 + cur.info.packageName); 9228 if (chatty) { 9229 if (r == null) { 9230 r = new StringBuilder(256); 9231 } else { 9232 r.append(' '); 9233 } 9234 r.append("DUP:"); 9235 r.append(pg.info.name); 9236 } 9237 } 9238 } 9239 if (r != null) { 9240 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9241 } 9242 9243 N = pkg.permissions.size(); 9244 r = null; 9245 for (i=0; i<N; i++) { 9246 PackageParser.Permission p = pkg.permissions.get(i); 9247 9248 // Dont allow ephemeral apps to define new permissions. 9249 if (pkg.applicationInfo.isEphemeralApp()) { 9250 Slog.w(TAG, "Permission " + p.info.name + " from package " 9251 + p.info.packageName 9252 + " ignored: ephemeral apps cannot define new permissions."); 9253 continue; 9254 } 9255 9256 // Assume by default that we did not install this permission into the system. 9257 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9258 9259 // Now that permission groups have a special meaning, we ignore permission 9260 // groups for legacy apps to prevent unexpected behavior. In particular, 9261 // permissions for one app being granted to someone just becase they happen 9262 // to be in a group defined by another app (before this had no implications). 9263 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9264 p.group = mPermissionGroups.get(p.info.group); 9265 // Warn for a permission in an unknown group. 9266 if (p.info.group != null && p.group == null) { 9267 Slog.w(TAG, "Permission " + p.info.name + " from package " 9268 + p.info.packageName + " in an unknown group " + p.info.group); 9269 } 9270 } 9271 9272 ArrayMap<String, BasePermission> permissionMap = 9273 p.tree ? mSettings.mPermissionTrees 9274 : mSettings.mPermissions; 9275 BasePermission bp = permissionMap.get(p.info.name); 9276 9277 // Allow system apps to redefine non-system permissions 9278 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9279 final boolean currentOwnerIsSystem = (bp.perm != null 9280 && isSystemApp(bp.perm.owner)); 9281 if (isSystemApp(p.owner)) { 9282 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9283 // It's a built-in permission and no owner, take ownership now 9284 bp.packageSetting = pkgSetting; 9285 bp.perm = p; 9286 bp.uid = pkg.applicationInfo.uid; 9287 bp.sourcePackage = p.info.packageName; 9288 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9289 } else if (!currentOwnerIsSystem) { 9290 String msg = "New decl " + p.owner + " of permission " 9291 + p.info.name + " is system; overriding " + bp.sourcePackage; 9292 reportSettingsProblem(Log.WARN, msg); 9293 bp = null; 9294 } 9295 } 9296 } 9297 9298 if (bp == null) { 9299 bp = new BasePermission(p.info.name, p.info.packageName, 9300 BasePermission.TYPE_NORMAL); 9301 permissionMap.put(p.info.name, bp); 9302 } 9303 9304 if (bp.perm == null) { 9305 if (bp.sourcePackage == null 9306 || bp.sourcePackage.equals(p.info.packageName)) { 9307 BasePermission tree = findPermissionTreeLP(p.info.name); 9308 if (tree == null 9309 || tree.sourcePackage.equals(p.info.packageName)) { 9310 bp.packageSetting = pkgSetting; 9311 bp.perm = p; 9312 bp.uid = pkg.applicationInfo.uid; 9313 bp.sourcePackage = p.info.packageName; 9314 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9315 if (chatty) { 9316 if (r == null) { 9317 r = new StringBuilder(256); 9318 } else { 9319 r.append(' '); 9320 } 9321 r.append(p.info.name); 9322 } 9323 } else { 9324 Slog.w(TAG, "Permission " + p.info.name + " from package " 9325 + p.info.packageName + " ignored: base tree " 9326 + tree.name + " is from package " 9327 + tree.sourcePackage); 9328 } 9329 } else { 9330 Slog.w(TAG, "Permission " + p.info.name + " from package " 9331 + p.info.packageName + " ignored: original from " 9332 + bp.sourcePackage); 9333 } 9334 } else if (chatty) { 9335 if (r == null) { 9336 r = new StringBuilder(256); 9337 } else { 9338 r.append(' '); 9339 } 9340 r.append("DUP:"); 9341 r.append(p.info.name); 9342 } 9343 if (bp.perm == p) { 9344 bp.protectionLevel = p.info.protectionLevel; 9345 } 9346 } 9347 9348 if (r != null) { 9349 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9350 } 9351 9352 N = pkg.instrumentation.size(); 9353 r = null; 9354 for (i=0; i<N; i++) { 9355 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9356 a.info.packageName = pkg.applicationInfo.packageName; 9357 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9358 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9359 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9360 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9361 a.info.dataDir = pkg.applicationInfo.dataDir; 9362 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9363 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9364 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9365 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9366 mInstrumentation.put(a.getComponentName(), a); 9367 if (chatty) { 9368 if (r == null) { 9369 r = new StringBuilder(256); 9370 } else { 9371 r.append(' '); 9372 } 9373 r.append(a.info.name); 9374 } 9375 } 9376 if (r != null) { 9377 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9378 } 9379 9380 if (pkg.protectedBroadcasts != null) { 9381 N = pkg.protectedBroadcasts.size(); 9382 for (i=0; i<N; i++) { 9383 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9384 } 9385 } 9386 9387 // Create idmap files for pairs of (packages, overlay packages). 9388 // Note: "android", ie framework-res.apk, is handled by native layers. 9389 if (pkg.mOverlayTarget != null) { 9390 // This is an overlay package. 9391 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9392 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9393 mOverlays.put(pkg.mOverlayTarget, 9394 new ArrayMap<String, PackageParser.Package>()); 9395 } 9396 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9397 map.put(pkg.packageName, pkg); 9398 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9399 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9400 createIdmapFailed = true; 9401 } 9402 } 9403 } else if (mOverlays.containsKey(pkg.packageName) && 9404 !pkg.packageName.equals("android")) { 9405 // This is a regular package, with one or more known overlay packages. 9406 createIdmapsForPackageLI(pkg); 9407 } 9408 } 9409 9410 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9411 9412 if (createIdmapFailed) { 9413 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9414 "scanPackageLI failed to createIdmap"); 9415 } 9416 } 9417 9418 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9419 PackageParser.Package update, int[] userIds) { 9420 if (existing.applicationInfo == null || update.applicationInfo == null) { 9421 // This isn't due to an app installation. 9422 return; 9423 } 9424 9425 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9426 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9427 9428 // The codePath hasn't changed, so there's nothing for us to do. 9429 if (Objects.equals(oldCodePath, newCodePath)) { 9430 return; 9431 } 9432 9433 File canonicalNewCodePath; 9434 try { 9435 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9436 } catch (IOException e) { 9437 Slog.w(TAG, "Failed to get canonical path.", e); 9438 return; 9439 } 9440 9441 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9442 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9443 // that the last component of the path (i.e, the name) doesn't need canonicalization 9444 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9445 // but may change in the future. Hopefully this function won't exist at that point. 9446 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9447 oldCodePath.getName()); 9448 9449 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9450 // with "@". 9451 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9452 if (!oldMarkerPrefix.endsWith("@")) { 9453 oldMarkerPrefix += "@"; 9454 } 9455 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9456 if (!newMarkerPrefix.endsWith("@")) { 9457 newMarkerPrefix += "@"; 9458 } 9459 9460 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9461 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9462 for (String updatedPath : updatedPaths) { 9463 String updatedPathName = new File(updatedPath).getName(); 9464 markerSuffixes.add(updatedPathName.replace('/', '@')); 9465 } 9466 9467 for (int userId : userIds) { 9468 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9469 9470 for (String markerSuffix : markerSuffixes) { 9471 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9472 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9473 if (oldForeignUseMark.exists()) { 9474 try { 9475 Os.rename(oldForeignUseMark.getAbsolutePath(), 9476 newForeignUseMark.getAbsolutePath()); 9477 } catch (ErrnoException e) { 9478 Slog.w(TAG, "Failed to rename foreign use marker", e); 9479 oldForeignUseMark.delete(); 9480 } 9481 } 9482 } 9483 } 9484 } 9485 9486 /** 9487 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9488 * is derived purely on the basis of the contents of {@code scanFile} and 9489 * {@code cpuAbiOverride}. 9490 * 9491 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9492 */ 9493 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9494 String cpuAbiOverride, boolean extractLibs, 9495 File appLib32InstallDir) 9496 throws PackageManagerException { 9497 // Give ourselves some initial paths; we'll come back for another 9498 // pass once we've determined ABI below. 9499 setNativeLibraryPaths(pkg, appLib32InstallDir); 9500 9501 // We would never need to extract libs for forward-locked and external packages, 9502 // since the container service will do it for us. We shouldn't attempt to 9503 // extract libs from system app when it was not updated. 9504 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9505 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9506 extractLibs = false; 9507 } 9508 9509 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9510 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9511 9512 NativeLibraryHelper.Handle handle = null; 9513 try { 9514 handle = NativeLibraryHelper.Handle.create(pkg); 9515 // TODO(multiArch): This can be null for apps that didn't go through the 9516 // usual installation process. We can calculate it again, like we 9517 // do during install time. 9518 // 9519 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9520 // unnecessary. 9521 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9522 9523 // Null out the abis so that they can be recalculated. 9524 pkg.applicationInfo.primaryCpuAbi = null; 9525 pkg.applicationInfo.secondaryCpuAbi = null; 9526 if (isMultiArch(pkg.applicationInfo)) { 9527 // Warn if we've set an abiOverride for multi-lib packages.. 9528 // By definition, we need to copy both 32 and 64 bit libraries for 9529 // such packages. 9530 if (pkg.cpuAbiOverride != null 9531 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9532 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9533 } 9534 9535 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9536 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9537 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9538 if (extractLibs) { 9539 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9540 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9541 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9542 useIsaSpecificSubdirs); 9543 } else { 9544 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9545 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9546 } 9547 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9548 } 9549 9550 maybeThrowExceptionForMultiArchCopy( 9551 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9552 9553 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9554 if (extractLibs) { 9555 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9556 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9557 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9558 useIsaSpecificSubdirs); 9559 } else { 9560 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9561 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9562 } 9563 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9564 } 9565 9566 maybeThrowExceptionForMultiArchCopy( 9567 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9568 9569 if (abi64 >= 0) { 9570 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9571 } 9572 9573 if (abi32 >= 0) { 9574 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9575 if (abi64 >= 0) { 9576 if (pkg.use32bitAbi) { 9577 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9578 pkg.applicationInfo.primaryCpuAbi = abi; 9579 } else { 9580 pkg.applicationInfo.secondaryCpuAbi = abi; 9581 } 9582 } else { 9583 pkg.applicationInfo.primaryCpuAbi = abi; 9584 } 9585 } 9586 9587 } else { 9588 String[] abiList = (cpuAbiOverride != null) ? 9589 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9590 9591 // Enable gross and lame hacks for apps that are built with old 9592 // SDK tools. We must scan their APKs for renderscript bitcode and 9593 // not launch them if it's present. Don't bother checking on devices 9594 // that don't have 64 bit support. 9595 boolean needsRenderScriptOverride = false; 9596 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9597 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9598 abiList = Build.SUPPORTED_32_BIT_ABIS; 9599 needsRenderScriptOverride = true; 9600 } 9601 9602 final int copyRet; 9603 if (extractLibs) { 9604 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9605 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9606 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9607 } else { 9608 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9609 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9610 } 9611 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9612 9613 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9614 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9615 "Error unpackaging native libs for app, errorCode=" + copyRet); 9616 } 9617 9618 if (copyRet >= 0) { 9619 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9620 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9621 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9622 } else if (needsRenderScriptOverride) { 9623 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9624 } 9625 } 9626 } catch (IOException ioe) { 9627 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9628 } finally { 9629 IoUtils.closeQuietly(handle); 9630 } 9631 9632 // Now that we've calculated the ABIs and determined if it's an internal app, 9633 // we will go ahead and populate the nativeLibraryPath. 9634 setNativeLibraryPaths(pkg, appLib32InstallDir); 9635 } 9636 9637 /** 9638 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9639 * i.e, so that all packages can be run inside a single process if required. 9640 * 9641 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9642 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9643 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9644 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9645 * updating a package that belongs to a shared user. 9646 * 9647 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9648 * adds unnecessary complexity. 9649 */ 9650 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9651 PackageParser.Package scannedPackage) { 9652 String requiredInstructionSet = null; 9653 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9654 requiredInstructionSet = VMRuntime.getInstructionSet( 9655 scannedPackage.applicationInfo.primaryCpuAbi); 9656 } 9657 9658 PackageSetting requirer = null; 9659 for (PackageSetting ps : packagesForUser) { 9660 // If packagesForUser contains scannedPackage, we skip it. This will happen 9661 // when scannedPackage is an update of an existing package. Without this check, 9662 // we will never be able to change the ABI of any package belonging to a shared 9663 // user, even if it's compatible with other packages. 9664 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9665 if (ps.primaryCpuAbiString == null) { 9666 continue; 9667 } 9668 9669 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9670 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9671 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9672 // this but there's not much we can do. 9673 String errorMessage = "Instruction set mismatch, " 9674 + ((requirer == null) ? "[caller]" : requirer) 9675 + " requires " + requiredInstructionSet + " whereas " + ps 9676 + " requires " + instructionSet; 9677 Slog.w(TAG, errorMessage); 9678 } 9679 9680 if (requiredInstructionSet == null) { 9681 requiredInstructionSet = instructionSet; 9682 requirer = ps; 9683 } 9684 } 9685 } 9686 9687 if (requiredInstructionSet != null) { 9688 String adjustedAbi; 9689 if (requirer != null) { 9690 // requirer != null implies that either scannedPackage was null or that scannedPackage 9691 // did not require an ABI, in which case we have to adjust scannedPackage to match 9692 // the ABI of the set (which is the same as requirer's ABI) 9693 adjustedAbi = requirer.primaryCpuAbiString; 9694 if (scannedPackage != null) { 9695 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9696 } 9697 } else { 9698 // requirer == null implies that we're updating all ABIs in the set to 9699 // match scannedPackage. 9700 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9701 } 9702 9703 for (PackageSetting ps : packagesForUser) { 9704 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9705 if (ps.primaryCpuAbiString != null) { 9706 continue; 9707 } 9708 9709 ps.primaryCpuAbiString = adjustedAbi; 9710 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9711 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9712 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9713 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9714 + " (requirer=" 9715 + (requirer == null ? "null" : requirer.pkg.packageName) 9716 + ", scannedPackage=" 9717 + (scannedPackage != null ? scannedPackage.packageName : "null") 9718 + ")"); 9719 try { 9720 mInstaller.rmdex(ps.codePathString, 9721 getDexCodeInstructionSet(getPreferredInstructionSet())); 9722 } catch (InstallerException ignored) { 9723 } 9724 } 9725 } 9726 } 9727 } 9728 } 9729 9730 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9731 synchronized (mPackages) { 9732 mResolverReplaced = true; 9733 // Set up information for custom user intent resolution activity. 9734 mResolveActivity.applicationInfo = pkg.applicationInfo; 9735 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9736 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9737 mResolveActivity.processName = pkg.applicationInfo.packageName; 9738 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9739 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9740 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9741 mResolveActivity.theme = 0; 9742 mResolveActivity.exported = true; 9743 mResolveActivity.enabled = true; 9744 mResolveInfo.activityInfo = mResolveActivity; 9745 mResolveInfo.priority = 0; 9746 mResolveInfo.preferredOrder = 0; 9747 mResolveInfo.match = 0; 9748 mResolveComponentName = mCustomResolverComponentName; 9749 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9750 mResolveComponentName); 9751 } 9752 } 9753 9754 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9755 if (installerComponent == null) { 9756 if (DEBUG_EPHEMERAL) { 9757 Slog.d(TAG, "Clear ephemeral installer activity"); 9758 } 9759 mEphemeralInstallerActivity.applicationInfo = null; 9760 return; 9761 } 9762 9763 if (DEBUG_EPHEMERAL) { 9764 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9765 } 9766 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9767 // Set up information for ephemeral installer activity 9768 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9769 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9770 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9771 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9772 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9773 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9774 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9775 mEphemeralInstallerActivity.theme = 0; 9776 mEphemeralInstallerActivity.exported = true; 9777 mEphemeralInstallerActivity.enabled = true; 9778 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9779 mEphemeralInstallerInfo.priority = 0; 9780 mEphemeralInstallerInfo.preferredOrder = 1; 9781 mEphemeralInstallerInfo.isDefault = true; 9782 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9783 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9784 } 9785 9786 private static String calculateBundledApkRoot(final String codePathString) { 9787 final File codePath = new File(codePathString); 9788 final File codeRoot; 9789 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9790 codeRoot = Environment.getRootDirectory(); 9791 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9792 codeRoot = Environment.getOemDirectory(); 9793 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9794 codeRoot = Environment.getVendorDirectory(); 9795 } else { 9796 // Unrecognized code path; take its top real segment as the apk root: 9797 // e.g. /something/app/blah.apk => /something 9798 try { 9799 File f = codePath.getCanonicalFile(); 9800 File parent = f.getParentFile(); // non-null because codePath is a file 9801 File tmp; 9802 while ((tmp = parent.getParentFile()) != null) { 9803 f = parent; 9804 parent = tmp; 9805 } 9806 codeRoot = f; 9807 Slog.w(TAG, "Unrecognized code path " 9808 + codePath + " - using " + codeRoot); 9809 } catch (IOException e) { 9810 // Can't canonicalize the code path -- shenanigans? 9811 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9812 return Environment.getRootDirectory().getPath(); 9813 } 9814 } 9815 return codeRoot.getPath(); 9816 } 9817 9818 /** 9819 * Derive and set the location of native libraries for the given package, 9820 * which varies depending on where and how the package was installed. 9821 */ 9822 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9823 final ApplicationInfo info = pkg.applicationInfo; 9824 final String codePath = pkg.codePath; 9825 final File codeFile = new File(codePath); 9826 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9827 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9828 9829 info.nativeLibraryRootDir = null; 9830 info.nativeLibraryRootRequiresIsa = false; 9831 info.nativeLibraryDir = null; 9832 info.secondaryNativeLibraryDir = null; 9833 9834 if (isApkFile(codeFile)) { 9835 // Monolithic install 9836 if (bundledApp) { 9837 // If "/system/lib64/apkname" exists, assume that is the per-package 9838 // native library directory to use; otherwise use "/system/lib/apkname". 9839 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9840 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9841 getPrimaryInstructionSet(info)); 9842 9843 // This is a bundled system app so choose the path based on the ABI. 9844 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9845 // is just the default path. 9846 final String apkName = deriveCodePathName(codePath); 9847 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9848 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9849 apkName).getAbsolutePath(); 9850 9851 if (info.secondaryCpuAbi != null) { 9852 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9853 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9854 secondaryLibDir, apkName).getAbsolutePath(); 9855 } 9856 } else if (asecApp) { 9857 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9858 .getAbsolutePath(); 9859 } else { 9860 final String apkName = deriveCodePathName(codePath); 9861 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9862 .getAbsolutePath(); 9863 } 9864 9865 info.nativeLibraryRootRequiresIsa = false; 9866 info.nativeLibraryDir = info.nativeLibraryRootDir; 9867 } else { 9868 // Cluster install 9869 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9870 info.nativeLibraryRootRequiresIsa = true; 9871 9872 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9873 getPrimaryInstructionSet(info)).getAbsolutePath(); 9874 9875 if (info.secondaryCpuAbi != null) { 9876 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9877 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9878 } 9879 } 9880 } 9881 9882 /** 9883 * Calculate the abis and roots for a bundled app. These can uniquely 9884 * be determined from the contents of the system partition, i.e whether 9885 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9886 * of this information, and instead assume that the system was built 9887 * sensibly. 9888 */ 9889 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9890 PackageSetting pkgSetting) { 9891 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9892 9893 // If "/system/lib64/apkname" exists, assume that is the per-package 9894 // native library directory to use; otherwise use "/system/lib/apkname". 9895 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9896 setBundledAppAbi(pkg, apkRoot, apkName); 9897 // pkgSetting might be null during rescan following uninstall of updates 9898 // to a bundled app, so accommodate that possibility. The settings in 9899 // that case will be established later from the parsed package. 9900 // 9901 // If the settings aren't null, sync them up with what we've just derived. 9902 // note that apkRoot isn't stored in the package settings. 9903 if (pkgSetting != null) { 9904 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9905 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9906 } 9907 } 9908 9909 /** 9910 * Deduces the ABI of a bundled app and sets the relevant fields on the 9911 * parsed pkg object. 9912 * 9913 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9914 * under which system libraries are installed. 9915 * @param apkName the name of the installed package. 9916 */ 9917 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9918 final File codeFile = new File(pkg.codePath); 9919 9920 final boolean has64BitLibs; 9921 final boolean has32BitLibs; 9922 if (isApkFile(codeFile)) { 9923 // Monolithic install 9924 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9925 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9926 } else { 9927 // Cluster install 9928 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9929 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9930 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9931 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9932 has64BitLibs = (new File(rootDir, isa)).exists(); 9933 } else { 9934 has64BitLibs = false; 9935 } 9936 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9937 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9938 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9939 has32BitLibs = (new File(rootDir, isa)).exists(); 9940 } else { 9941 has32BitLibs = false; 9942 } 9943 } 9944 9945 if (has64BitLibs && !has32BitLibs) { 9946 // The package has 64 bit libs, but not 32 bit libs. Its primary 9947 // ABI should be 64 bit. We can safely assume here that the bundled 9948 // native libraries correspond to the most preferred ABI in the list. 9949 9950 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9951 pkg.applicationInfo.secondaryCpuAbi = null; 9952 } else if (has32BitLibs && !has64BitLibs) { 9953 // The package has 32 bit libs but not 64 bit libs. Its primary 9954 // ABI should be 32 bit. 9955 9956 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9957 pkg.applicationInfo.secondaryCpuAbi = null; 9958 } else if (has32BitLibs && has64BitLibs) { 9959 // The application has both 64 and 32 bit bundled libraries. We check 9960 // here that the app declares multiArch support, and warn if it doesn't. 9961 // 9962 // We will be lenient here and record both ABIs. The primary will be the 9963 // ABI that's higher on the list, i.e, a device that's configured to prefer 9964 // 64 bit apps will see a 64 bit primary ABI, 9965 9966 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9967 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9968 } 9969 9970 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9971 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9972 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9973 } else { 9974 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9975 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9976 } 9977 } else { 9978 pkg.applicationInfo.primaryCpuAbi = null; 9979 pkg.applicationInfo.secondaryCpuAbi = null; 9980 } 9981 } 9982 9983 private void killApplication(String pkgName, int appId, String reason) { 9984 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9985 } 9986 9987 private void killApplication(String pkgName, int appId, int userId, String reason) { 9988 // Request the ActivityManager to kill the process(only for existing packages) 9989 // so that we do not end up in a confused state while the user is still using the older 9990 // version of the application while the new one gets installed. 9991 final long token = Binder.clearCallingIdentity(); 9992 try { 9993 IActivityManager am = ActivityManager.getService(); 9994 if (am != null) { 9995 try { 9996 am.killApplication(pkgName, appId, userId, reason); 9997 } catch (RemoteException e) { 9998 } 9999 } 10000 } finally { 10001 Binder.restoreCallingIdentity(token); 10002 } 10003 } 10004 10005 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10006 // Remove the parent package setting 10007 PackageSetting ps = (PackageSetting) pkg.mExtras; 10008 if (ps != null) { 10009 removePackageLI(ps, chatty); 10010 } 10011 // Remove the child package setting 10012 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10013 for (int i = 0; i < childCount; i++) { 10014 PackageParser.Package childPkg = pkg.childPackages.get(i); 10015 ps = (PackageSetting) childPkg.mExtras; 10016 if (ps != null) { 10017 removePackageLI(ps, chatty); 10018 } 10019 } 10020 } 10021 10022 void removePackageLI(PackageSetting ps, boolean chatty) { 10023 if (DEBUG_INSTALL) { 10024 if (chatty) 10025 Log.d(TAG, "Removing package " + ps.name); 10026 } 10027 10028 // writer 10029 synchronized (mPackages) { 10030 mPackages.remove(ps.name); 10031 final PackageParser.Package pkg = ps.pkg; 10032 if (pkg != null) { 10033 cleanPackageDataStructuresLILPw(pkg, chatty); 10034 } 10035 } 10036 } 10037 10038 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10039 if (DEBUG_INSTALL) { 10040 if (chatty) 10041 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10042 } 10043 10044 // writer 10045 synchronized (mPackages) { 10046 // Remove the parent package 10047 mPackages.remove(pkg.applicationInfo.packageName); 10048 cleanPackageDataStructuresLILPw(pkg, chatty); 10049 10050 // Remove the child packages 10051 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10052 for (int i = 0; i < childCount; i++) { 10053 PackageParser.Package childPkg = pkg.childPackages.get(i); 10054 mPackages.remove(childPkg.applicationInfo.packageName); 10055 cleanPackageDataStructuresLILPw(childPkg, chatty); 10056 } 10057 } 10058 } 10059 10060 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10061 int N = pkg.providers.size(); 10062 StringBuilder r = null; 10063 int i; 10064 for (i=0; i<N; i++) { 10065 PackageParser.Provider p = pkg.providers.get(i); 10066 mProviders.removeProvider(p); 10067 if (p.info.authority == null) { 10068 10069 /* There was another ContentProvider with this authority when 10070 * this app was installed so this authority is null, 10071 * Ignore it as we don't have to unregister the provider. 10072 */ 10073 continue; 10074 } 10075 String names[] = p.info.authority.split(";"); 10076 for (int j = 0; j < names.length; j++) { 10077 if (mProvidersByAuthority.get(names[j]) == p) { 10078 mProvidersByAuthority.remove(names[j]); 10079 if (DEBUG_REMOVE) { 10080 if (chatty) 10081 Log.d(TAG, "Unregistered content provider: " + names[j] 10082 + ", className = " + p.info.name + ", isSyncable = " 10083 + p.info.isSyncable); 10084 } 10085 } 10086 } 10087 if (DEBUG_REMOVE && chatty) { 10088 if (r == null) { 10089 r = new StringBuilder(256); 10090 } else { 10091 r.append(' '); 10092 } 10093 r.append(p.info.name); 10094 } 10095 } 10096 if (r != null) { 10097 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10098 } 10099 10100 N = pkg.services.size(); 10101 r = null; 10102 for (i=0; i<N; i++) { 10103 PackageParser.Service s = pkg.services.get(i); 10104 mServices.removeService(s); 10105 if (chatty) { 10106 if (r == null) { 10107 r = new StringBuilder(256); 10108 } else { 10109 r.append(' '); 10110 } 10111 r.append(s.info.name); 10112 } 10113 } 10114 if (r != null) { 10115 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10116 } 10117 10118 N = pkg.receivers.size(); 10119 r = null; 10120 for (i=0; i<N; i++) { 10121 PackageParser.Activity a = pkg.receivers.get(i); 10122 mReceivers.removeActivity(a, "receiver"); 10123 if (DEBUG_REMOVE && chatty) { 10124 if (r == null) { 10125 r = new StringBuilder(256); 10126 } else { 10127 r.append(' '); 10128 } 10129 r.append(a.info.name); 10130 } 10131 } 10132 if (r != null) { 10133 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10134 } 10135 10136 N = pkg.activities.size(); 10137 r = null; 10138 for (i=0; i<N; i++) { 10139 PackageParser.Activity a = pkg.activities.get(i); 10140 mActivities.removeActivity(a, "activity"); 10141 if (DEBUG_REMOVE && chatty) { 10142 if (r == null) { 10143 r = new StringBuilder(256); 10144 } else { 10145 r.append(' '); 10146 } 10147 r.append(a.info.name); 10148 } 10149 } 10150 if (r != null) { 10151 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10152 } 10153 10154 N = pkg.permissions.size(); 10155 r = null; 10156 for (i=0; i<N; i++) { 10157 PackageParser.Permission p = pkg.permissions.get(i); 10158 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10159 if (bp == null) { 10160 bp = mSettings.mPermissionTrees.get(p.info.name); 10161 } 10162 if (bp != null && bp.perm == p) { 10163 bp.perm = null; 10164 if (DEBUG_REMOVE && chatty) { 10165 if (r == null) { 10166 r = new StringBuilder(256); 10167 } else { 10168 r.append(' '); 10169 } 10170 r.append(p.info.name); 10171 } 10172 } 10173 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10174 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10175 if (appOpPkgs != null) { 10176 appOpPkgs.remove(pkg.packageName); 10177 } 10178 } 10179 } 10180 if (r != null) { 10181 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10182 } 10183 10184 N = pkg.requestedPermissions.size(); 10185 r = null; 10186 for (i=0; i<N; i++) { 10187 String perm = pkg.requestedPermissions.get(i); 10188 BasePermission bp = mSettings.mPermissions.get(perm); 10189 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10190 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10191 if (appOpPkgs != null) { 10192 appOpPkgs.remove(pkg.packageName); 10193 if (appOpPkgs.isEmpty()) { 10194 mAppOpPermissionPackages.remove(perm); 10195 } 10196 } 10197 } 10198 } 10199 if (r != null) { 10200 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10201 } 10202 10203 N = pkg.instrumentation.size(); 10204 r = null; 10205 for (i=0; i<N; i++) { 10206 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10207 mInstrumentation.remove(a.getComponentName()); 10208 if (DEBUG_REMOVE && chatty) { 10209 if (r == null) { 10210 r = new StringBuilder(256); 10211 } else { 10212 r.append(' '); 10213 } 10214 r.append(a.info.name); 10215 } 10216 } 10217 if (r != null) { 10218 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10219 } 10220 10221 r = null; 10222 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10223 // Only system apps can hold shared libraries. 10224 if (pkg.libraryNames != null) { 10225 for (i=0; i<pkg.libraryNames.size(); i++) { 10226 String name = pkg.libraryNames.get(i); 10227 SharedLibraryEntry cur = mSharedLibraries.get(name); 10228 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10229 mSharedLibraries.remove(name); 10230 if (DEBUG_REMOVE && chatty) { 10231 if (r == null) { 10232 r = new StringBuilder(256); 10233 } else { 10234 r.append(' '); 10235 } 10236 r.append(name); 10237 } 10238 } 10239 } 10240 } 10241 } 10242 if (r != null) { 10243 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10244 } 10245 } 10246 10247 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10248 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10249 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10250 return true; 10251 } 10252 } 10253 return false; 10254 } 10255 10256 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10257 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10258 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10259 10260 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10261 // Update the parent permissions 10262 updatePermissionsLPw(pkg.packageName, pkg, flags); 10263 // Update the child permissions 10264 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10265 for (int i = 0; i < childCount; i++) { 10266 PackageParser.Package childPkg = pkg.childPackages.get(i); 10267 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10268 } 10269 } 10270 10271 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10272 int flags) { 10273 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10274 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10275 } 10276 10277 private void updatePermissionsLPw(String changingPkg, 10278 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10279 // Make sure there are no dangling permission trees. 10280 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10281 while (it.hasNext()) { 10282 final BasePermission bp = it.next(); 10283 if (bp.packageSetting == null) { 10284 // We may not yet have parsed the package, so just see if 10285 // we still know about its settings. 10286 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10287 } 10288 if (bp.packageSetting == null) { 10289 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10290 + " from package " + bp.sourcePackage); 10291 it.remove(); 10292 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10293 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10294 Slog.i(TAG, "Removing old permission tree: " + bp.name 10295 + " from package " + bp.sourcePackage); 10296 flags |= UPDATE_PERMISSIONS_ALL; 10297 it.remove(); 10298 } 10299 } 10300 } 10301 10302 // Make sure all dynamic permissions have been assigned to a package, 10303 // and make sure there are no dangling permissions. 10304 it = mSettings.mPermissions.values().iterator(); 10305 while (it.hasNext()) { 10306 final BasePermission bp = it.next(); 10307 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10308 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10309 + bp.name + " pkg=" + bp.sourcePackage 10310 + " info=" + bp.pendingInfo); 10311 if (bp.packageSetting == null && bp.pendingInfo != null) { 10312 final BasePermission tree = findPermissionTreeLP(bp.name); 10313 if (tree != null && tree.perm != null) { 10314 bp.packageSetting = tree.packageSetting; 10315 bp.perm = new PackageParser.Permission(tree.perm.owner, 10316 new PermissionInfo(bp.pendingInfo)); 10317 bp.perm.info.packageName = tree.perm.info.packageName; 10318 bp.perm.info.name = bp.name; 10319 bp.uid = tree.uid; 10320 } 10321 } 10322 } 10323 if (bp.packageSetting == null) { 10324 // We may not yet have parsed the package, so just see if 10325 // we still know about its settings. 10326 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10327 } 10328 if (bp.packageSetting == null) { 10329 Slog.w(TAG, "Removing dangling permission: " + bp.name 10330 + " from package " + bp.sourcePackage); 10331 it.remove(); 10332 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10333 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10334 Slog.i(TAG, "Removing old permission: " + bp.name 10335 + " from package " + bp.sourcePackage); 10336 flags |= UPDATE_PERMISSIONS_ALL; 10337 it.remove(); 10338 } 10339 } 10340 } 10341 10342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10343 // Now update the permissions for all packages, in particular 10344 // replace the granted permissions of the system packages. 10345 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10346 for (PackageParser.Package pkg : mPackages.values()) { 10347 if (pkg != pkgInfo) { 10348 // Only replace for packages on requested volume 10349 final String volumeUuid = getVolumeUuidForPackage(pkg); 10350 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10351 && Objects.equals(replaceVolumeUuid, volumeUuid); 10352 grantPermissionsLPw(pkg, replace, changingPkg); 10353 } 10354 } 10355 } 10356 10357 if (pkgInfo != null) { 10358 // Only replace for packages on requested volume 10359 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10360 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10361 && Objects.equals(replaceVolumeUuid, volumeUuid); 10362 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10363 } 10364 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10365 } 10366 10367 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10368 String packageOfInterest) { 10369 // IMPORTANT: There are two types of permissions: install and runtime. 10370 // Install time permissions are granted when the app is installed to 10371 // all device users and users added in the future. Runtime permissions 10372 // are granted at runtime explicitly to specific users. Normal and signature 10373 // protected permissions are install time permissions. Dangerous permissions 10374 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10375 // otherwise they are runtime permissions. This function does not manage 10376 // runtime permissions except for the case an app targeting Lollipop MR1 10377 // being upgraded to target a newer SDK, in which case dangerous permissions 10378 // are transformed from install time to runtime ones. 10379 10380 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10381 if (ps == null) { 10382 return; 10383 } 10384 10385 PermissionsState permissionsState = ps.getPermissionsState(); 10386 PermissionsState origPermissions = permissionsState; 10387 10388 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10389 10390 boolean runtimePermissionsRevoked = false; 10391 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10392 10393 boolean changedInstallPermission = false; 10394 10395 if (replace) { 10396 ps.installPermissionsFixed = false; 10397 if (!ps.isSharedUser()) { 10398 origPermissions = new PermissionsState(permissionsState); 10399 permissionsState.reset(); 10400 } else { 10401 // We need to know only about runtime permission changes since the 10402 // calling code always writes the install permissions state but 10403 // the runtime ones are written only if changed. The only cases of 10404 // changed runtime permissions here are promotion of an install to 10405 // runtime and revocation of a runtime from a shared user. 10406 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10407 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10408 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10409 runtimePermissionsRevoked = true; 10410 } 10411 } 10412 } 10413 10414 permissionsState.setGlobalGids(mGlobalGids); 10415 10416 final int N = pkg.requestedPermissions.size(); 10417 for (int i=0; i<N; i++) { 10418 final String name = pkg.requestedPermissions.get(i); 10419 final BasePermission bp = mSettings.mPermissions.get(name); 10420 10421 if (DEBUG_INSTALL) { 10422 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10423 } 10424 10425 if (bp == null || bp.packageSetting == null) { 10426 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10427 Slog.w(TAG, "Unknown permission " + name 10428 + " in package " + pkg.packageName); 10429 } 10430 continue; 10431 } 10432 10433 10434 // Limit ephemeral apps to ephemeral allowed permissions. 10435 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10436 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10437 + pkg.packageName); 10438 continue; 10439 } 10440 10441 final String perm = bp.name; 10442 boolean allowedSig = false; 10443 int grant = GRANT_DENIED; 10444 10445 // Keep track of app op permissions. 10446 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10447 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10448 if (pkgs == null) { 10449 pkgs = new ArraySet<>(); 10450 mAppOpPermissionPackages.put(bp.name, pkgs); 10451 } 10452 pkgs.add(pkg.packageName); 10453 } 10454 10455 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10456 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10457 >= Build.VERSION_CODES.M; 10458 switch (level) { 10459 case PermissionInfo.PROTECTION_NORMAL: { 10460 // For all apps normal permissions are install time ones. 10461 grant = GRANT_INSTALL; 10462 } break; 10463 10464 case PermissionInfo.PROTECTION_DANGEROUS: { 10465 // If a permission review is required for legacy apps we represent 10466 // their permissions as always granted runtime ones since we need 10467 // to keep the review required permission flag per user while an 10468 // install permission's state is shared across all users. 10469 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10470 // For legacy apps dangerous permissions are install time ones. 10471 grant = GRANT_INSTALL; 10472 } else if (origPermissions.hasInstallPermission(bp.name)) { 10473 // For legacy apps that became modern, install becomes runtime. 10474 grant = GRANT_UPGRADE; 10475 } else if (mPromoteSystemApps 10476 && isSystemApp(ps) 10477 && mExistingSystemPackages.contains(ps.name)) { 10478 // For legacy system apps, install becomes runtime. 10479 // We cannot check hasInstallPermission() for system apps since those 10480 // permissions were granted implicitly and not persisted pre-M. 10481 grant = GRANT_UPGRADE; 10482 } else { 10483 // For modern apps keep runtime permissions unchanged. 10484 grant = GRANT_RUNTIME; 10485 } 10486 } break; 10487 10488 case PermissionInfo.PROTECTION_SIGNATURE: { 10489 // For all apps signature permissions are install time ones. 10490 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10491 if (allowedSig) { 10492 grant = GRANT_INSTALL; 10493 } 10494 } break; 10495 } 10496 10497 if (DEBUG_INSTALL) { 10498 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10499 } 10500 10501 if (grant != GRANT_DENIED) { 10502 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10503 // If this is an existing, non-system package, then 10504 // we can't add any new permissions to it. 10505 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10506 // Except... if this is a permission that was added 10507 // to the platform (note: need to only do this when 10508 // updating the platform). 10509 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10510 grant = GRANT_DENIED; 10511 } 10512 } 10513 } 10514 10515 switch (grant) { 10516 case GRANT_INSTALL: { 10517 // Revoke this as runtime permission to handle the case of 10518 // a runtime permission being downgraded to an install one. 10519 // Also in permission review mode we keep dangerous permissions 10520 // for legacy apps 10521 for (int userId : UserManagerService.getInstance().getUserIds()) { 10522 if (origPermissions.getRuntimePermissionState( 10523 bp.name, userId) != null) { 10524 // Revoke the runtime permission and clear the flags. 10525 origPermissions.revokeRuntimePermission(bp, userId); 10526 origPermissions.updatePermissionFlags(bp, userId, 10527 PackageManager.MASK_PERMISSION_FLAGS, 0); 10528 // If we revoked a permission permission, we have to write. 10529 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10530 changedRuntimePermissionUserIds, userId); 10531 } 10532 } 10533 // Grant an install permission. 10534 if (permissionsState.grantInstallPermission(bp) != 10535 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10536 changedInstallPermission = true; 10537 } 10538 } break; 10539 10540 case GRANT_RUNTIME: { 10541 // Grant previously granted runtime permissions. 10542 for (int userId : UserManagerService.getInstance().getUserIds()) { 10543 PermissionState permissionState = origPermissions 10544 .getRuntimePermissionState(bp.name, userId); 10545 int flags = permissionState != null 10546 ? permissionState.getFlags() : 0; 10547 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10548 if (permissionsState.grantRuntimePermission(bp, userId) == 10549 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10550 // If we cannot put the permission as it was, we have to write. 10551 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10552 changedRuntimePermissionUserIds, userId); 10553 } 10554 // If the app supports runtime permissions no need for a review. 10555 if (mPermissionReviewRequired 10556 && appSupportsRuntimePermissions 10557 && (flags & PackageManager 10558 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10559 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10560 // Since we changed the flags, we have to write. 10561 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10562 changedRuntimePermissionUserIds, userId); 10563 } 10564 } else if (mPermissionReviewRequired 10565 && !appSupportsRuntimePermissions) { 10566 // For legacy apps that need a permission review, every new 10567 // runtime permission is granted but it is pending a review. 10568 // We also need to review only platform defined runtime 10569 // permissions as these are the only ones the platform knows 10570 // how to disable the API to simulate revocation as legacy 10571 // apps don't expect to run with revoked permissions. 10572 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10573 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10574 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10575 // We changed the flags, hence have to write. 10576 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10577 changedRuntimePermissionUserIds, userId); 10578 } 10579 } 10580 if (permissionsState.grantRuntimePermission(bp, userId) 10581 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10582 // We changed the permission, hence have to write. 10583 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10584 changedRuntimePermissionUserIds, userId); 10585 } 10586 } 10587 // Propagate the permission flags. 10588 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10589 } 10590 } break; 10591 10592 case GRANT_UPGRADE: { 10593 // Grant runtime permissions for a previously held install permission. 10594 PermissionState permissionState = origPermissions 10595 .getInstallPermissionState(bp.name); 10596 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10597 10598 if (origPermissions.revokeInstallPermission(bp) 10599 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10600 // We will be transferring the permission flags, so clear them. 10601 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10602 PackageManager.MASK_PERMISSION_FLAGS, 0); 10603 changedInstallPermission = true; 10604 } 10605 10606 // If the permission is not to be promoted to runtime we ignore it and 10607 // also its other flags as they are not applicable to install permissions. 10608 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10609 for (int userId : currentUserIds) { 10610 if (permissionsState.grantRuntimePermission(bp, userId) != 10611 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10612 // Transfer the permission flags. 10613 permissionsState.updatePermissionFlags(bp, userId, 10614 flags, flags); 10615 // If we granted the permission, we have to write. 10616 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10617 changedRuntimePermissionUserIds, userId); 10618 } 10619 } 10620 } 10621 } break; 10622 10623 default: { 10624 if (packageOfInterest == null 10625 || packageOfInterest.equals(pkg.packageName)) { 10626 Slog.w(TAG, "Not granting permission " + perm 10627 + " to package " + pkg.packageName 10628 + " because it was previously installed without"); 10629 } 10630 } break; 10631 } 10632 } else { 10633 if (permissionsState.revokeInstallPermission(bp) != 10634 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10635 // Also drop the permission flags. 10636 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10637 PackageManager.MASK_PERMISSION_FLAGS, 0); 10638 changedInstallPermission = true; 10639 Slog.i(TAG, "Un-granting permission " + perm 10640 + " from package " + pkg.packageName 10641 + " (protectionLevel=" + bp.protectionLevel 10642 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10643 + ")"); 10644 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10645 // Don't print warning for app op permissions, since it is fine for them 10646 // not to be granted, there is a UI for the user to decide. 10647 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10648 Slog.w(TAG, "Not granting permission " + perm 10649 + " to package " + pkg.packageName 10650 + " (protectionLevel=" + bp.protectionLevel 10651 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10652 + ")"); 10653 } 10654 } 10655 } 10656 } 10657 10658 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10659 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10660 // This is the first that we have heard about this package, so the 10661 // permissions we have now selected are fixed until explicitly 10662 // changed. 10663 ps.installPermissionsFixed = true; 10664 } 10665 10666 // Persist the runtime permissions state for users with changes. If permissions 10667 // were revoked because no app in the shared user declares them we have to 10668 // write synchronously to avoid losing runtime permissions state. 10669 for (int userId : changedRuntimePermissionUserIds) { 10670 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10671 } 10672 } 10673 10674 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10675 boolean allowed = false; 10676 final int NP = PackageParser.NEW_PERMISSIONS.length; 10677 for (int ip=0; ip<NP; ip++) { 10678 final PackageParser.NewPermissionInfo npi 10679 = PackageParser.NEW_PERMISSIONS[ip]; 10680 if (npi.name.equals(perm) 10681 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10682 allowed = true; 10683 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10684 + pkg.packageName); 10685 break; 10686 } 10687 } 10688 return allowed; 10689 } 10690 10691 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10692 BasePermission bp, PermissionsState origPermissions) { 10693 boolean privilegedPermission = (bp.protectionLevel 10694 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10695 boolean privappPermissionsDisable = 10696 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10697 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10698 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10699 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10700 && !platformPackage && platformPermission) { 10701 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10702 .getPrivAppPermissions(pkg.packageName); 10703 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10704 if (!whitelisted) { 10705 Slog.w(TAG, "Privileged permission " + perm + " for package " 10706 + pkg.packageName + " - not in privapp-permissions whitelist"); 10707 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10708 return false; 10709 } 10710 } 10711 } 10712 boolean allowed = (compareSignatures( 10713 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10714 == PackageManager.SIGNATURE_MATCH) 10715 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10716 == PackageManager.SIGNATURE_MATCH); 10717 if (!allowed && privilegedPermission) { 10718 if (isSystemApp(pkg)) { 10719 // For updated system applications, a system permission 10720 // is granted only if it had been defined by the original application. 10721 if (pkg.isUpdatedSystemApp()) { 10722 final PackageSetting sysPs = mSettings 10723 .getDisabledSystemPkgLPr(pkg.packageName); 10724 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10725 // If the original was granted this permission, we take 10726 // that grant decision as read and propagate it to the 10727 // update. 10728 if (sysPs.isPrivileged()) { 10729 allowed = true; 10730 } 10731 } else { 10732 // The system apk may have been updated with an older 10733 // version of the one on the data partition, but which 10734 // granted a new system permission that it didn't have 10735 // before. In this case we do want to allow the app to 10736 // now get the new permission if the ancestral apk is 10737 // privileged to get it. 10738 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10739 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10740 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10741 allowed = true; 10742 break; 10743 } 10744 } 10745 } 10746 // Also if a privileged parent package on the system image or any of 10747 // its children requested a privileged permission, the updated child 10748 // packages can also get the permission. 10749 if (pkg.parentPackage != null) { 10750 final PackageSetting disabledSysParentPs = mSettings 10751 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10752 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10753 && disabledSysParentPs.isPrivileged()) { 10754 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10755 allowed = true; 10756 } else if (disabledSysParentPs.pkg.childPackages != null) { 10757 final int count = disabledSysParentPs.pkg.childPackages.size(); 10758 for (int i = 0; i < count; i++) { 10759 PackageParser.Package disabledSysChildPkg = 10760 disabledSysParentPs.pkg.childPackages.get(i); 10761 if (isPackageRequestingPermission(disabledSysChildPkg, 10762 perm)) { 10763 allowed = true; 10764 break; 10765 } 10766 } 10767 } 10768 } 10769 } 10770 } 10771 } else { 10772 allowed = isPrivilegedApp(pkg); 10773 } 10774 } 10775 } 10776 if (!allowed) { 10777 if (!allowed && (bp.protectionLevel 10778 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10779 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10780 // If this was a previously normal/dangerous permission that got moved 10781 // to a system permission as part of the runtime permission redesign, then 10782 // we still want to blindly grant it to old apps. 10783 allowed = true; 10784 } 10785 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10786 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10787 // If this permission is to be granted to the system installer and 10788 // this app is an installer, then it gets the permission. 10789 allowed = true; 10790 } 10791 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10792 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10793 // If this permission is to be granted to the system verifier and 10794 // this app is a verifier, then it gets the permission. 10795 allowed = true; 10796 } 10797 if (!allowed && (bp.protectionLevel 10798 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10799 && isSystemApp(pkg)) { 10800 // Any pre-installed system app is allowed to get this permission. 10801 allowed = true; 10802 } 10803 if (!allowed && (bp.protectionLevel 10804 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10805 // For development permissions, a development permission 10806 // is granted only if it was already granted. 10807 allowed = origPermissions.hasInstallPermission(perm); 10808 } 10809 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10810 && pkg.packageName.equals(mSetupWizardPackage)) { 10811 // If this permission is to be granted to the system setup wizard and 10812 // this app is a setup wizard, then it gets the permission. 10813 allowed = true; 10814 } 10815 } 10816 return allowed; 10817 } 10818 10819 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10820 final int permCount = pkg.requestedPermissions.size(); 10821 for (int j = 0; j < permCount; j++) { 10822 String requestedPermission = pkg.requestedPermissions.get(j); 10823 if (permission.equals(requestedPermission)) { 10824 return true; 10825 } 10826 } 10827 return false; 10828 } 10829 10830 final class ActivityIntentResolver 10831 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10832 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10833 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 10834 if (!sUserManager.exists(userId)) return null; 10835 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 10836 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 10837 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 10838 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 10839 isEphemeral, userId); 10840 } 10841 10842 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10843 int userId) { 10844 if (!sUserManager.exists(userId)) return null; 10845 mFlags = flags; 10846 return super.queryIntent(intent, resolvedType, 10847 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 10848 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 10849 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 10850 } 10851 10852 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10853 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10854 if (!sUserManager.exists(userId)) return null; 10855 if (packageActivities == null) { 10856 return null; 10857 } 10858 mFlags = flags; 10859 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10860 final boolean vislbleToEphemeral = 10861 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 10862 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 10863 final int N = packageActivities.size(); 10864 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10865 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10866 10867 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10868 for (int i = 0; i < N; ++i) { 10869 intentFilters = packageActivities.get(i).intents; 10870 if (intentFilters != null && intentFilters.size() > 0) { 10871 PackageParser.ActivityIntentInfo[] array = 10872 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10873 intentFilters.toArray(array); 10874 listCut.add(array); 10875 } 10876 } 10877 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 10878 vislbleToEphemeral, isEphemeral, listCut, userId); 10879 } 10880 10881 /** 10882 * Finds a privileged activity that matches the specified activity names. 10883 */ 10884 private PackageParser.Activity findMatchingActivity( 10885 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10886 for (PackageParser.Activity sysActivity : activityList) { 10887 if (sysActivity.info.name.equals(activityInfo.name)) { 10888 return sysActivity; 10889 } 10890 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10891 return sysActivity; 10892 } 10893 if (sysActivity.info.targetActivity != null) { 10894 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10895 return sysActivity; 10896 } 10897 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10898 return sysActivity; 10899 } 10900 } 10901 } 10902 return null; 10903 } 10904 10905 public class IterGenerator<E> { 10906 public Iterator<E> generate(ActivityIntentInfo info) { 10907 return null; 10908 } 10909 } 10910 10911 public class ActionIterGenerator extends IterGenerator<String> { 10912 @Override 10913 public Iterator<String> generate(ActivityIntentInfo info) { 10914 return info.actionsIterator(); 10915 } 10916 } 10917 10918 public class CategoriesIterGenerator extends IterGenerator<String> { 10919 @Override 10920 public Iterator<String> generate(ActivityIntentInfo info) { 10921 return info.categoriesIterator(); 10922 } 10923 } 10924 10925 public class SchemesIterGenerator extends IterGenerator<String> { 10926 @Override 10927 public Iterator<String> generate(ActivityIntentInfo info) { 10928 return info.schemesIterator(); 10929 } 10930 } 10931 10932 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10933 @Override 10934 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10935 return info.authoritiesIterator(); 10936 } 10937 } 10938 10939 /** 10940 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10941 * MODIFIED. Do not pass in a list that should not be changed. 10942 */ 10943 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10944 IterGenerator<T> generator, Iterator<T> searchIterator) { 10945 // loop through the set of actions; every one must be found in the intent filter 10946 while (searchIterator.hasNext()) { 10947 // we must have at least one filter in the list to consider a match 10948 if (intentList.size() == 0) { 10949 break; 10950 } 10951 10952 final T searchAction = searchIterator.next(); 10953 10954 // loop through the set of intent filters 10955 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10956 while (intentIter.hasNext()) { 10957 final ActivityIntentInfo intentInfo = intentIter.next(); 10958 boolean selectionFound = false; 10959 10960 // loop through the intent filter's selection criteria; at least one 10961 // of them must match the searched criteria 10962 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10963 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10964 final T intentSelection = intentSelectionIter.next(); 10965 if (intentSelection != null && intentSelection.equals(searchAction)) { 10966 selectionFound = true; 10967 break; 10968 } 10969 } 10970 10971 // the selection criteria wasn't found in this filter's set; this filter 10972 // is not a potential match 10973 if (!selectionFound) { 10974 intentIter.remove(); 10975 } 10976 } 10977 } 10978 } 10979 10980 private boolean isProtectedAction(ActivityIntentInfo filter) { 10981 final Iterator<String> actionsIter = filter.actionsIterator(); 10982 while (actionsIter != null && actionsIter.hasNext()) { 10983 final String filterAction = actionsIter.next(); 10984 if (PROTECTED_ACTIONS.contains(filterAction)) { 10985 return true; 10986 } 10987 } 10988 return false; 10989 } 10990 10991 /** 10992 * Adjusts the priority of the given intent filter according to policy. 10993 * <p> 10994 * <ul> 10995 * <li>The priority for non privileged applications is capped to '0'</li> 10996 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10997 * <li>The priority for unbundled updates to privileged applications is capped to the 10998 * priority defined on the system partition</li> 10999 * </ul> 11000 * <p> 11001 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11002 * allowed to obtain any priority on any action. 11003 */ 11004 private void adjustPriority( 11005 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11006 // nothing to do; priority is fine as-is 11007 if (intent.getPriority() <= 0) { 11008 return; 11009 } 11010 11011 final ActivityInfo activityInfo = intent.activity.info; 11012 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11013 11014 final boolean privilegedApp = 11015 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11016 if (!privilegedApp) { 11017 // non-privileged applications can never define a priority >0 11018 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11019 + " package: " + applicationInfo.packageName 11020 + " activity: " + intent.activity.className 11021 + " origPrio: " + intent.getPriority()); 11022 intent.setPriority(0); 11023 return; 11024 } 11025 11026 if (systemActivities == null) { 11027 // the system package is not disabled; we're parsing the system partition 11028 if (isProtectedAction(intent)) { 11029 if (mDeferProtectedFilters) { 11030 // We can't deal with these just yet. No component should ever obtain a 11031 // >0 priority for a protected actions, with ONE exception -- the setup 11032 // wizard. The setup wizard, however, cannot be known until we're able to 11033 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11034 // until all intent filters have been processed. Chicken, meet egg. 11035 // Let the filter temporarily have a high priority and rectify the 11036 // priorities after all system packages have been scanned. 11037 mProtectedFilters.add(intent); 11038 if (DEBUG_FILTERS) { 11039 Slog.i(TAG, "Protected action; save for later;" 11040 + " package: " + applicationInfo.packageName 11041 + " activity: " + intent.activity.className 11042 + " origPrio: " + intent.getPriority()); 11043 } 11044 return; 11045 } else { 11046 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11047 Slog.i(TAG, "No setup wizard;" 11048 + " All protected intents capped to priority 0"); 11049 } 11050 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11051 if (DEBUG_FILTERS) { 11052 Slog.i(TAG, "Found setup wizard;" 11053 + " allow priority " + intent.getPriority() + ";" 11054 + " package: " + intent.activity.info.packageName 11055 + " activity: " + intent.activity.className 11056 + " priority: " + intent.getPriority()); 11057 } 11058 // setup wizard gets whatever it wants 11059 return; 11060 } 11061 Slog.w(TAG, "Protected action; cap priority to 0;" 11062 + " package: " + intent.activity.info.packageName 11063 + " activity: " + intent.activity.className 11064 + " origPrio: " + intent.getPriority()); 11065 intent.setPriority(0); 11066 return; 11067 } 11068 } 11069 // privileged apps on the system image get whatever priority they request 11070 return; 11071 } 11072 11073 // privileged app unbundled update ... try to find the same activity 11074 final PackageParser.Activity foundActivity = 11075 findMatchingActivity(systemActivities, activityInfo); 11076 if (foundActivity == null) { 11077 // this is a new activity; it cannot obtain >0 priority 11078 if (DEBUG_FILTERS) { 11079 Slog.i(TAG, "New activity; cap priority to 0;" 11080 + " package: " + applicationInfo.packageName 11081 + " activity: " + intent.activity.className 11082 + " origPrio: " + intent.getPriority()); 11083 } 11084 intent.setPriority(0); 11085 return; 11086 } 11087 11088 // found activity, now check for filter equivalence 11089 11090 // a shallow copy is enough; we modify the list, not its contents 11091 final List<ActivityIntentInfo> intentListCopy = 11092 new ArrayList<>(foundActivity.intents); 11093 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11094 11095 // find matching action subsets 11096 final Iterator<String> actionsIterator = intent.actionsIterator(); 11097 if (actionsIterator != null) { 11098 getIntentListSubset( 11099 intentListCopy, new ActionIterGenerator(), actionsIterator); 11100 if (intentListCopy.size() == 0) { 11101 // no more intents to match; we're not equivalent 11102 if (DEBUG_FILTERS) { 11103 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11104 + " package: " + applicationInfo.packageName 11105 + " activity: " + intent.activity.className 11106 + " origPrio: " + intent.getPriority()); 11107 } 11108 intent.setPriority(0); 11109 return; 11110 } 11111 } 11112 11113 // find matching category subsets 11114 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11115 if (categoriesIterator != null) { 11116 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11117 categoriesIterator); 11118 if (intentListCopy.size() == 0) { 11119 // no more intents to match; we're not equivalent 11120 if (DEBUG_FILTERS) { 11121 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11122 + " package: " + applicationInfo.packageName 11123 + " activity: " + intent.activity.className 11124 + " origPrio: " + intent.getPriority()); 11125 } 11126 intent.setPriority(0); 11127 return; 11128 } 11129 } 11130 11131 // find matching schemes subsets 11132 final Iterator<String> schemesIterator = intent.schemesIterator(); 11133 if (schemesIterator != null) { 11134 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11135 schemesIterator); 11136 if (intentListCopy.size() == 0) { 11137 // no more intents to match; we're not equivalent 11138 if (DEBUG_FILTERS) { 11139 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11140 + " package: " + applicationInfo.packageName 11141 + " activity: " + intent.activity.className 11142 + " origPrio: " + intent.getPriority()); 11143 } 11144 intent.setPriority(0); 11145 return; 11146 } 11147 } 11148 11149 // find matching authorities subsets 11150 final Iterator<IntentFilter.AuthorityEntry> 11151 authoritiesIterator = intent.authoritiesIterator(); 11152 if (authoritiesIterator != null) { 11153 getIntentListSubset(intentListCopy, 11154 new AuthoritiesIterGenerator(), 11155 authoritiesIterator); 11156 if (intentListCopy.size() == 0) { 11157 // no more intents to match; we're not equivalent 11158 if (DEBUG_FILTERS) { 11159 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11160 + " package: " + applicationInfo.packageName 11161 + " activity: " + intent.activity.className 11162 + " origPrio: " + intent.getPriority()); 11163 } 11164 intent.setPriority(0); 11165 return; 11166 } 11167 } 11168 11169 // we found matching filter(s); app gets the max priority of all intents 11170 int cappedPriority = 0; 11171 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11172 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11173 } 11174 if (intent.getPriority() > cappedPriority) { 11175 if (DEBUG_FILTERS) { 11176 Slog.i(TAG, "Found matching filter(s);" 11177 + " cap priority to " + cappedPriority + ";" 11178 + " package: " + applicationInfo.packageName 11179 + " activity: " + intent.activity.className 11180 + " origPrio: " + intent.getPriority()); 11181 } 11182 intent.setPriority(cappedPriority); 11183 return; 11184 } 11185 // all this for nothing; the requested priority was <= what was on the system 11186 } 11187 11188 public final void addActivity(PackageParser.Activity a, String type) { 11189 mActivities.put(a.getComponentName(), a); 11190 if (DEBUG_SHOW_INFO) 11191 Log.v( 11192 TAG, " " + type + " " + 11193 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11194 if (DEBUG_SHOW_INFO) 11195 Log.v(TAG, " Class=" + a.info.name); 11196 final int NI = a.intents.size(); 11197 for (int j=0; j<NI; j++) { 11198 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11199 if ("activity".equals(type)) { 11200 final PackageSetting ps = 11201 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11202 final List<PackageParser.Activity> systemActivities = 11203 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11204 adjustPriority(systemActivities, intent); 11205 } 11206 if (DEBUG_SHOW_INFO) { 11207 Log.v(TAG, " IntentFilter:"); 11208 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11209 } 11210 if (!intent.debugCheck()) { 11211 Log.w(TAG, "==> For Activity " + a.info.name); 11212 } 11213 addFilter(intent); 11214 } 11215 } 11216 11217 public final void removeActivity(PackageParser.Activity a, String type) { 11218 mActivities.remove(a.getComponentName()); 11219 if (DEBUG_SHOW_INFO) { 11220 Log.v(TAG, " " + type + " " 11221 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11222 : a.info.name) + ":"); 11223 Log.v(TAG, " Class=" + a.info.name); 11224 } 11225 final int NI = a.intents.size(); 11226 for (int j=0; j<NI; j++) { 11227 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11228 if (DEBUG_SHOW_INFO) { 11229 Log.v(TAG, " IntentFilter:"); 11230 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11231 } 11232 removeFilter(intent); 11233 } 11234 } 11235 11236 @Override 11237 protected boolean allowFilterResult( 11238 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11239 ActivityInfo filterAi = filter.activity.info; 11240 for (int i=dest.size()-1; i>=0; i--) { 11241 ActivityInfo destAi = dest.get(i).activityInfo; 11242 if (destAi.name == filterAi.name 11243 && destAi.packageName == filterAi.packageName) { 11244 return false; 11245 } 11246 } 11247 return true; 11248 } 11249 11250 @Override 11251 protected ActivityIntentInfo[] newArray(int size) { 11252 return new ActivityIntentInfo[size]; 11253 } 11254 11255 @Override 11256 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11257 if (!sUserManager.exists(userId)) return true; 11258 PackageParser.Package p = filter.activity.owner; 11259 if (p != null) { 11260 PackageSetting ps = (PackageSetting)p.mExtras; 11261 if (ps != null) { 11262 // System apps are never considered stopped for purposes of 11263 // filtering, because there may be no way for the user to 11264 // actually re-launch them. 11265 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11266 && ps.getStopped(userId); 11267 } 11268 } 11269 return false; 11270 } 11271 11272 @Override 11273 protected boolean isPackageForFilter(String packageName, 11274 PackageParser.ActivityIntentInfo info) { 11275 return packageName.equals(info.activity.owner.packageName); 11276 } 11277 11278 @Override 11279 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11280 int match, int userId) { 11281 if (!sUserManager.exists(userId)) return null; 11282 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11283 return null; 11284 } 11285 final PackageParser.Activity activity = info.activity; 11286 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11287 if (ps == null) { 11288 return null; 11289 } 11290 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11291 ps.readUserState(userId), userId); 11292 if (ai == null) { 11293 return null; 11294 } 11295 final ResolveInfo res = new ResolveInfo(); 11296 res.activityInfo = ai; 11297 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11298 res.filter = info; 11299 } 11300 if (info != null) { 11301 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11302 } 11303 res.priority = info.getPriority(); 11304 res.preferredOrder = activity.owner.mPreferredOrder; 11305 //System.out.println("Result: " + res.activityInfo.className + 11306 // " = " + res.priority); 11307 res.match = match; 11308 res.isDefault = info.hasDefault; 11309 res.labelRes = info.labelRes; 11310 res.nonLocalizedLabel = info.nonLocalizedLabel; 11311 if (userNeedsBadging(userId)) { 11312 res.noResourceId = true; 11313 } else { 11314 res.icon = info.icon; 11315 } 11316 res.iconResourceId = info.icon; 11317 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11318 return res; 11319 } 11320 11321 @Override 11322 protected void sortResults(List<ResolveInfo> results) { 11323 Collections.sort(results, mResolvePrioritySorter); 11324 } 11325 11326 @Override 11327 protected void dumpFilter(PrintWriter out, String prefix, 11328 PackageParser.ActivityIntentInfo filter) { 11329 out.print(prefix); out.print( 11330 Integer.toHexString(System.identityHashCode(filter.activity))); 11331 out.print(' '); 11332 filter.activity.printComponentShortName(out); 11333 out.print(" filter "); 11334 out.println(Integer.toHexString(System.identityHashCode(filter))); 11335 } 11336 11337 @Override 11338 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11339 return filter.activity; 11340 } 11341 11342 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11343 PackageParser.Activity activity = (PackageParser.Activity)label; 11344 out.print(prefix); out.print( 11345 Integer.toHexString(System.identityHashCode(activity))); 11346 out.print(' '); 11347 activity.printComponentShortName(out); 11348 if (count > 1) { 11349 out.print(" ("); out.print(count); out.print(" filters)"); 11350 } 11351 out.println(); 11352 } 11353 11354 // Keys are String (activity class name), values are Activity. 11355 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11356 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11357 private int mFlags; 11358 } 11359 11360 private final class ServiceIntentResolver 11361 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11362 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11363 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11364 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11365 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11366 isEphemeral, userId); 11367 } 11368 11369 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11370 int userId) { 11371 if (!sUserManager.exists(userId)) return null; 11372 mFlags = flags; 11373 return super.queryIntent(intent, resolvedType, 11374 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11375 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11376 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11377 } 11378 11379 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11380 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11381 if (!sUserManager.exists(userId)) return null; 11382 if (packageServices == null) { 11383 return null; 11384 } 11385 mFlags = flags; 11386 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11387 final boolean vislbleToEphemeral = 11388 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11389 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11390 final int N = packageServices.size(); 11391 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11392 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11393 11394 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11395 for (int i = 0; i < N; ++i) { 11396 intentFilters = packageServices.get(i).intents; 11397 if (intentFilters != null && intentFilters.size() > 0) { 11398 PackageParser.ServiceIntentInfo[] array = 11399 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11400 intentFilters.toArray(array); 11401 listCut.add(array); 11402 } 11403 } 11404 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11405 vislbleToEphemeral, isEphemeral, listCut, userId); 11406 } 11407 11408 public final void addService(PackageParser.Service s) { 11409 mServices.put(s.getComponentName(), s); 11410 if (DEBUG_SHOW_INFO) { 11411 Log.v(TAG, " " 11412 + (s.info.nonLocalizedLabel != null 11413 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11414 Log.v(TAG, " Class=" + s.info.name); 11415 } 11416 final int NI = s.intents.size(); 11417 int j; 11418 for (j=0; j<NI; j++) { 11419 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11420 if (DEBUG_SHOW_INFO) { 11421 Log.v(TAG, " IntentFilter:"); 11422 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11423 } 11424 if (!intent.debugCheck()) { 11425 Log.w(TAG, "==> For Service " + s.info.name); 11426 } 11427 addFilter(intent); 11428 } 11429 } 11430 11431 public final void removeService(PackageParser.Service s) { 11432 mServices.remove(s.getComponentName()); 11433 if (DEBUG_SHOW_INFO) { 11434 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11435 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11436 Log.v(TAG, " Class=" + s.info.name); 11437 } 11438 final int NI = s.intents.size(); 11439 int j; 11440 for (j=0; j<NI; j++) { 11441 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11442 if (DEBUG_SHOW_INFO) { 11443 Log.v(TAG, " IntentFilter:"); 11444 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11445 } 11446 removeFilter(intent); 11447 } 11448 } 11449 11450 @Override 11451 protected boolean allowFilterResult( 11452 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11453 ServiceInfo filterSi = filter.service.info; 11454 for (int i=dest.size()-1; i>=0; i--) { 11455 ServiceInfo destAi = dest.get(i).serviceInfo; 11456 if (destAi.name == filterSi.name 11457 && destAi.packageName == filterSi.packageName) { 11458 return false; 11459 } 11460 } 11461 return true; 11462 } 11463 11464 @Override 11465 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11466 return new PackageParser.ServiceIntentInfo[size]; 11467 } 11468 11469 @Override 11470 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11471 if (!sUserManager.exists(userId)) return true; 11472 PackageParser.Package p = filter.service.owner; 11473 if (p != null) { 11474 PackageSetting ps = (PackageSetting)p.mExtras; 11475 if (ps != null) { 11476 // System apps are never considered stopped for purposes of 11477 // filtering, because there may be no way for the user to 11478 // actually re-launch them. 11479 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11480 && ps.getStopped(userId); 11481 } 11482 } 11483 return false; 11484 } 11485 11486 @Override 11487 protected boolean isPackageForFilter(String packageName, 11488 PackageParser.ServiceIntentInfo info) { 11489 return packageName.equals(info.service.owner.packageName); 11490 } 11491 11492 @Override 11493 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11494 int match, int userId) { 11495 if (!sUserManager.exists(userId)) return null; 11496 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11497 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11498 return null; 11499 } 11500 final PackageParser.Service service = info.service; 11501 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11502 if (ps == null) { 11503 return null; 11504 } 11505 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11506 ps.readUserState(userId), userId); 11507 if (si == null) { 11508 return null; 11509 } 11510 final ResolveInfo res = new ResolveInfo(); 11511 res.serviceInfo = si; 11512 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11513 res.filter = filter; 11514 } 11515 res.priority = info.getPriority(); 11516 res.preferredOrder = service.owner.mPreferredOrder; 11517 res.match = match; 11518 res.isDefault = info.hasDefault; 11519 res.labelRes = info.labelRes; 11520 res.nonLocalizedLabel = info.nonLocalizedLabel; 11521 res.icon = info.icon; 11522 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11523 return res; 11524 } 11525 11526 @Override 11527 protected void sortResults(List<ResolveInfo> results) { 11528 Collections.sort(results, mResolvePrioritySorter); 11529 } 11530 11531 @Override 11532 protected void dumpFilter(PrintWriter out, String prefix, 11533 PackageParser.ServiceIntentInfo filter) { 11534 out.print(prefix); out.print( 11535 Integer.toHexString(System.identityHashCode(filter.service))); 11536 out.print(' '); 11537 filter.service.printComponentShortName(out); 11538 out.print(" filter "); 11539 out.println(Integer.toHexString(System.identityHashCode(filter))); 11540 } 11541 11542 @Override 11543 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11544 return filter.service; 11545 } 11546 11547 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11548 PackageParser.Service service = (PackageParser.Service)label; 11549 out.print(prefix); out.print( 11550 Integer.toHexString(System.identityHashCode(service))); 11551 out.print(' '); 11552 service.printComponentShortName(out); 11553 if (count > 1) { 11554 out.print(" ("); out.print(count); out.print(" filters)"); 11555 } 11556 out.println(); 11557 } 11558 11559// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11560// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11561// final List<ResolveInfo> retList = Lists.newArrayList(); 11562// while (i.hasNext()) { 11563// final ResolveInfo resolveInfo = (ResolveInfo) i; 11564// if (isEnabledLP(resolveInfo.serviceInfo)) { 11565// retList.add(resolveInfo); 11566// } 11567// } 11568// return retList; 11569// } 11570 11571 // Keys are String (activity class name), values are Activity. 11572 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11573 = new ArrayMap<ComponentName, PackageParser.Service>(); 11574 private int mFlags; 11575 } 11576 11577 private final class ProviderIntentResolver 11578 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11579 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11580 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11581 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11582 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11583 isEphemeral, userId); 11584 } 11585 11586 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11587 int userId) { 11588 if (!sUserManager.exists(userId)) 11589 return null; 11590 mFlags = flags; 11591 return super.queryIntent(intent, resolvedType, 11592 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11593 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11594 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11595 } 11596 11597 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11598 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11599 if (!sUserManager.exists(userId)) 11600 return null; 11601 if (packageProviders == null) { 11602 return null; 11603 } 11604 mFlags = flags; 11605 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11606 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11607 final boolean vislbleToEphemeral = 11608 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11609 final int N = packageProviders.size(); 11610 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11611 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11612 11613 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11614 for (int i = 0; i < N; ++i) { 11615 intentFilters = packageProviders.get(i).intents; 11616 if (intentFilters != null && intentFilters.size() > 0) { 11617 PackageParser.ProviderIntentInfo[] array = 11618 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11619 intentFilters.toArray(array); 11620 listCut.add(array); 11621 } 11622 } 11623 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11624 vislbleToEphemeral, isEphemeral, listCut, userId); 11625 } 11626 11627 public final void addProvider(PackageParser.Provider p) { 11628 if (mProviders.containsKey(p.getComponentName())) { 11629 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11630 return; 11631 } 11632 11633 mProviders.put(p.getComponentName(), p); 11634 if (DEBUG_SHOW_INFO) { 11635 Log.v(TAG, " " 11636 + (p.info.nonLocalizedLabel != null 11637 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11638 Log.v(TAG, " Class=" + p.info.name); 11639 } 11640 final int NI = p.intents.size(); 11641 int j; 11642 for (j = 0; j < NI; j++) { 11643 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11644 if (DEBUG_SHOW_INFO) { 11645 Log.v(TAG, " IntentFilter:"); 11646 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11647 } 11648 if (!intent.debugCheck()) { 11649 Log.w(TAG, "==> For Provider " + p.info.name); 11650 } 11651 addFilter(intent); 11652 } 11653 } 11654 11655 public final void removeProvider(PackageParser.Provider p) { 11656 mProviders.remove(p.getComponentName()); 11657 if (DEBUG_SHOW_INFO) { 11658 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11659 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11660 Log.v(TAG, " Class=" + p.info.name); 11661 } 11662 final int NI = p.intents.size(); 11663 int j; 11664 for (j = 0; j < NI; j++) { 11665 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11666 if (DEBUG_SHOW_INFO) { 11667 Log.v(TAG, " IntentFilter:"); 11668 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11669 } 11670 removeFilter(intent); 11671 } 11672 } 11673 11674 @Override 11675 protected boolean allowFilterResult( 11676 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11677 ProviderInfo filterPi = filter.provider.info; 11678 for (int i = dest.size() - 1; i >= 0; i--) { 11679 ProviderInfo destPi = dest.get(i).providerInfo; 11680 if (destPi.name == filterPi.name 11681 && destPi.packageName == filterPi.packageName) { 11682 return false; 11683 } 11684 } 11685 return true; 11686 } 11687 11688 @Override 11689 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11690 return new PackageParser.ProviderIntentInfo[size]; 11691 } 11692 11693 @Override 11694 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11695 if (!sUserManager.exists(userId)) 11696 return true; 11697 PackageParser.Package p = filter.provider.owner; 11698 if (p != null) { 11699 PackageSetting ps = (PackageSetting) p.mExtras; 11700 if (ps != null) { 11701 // System apps are never considered stopped for purposes of 11702 // filtering, because there may be no way for the user to 11703 // actually re-launch them. 11704 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11705 && ps.getStopped(userId); 11706 } 11707 } 11708 return false; 11709 } 11710 11711 @Override 11712 protected boolean isPackageForFilter(String packageName, 11713 PackageParser.ProviderIntentInfo info) { 11714 return packageName.equals(info.provider.owner.packageName); 11715 } 11716 11717 @Override 11718 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11719 int match, int userId) { 11720 if (!sUserManager.exists(userId)) 11721 return null; 11722 final PackageParser.ProviderIntentInfo info = filter; 11723 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11724 return null; 11725 } 11726 final PackageParser.Provider provider = info.provider; 11727 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11728 if (ps == null) { 11729 return null; 11730 } 11731 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11732 ps.readUserState(userId), userId); 11733 if (pi == null) { 11734 return null; 11735 } 11736 final ResolveInfo res = new ResolveInfo(); 11737 res.providerInfo = pi; 11738 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11739 res.filter = filter; 11740 } 11741 res.priority = info.getPriority(); 11742 res.preferredOrder = provider.owner.mPreferredOrder; 11743 res.match = match; 11744 res.isDefault = info.hasDefault; 11745 res.labelRes = info.labelRes; 11746 res.nonLocalizedLabel = info.nonLocalizedLabel; 11747 res.icon = info.icon; 11748 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11749 return res; 11750 } 11751 11752 @Override 11753 protected void sortResults(List<ResolveInfo> results) { 11754 Collections.sort(results, mResolvePrioritySorter); 11755 } 11756 11757 @Override 11758 protected void dumpFilter(PrintWriter out, String prefix, 11759 PackageParser.ProviderIntentInfo filter) { 11760 out.print(prefix); 11761 out.print( 11762 Integer.toHexString(System.identityHashCode(filter.provider))); 11763 out.print(' '); 11764 filter.provider.printComponentShortName(out); 11765 out.print(" filter "); 11766 out.println(Integer.toHexString(System.identityHashCode(filter))); 11767 } 11768 11769 @Override 11770 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11771 return filter.provider; 11772 } 11773 11774 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11775 PackageParser.Provider provider = (PackageParser.Provider)label; 11776 out.print(prefix); out.print( 11777 Integer.toHexString(System.identityHashCode(provider))); 11778 out.print(' '); 11779 provider.printComponentShortName(out); 11780 if (count > 1) { 11781 out.print(" ("); out.print(count); out.print(" filters)"); 11782 } 11783 out.println(); 11784 } 11785 11786 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11787 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11788 private int mFlags; 11789 } 11790 11791 static final class EphemeralIntentResolver 11792 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11793 /** 11794 * The result that has the highest defined order. Ordering applies on a 11795 * per-package basis. Mapping is from package name to Pair of order and 11796 * EphemeralResolveInfo. 11797 * <p> 11798 * NOTE: This is implemented as a field variable for convenience and efficiency. 11799 * By having a field variable, we're able to track filter ordering as soon as 11800 * a non-zero order is defined. Otherwise, multiple loops across the result set 11801 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11802 * this needs to be contained entirely within {@link #filterResults()}. 11803 */ 11804 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11805 11806 @Override 11807 protected EphemeralResponse[] newArray(int size) { 11808 return new EphemeralResponse[size]; 11809 } 11810 11811 @Override 11812 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11813 return true; 11814 } 11815 11816 @Override 11817 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11818 int userId) { 11819 if (!sUserManager.exists(userId)) { 11820 return null; 11821 } 11822 final String packageName = responseObj.resolveInfo.getPackageName(); 11823 final Integer order = responseObj.getOrder(); 11824 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11825 mOrderResult.get(packageName); 11826 // ordering is enabled and this item's order isn't high enough 11827 if (lastOrderResult != null && lastOrderResult.first >= order) { 11828 return null; 11829 } 11830 final EphemeralResolveInfo res = responseObj.resolveInfo; 11831 if (order > 0) { 11832 // non-zero order, enable ordering 11833 mOrderResult.put(packageName, new Pair<>(order, res)); 11834 } 11835 return responseObj; 11836 } 11837 11838 @Override 11839 protected void filterResults(List<EphemeralResponse> results) { 11840 // only do work if ordering is enabled [most of the time it won't be] 11841 if (mOrderResult.size() == 0) { 11842 return; 11843 } 11844 int resultSize = results.size(); 11845 for (int i = 0; i < resultSize; i++) { 11846 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11847 final String packageName = info.getPackageName(); 11848 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11849 if (savedInfo == null) { 11850 // package doesn't having ordering 11851 continue; 11852 } 11853 if (savedInfo.second == info) { 11854 // circled back to the highest ordered item; remove from order list 11855 mOrderResult.remove(savedInfo); 11856 if (mOrderResult.size() == 0) { 11857 // no more ordered items 11858 break; 11859 } 11860 continue; 11861 } 11862 // item has a worse order, remove it from the result list 11863 results.remove(i); 11864 resultSize--; 11865 i--; 11866 } 11867 } 11868 } 11869 11870 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11871 new Comparator<ResolveInfo>() { 11872 public int compare(ResolveInfo r1, ResolveInfo r2) { 11873 int v1 = r1.priority; 11874 int v2 = r2.priority; 11875 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11876 if (v1 != v2) { 11877 return (v1 > v2) ? -1 : 1; 11878 } 11879 v1 = r1.preferredOrder; 11880 v2 = r2.preferredOrder; 11881 if (v1 != v2) { 11882 return (v1 > v2) ? -1 : 1; 11883 } 11884 if (r1.isDefault != r2.isDefault) { 11885 return r1.isDefault ? -1 : 1; 11886 } 11887 v1 = r1.match; 11888 v2 = r2.match; 11889 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11890 if (v1 != v2) { 11891 return (v1 > v2) ? -1 : 1; 11892 } 11893 if (r1.system != r2.system) { 11894 return r1.system ? -1 : 1; 11895 } 11896 if (r1.activityInfo != null) { 11897 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11898 } 11899 if (r1.serviceInfo != null) { 11900 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11901 } 11902 if (r1.providerInfo != null) { 11903 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11904 } 11905 return 0; 11906 } 11907 }; 11908 11909 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11910 new Comparator<ProviderInfo>() { 11911 public int compare(ProviderInfo p1, ProviderInfo p2) { 11912 final int v1 = p1.initOrder; 11913 final int v2 = p2.initOrder; 11914 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11915 } 11916 }; 11917 11918 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11919 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11920 final int[] userIds) { 11921 mHandler.post(new Runnable() { 11922 @Override 11923 public void run() { 11924 try { 11925 final IActivityManager am = ActivityManager.getService(); 11926 if (am == null) return; 11927 final int[] resolvedUserIds; 11928 if (userIds == null) { 11929 resolvedUserIds = am.getRunningUserIds(); 11930 } else { 11931 resolvedUserIds = userIds; 11932 } 11933 for (int id : resolvedUserIds) { 11934 final Intent intent = new Intent(action, 11935 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11936 if (extras != null) { 11937 intent.putExtras(extras); 11938 } 11939 if (targetPkg != null) { 11940 intent.setPackage(targetPkg); 11941 } 11942 // Modify the UID when posting to other users 11943 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11944 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11945 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11946 intent.putExtra(Intent.EXTRA_UID, uid); 11947 } 11948 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11949 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11950 if (DEBUG_BROADCASTS) { 11951 RuntimeException here = new RuntimeException("here"); 11952 here.fillInStackTrace(); 11953 Slog.d(TAG, "Sending to user " + id + ": " 11954 + intent.toShortString(false, true, false, false) 11955 + " " + intent.getExtras(), here); 11956 } 11957 am.broadcastIntent(null, intent, null, finishedReceiver, 11958 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11959 null, finishedReceiver != null, false, id); 11960 } 11961 } catch (RemoteException ex) { 11962 } 11963 } 11964 }); 11965 } 11966 11967 /** 11968 * Check if the external storage media is available. This is true if there 11969 * is a mounted external storage medium or if the external storage is 11970 * emulated. 11971 */ 11972 private boolean isExternalMediaAvailable() { 11973 return mMediaMounted || Environment.isExternalStorageEmulated(); 11974 } 11975 11976 @Override 11977 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11978 // writer 11979 synchronized (mPackages) { 11980 if (!isExternalMediaAvailable()) { 11981 // If the external storage is no longer mounted at this point, 11982 // the caller may not have been able to delete all of this 11983 // packages files and can not delete any more. Bail. 11984 return null; 11985 } 11986 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11987 if (lastPackage != null) { 11988 pkgs.remove(lastPackage); 11989 } 11990 if (pkgs.size() > 0) { 11991 return pkgs.get(0); 11992 } 11993 } 11994 return null; 11995 } 11996 11997 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11998 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11999 userId, andCode ? 1 : 0, packageName); 12000 if (mSystemReady) { 12001 msg.sendToTarget(); 12002 } else { 12003 if (mPostSystemReadyMessages == null) { 12004 mPostSystemReadyMessages = new ArrayList<>(); 12005 } 12006 mPostSystemReadyMessages.add(msg); 12007 } 12008 } 12009 12010 void startCleaningPackages() { 12011 // reader 12012 if (!isExternalMediaAvailable()) { 12013 return; 12014 } 12015 synchronized (mPackages) { 12016 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12017 return; 12018 } 12019 } 12020 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12021 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12022 IActivityManager am = ActivityManager.getService(); 12023 if (am != null) { 12024 try { 12025 am.startService(null, intent, null, mContext.getOpPackageName(), 12026 UserHandle.USER_SYSTEM); 12027 } catch (RemoteException e) { 12028 } 12029 } 12030 } 12031 12032 @Override 12033 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12034 int installFlags, String installerPackageName, int userId) { 12035 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12036 12037 final int callingUid = Binder.getCallingUid(); 12038 enforceCrossUserPermission(callingUid, userId, 12039 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12040 12041 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12042 try { 12043 if (observer != null) { 12044 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12045 } 12046 } catch (RemoteException re) { 12047 } 12048 return; 12049 } 12050 12051 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12052 installFlags |= PackageManager.INSTALL_FROM_ADB; 12053 12054 } else { 12055 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12056 // about installerPackageName. 12057 12058 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12059 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12060 } 12061 12062 UserHandle user; 12063 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12064 user = UserHandle.ALL; 12065 } else { 12066 user = new UserHandle(userId); 12067 } 12068 12069 // Only system components can circumvent runtime permissions when installing. 12070 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12071 && mContext.checkCallingOrSelfPermission(Manifest.permission 12072 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12073 throw new SecurityException("You need the " 12074 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12075 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12076 } 12077 12078 final File originFile = new File(originPath); 12079 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12080 12081 final Message msg = mHandler.obtainMessage(INIT_COPY); 12082 final VerificationInfo verificationInfo = new VerificationInfo( 12083 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12084 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12085 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12086 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12087 null /*certificates*/); 12088 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12089 msg.obj = params; 12090 12091 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12092 System.identityHashCode(msg.obj)); 12093 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12094 System.identityHashCode(msg.obj)); 12095 12096 mHandler.sendMessage(msg); 12097 } 12098 12099 void installStage(String packageName, File stagedDir, String stagedCid, 12100 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12101 String installerPackageName, int installerUid, UserHandle user, 12102 Certificate[][] certificates) { 12103 if (DEBUG_EPHEMERAL) { 12104 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12105 Slog.d(TAG, "Ephemeral install of " + packageName); 12106 } 12107 } 12108 final VerificationInfo verificationInfo = new VerificationInfo( 12109 sessionParams.originatingUri, sessionParams.referrerUri, 12110 sessionParams.originatingUid, installerUid); 12111 12112 final OriginInfo origin; 12113 if (stagedDir != null) { 12114 origin = OriginInfo.fromStagedFile(stagedDir); 12115 } else { 12116 origin = OriginInfo.fromStagedContainer(stagedCid); 12117 } 12118 12119 final Message msg = mHandler.obtainMessage(INIT_COPY); 12120 final InstallParams params = new InstallParams(origin, null, observer, 12121 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12122 verificationInfo, user, sessionParams.abiOverride, 12123 sessionParams.grantedRuntimePermissions, certificates); 12124 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12125 msg.obj = params; 12126 12127 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12128 System.identityHashCode(msg.obj)); 12129 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12130 System.identityHashCode(msg.obj)); 12131 12132 mHandler.sendMessage(msg); 12133 } 12134 12135 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12136 int userId) { 12137 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12138 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12139 } 12140 12141 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12142 int appId, int... userIds) { 12143 if (ArrayUtils.isEmpty(userIds)) { 12144 return; 12145 } 12146 Bundle extras = new Bundle(1); 12147 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12148 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12149 12150 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12151 packageName, extras, 0, null, null, userIds); 12152 if (isSystem) { 12153 mHandler.post(() -> { 12154 for (int userId : userIds) { 12155 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12156 } 12157 } 12158 ); 12159 } 12160 } 12161 12162 /** 12163 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12164 * automatically without needing an explicit launch. 12165 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12166 */ 12167 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12168 // If user is not running, the app didn't miss any broadcast 12169 if (!mUserManagerInternal.isUserRunning(userId)) { 12170 return; 12171 } 12172 final IActivityManager am = ActivityManager.getService(); 12173 try { 12174 // Deliver LOCKED_BOOT_COMPLETED first 12175 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12176 .setPackage(packageName); 12177 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12178 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12179 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12180 12181 // Deliver BOOT_COMPLETED only if user is unlocked 12182 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12183 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12184 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12185 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12186 } 12187 } catch (RemoteException e) { 12188 throw e.rethrowFromSystemServer(); 12189 } 12190 } 12191 12192 @Override 12193 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12194 int userId) { 12195 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12196 PackageSetting pkgSetting; 12197 final int uid = Binder.getCallingUid(); 12198 enforceCrossUserPermission(uid, userId, 12199 true /* requireFullPermission */, true /* checkShell */, 12200 "setApplicationHiddenSetting for user " + userId); 12201 12202 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12203 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12204 return false; 12205 } 12206 12207 long callingId = Binder.clearCallingIdentity(); 12208 try { 12209 boolean sendAdded = false; 12210 boolean sendRemoved = false; 12211 // writer 12212 synchronized (mPackages) { 12213 pkgSetting = mSettings.mPackages.get(packageName); 12214 if (pkgSetting == null) { 12215 return false; 12216 } 12217 // Do not allow "android" is being disabled 12218 if ("android".equals(packageName)) { 12219 Slog.w(TAG, "Cannot hide package: android"); 12220 return false; 12221 } 12222 // Only allow protected packages to hide themselves. 12223 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12224 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12225 Slog.w(TAG, "Not hiding protected package: " + packageName); 12226 return false; 12227 } 12228 12229 if (pkgSetting.getHidden(userId) != hidden) { 12230 pkgSetting.setHidden(hidden, userId); 12231 mSettings.writePackageRestrictionsLPr(userId); 12232 if (hidden) { 12233 sendRemoved = true; 12234 } else { 12235 sendAdded = true; 12236 } 12237 } 12238 } 12239 if (sendAdded) { 12240 sendPackageAddedForUser(packageName, pkgSetting, userId); 12241 return true; 12242 } 12243 if (sendRemoved) { 12244 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12245 "hiding pkg"); 12246 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12247 return true; 12248 } 12249 } finally { 12250 Binder.restoreCallingIdentity(callingId); 12251 } 12252 return false; 12253 } 12254 12255 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12256 int userId) { 12257 final PackageRemovedInfo info = new PackageRemovedInfo(); 12258 info.removedPackage = packageName; 12259 info.removedUsers = new int[] {userId}; 12260 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12261 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12262 } 12263 12264 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12265 if (pkgList.length > 0) { 12266 Bundle extras = new Bundle(1); 12267 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12268 12269 sendPackageBroadcast( 12270 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12271 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12272 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12273 new int[] {userId}); 12274 } 12275 } 12276 12277 /** 12278 * Returns true if application is not found or there was an error. Otherwise it returns 12279 * the hidden state of the package for the given user. 12280 */ 12281 @Override 12282 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12283 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12284 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12285 true /* requireFullPermission */, false /* checkShell */, 12286 "getApplicationHidden for user " + userId); 12287 PackageSetting pkgSetting; 12288 long callingId = Binder.clearCallingIdentity(); 12289 try { 12290 // writer 12291 synchronized (mPackages) { 12292 pkgSetting = mSettings.mPackages.get(packageName); 12293 if (pkgSetting == null) { 12294 return true; 12295 } 12296 return pkgSetting.getHidden(userId); 12297 } 12298 } finally { 12299 Binder.restoreCallingIdentity(callingId); 12300 } 12301 } 12302 12303 /** 12304 * @hide 12305 */ 12306 @Override 12307 public int installExistingPackageAsUser(String packageName, int userId) { 12308 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12309 null); 12310 PackageSetting pkgSetting; 12311 final int uid = Binder.getCallingUid(); 12312 enforceCrossUserPermission(uid, userId, 12313 true /* requireFullPermission */, true /* checkShell */, 12314 "installExistingPackage for user " + userId); 12315 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12316 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12317 } 12318 12319 long callingId = Binder.clearCallingIdentity(); 12320 try { 12321 boolean installed = false; 12322 12323 // writer 12324 synchronized (mPackages) { 12325 pkgSetting = mSettings.mPackages.get(packageName); 12326 if (pkgSetting == null) { 12327 return PackageManager.INSTALL_FAILED_INVALID_URI; 12328 } 12329 if (!pkgSetting.getInstalled(userId)) { 12330 pkgSetting.setInstalled(true, userId); 12331 pkgSetting.setHidden(false, userId); 12332 mSettings.writePackageRestrictionsLPr(userId); 12333 installed = true; 12334 } 12335 } 12336 12337 if (installed) { 12338 if (pkgSetting.pkg != null) { 12339 synchronized (mInstallLock) { 12340 // We don't need to freeze for a brand new install 12341 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12342 } 12343 } 12344 sendPackageAddedForUser(packageName, pkgSetting, userId); 12345 } 12346 } finally { 12347 Binder.restoreCallingIdentity(callingId); 12348 } 12349 12350 return PackageManager.INSTALL_SUCCEEDED; 12351 } 12352 12353 boolean isUserRestricted(int userId, String restrictionKey) { 12354 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12355 if (restrictions.getBoolean(restrictionKey, false)) { 12356 Log.w(TAG, "User is restricted: " + restrictionKey); 12357 return true; 12358 } 12359 return false; 12360 } 12361 12362 @Override 12363 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12364 int userId) { 12365 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12366 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12367 true /* requireFullPermission */, true /* checkShell */, 12368 "setPackagesSuspended for user " + userId); 12369 12370 if (ArrayUtils.isEmpty(packageNames)) { 12371 return packageNames; 12372 } 12373 12374 // List of package names for whom the suspended state has changed. 12375 List<String> changedPackages = new ArrayList<>(packageNames.length); 12376 // List of package names for whom the suspended state is not set as requested in this 12377 // method. 12378 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12379 long callingId = Binder.clearCallingIdentity(); 12380 try { 12381 for (int i = 0; i < packageNames.length; i++) { 12382 String packageName = packageNames[i]; 12383 boolean changed = false; 12384 final int appId; 12385 synchronized (mPackages) { 12386 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12387 if (pkgSetting == null) { 12388 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12389 + "\". Skipping suspending/un-suspending."); 12390 unactionedPackages.add(packageName); 12391 continue; 12392 } 12393 appId = pkgSetting.appId; 12394 if (pkgSetting.getSuspended(userId) != suspended) { 12395 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12396 unactionedPackages.add(packageName); 12397 continue; 12398 } 12399 pkgSetting.setSuspended(suspended, userId); 12400 mSettings.writePackageRestrictionsLPr(userId); 12401 changed = true; 12402 changedPackages.add(packageName); 12403 } 12404 } 12405 12406 if (changed && suspended) { 12407 killApplication(packageName, UserHandle.getUid(userId, appId), 12408 "suspending package"); 12409 } 12410 } 12411 } finally { 12412 Binder.restoreCallingIdentity(callingId); 12413 } 12414 12415 if (!changedPackages.isEmpty()) { 12416 sendPackagesSuspendedForUser(changedPackages.toArray( 12417 new String[changedPackages.size()]), userId, suspended); 12418 } 12419 12420 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12421 } 12422 12423 @Override 12424 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12425 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12426 true /* requireFullPermission */, false /* checkShell */, 12427 "isPackageSuspendedForUser for user " + userId); 12428 synchronized (mPackages) { 12429 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12430 if (pkgSetting == null) { 12431 throw new IllegalArgumentException("Unknown target package: " + packageName); 12432 } 12433 return pkgSetting.getSuspended(userId); 12434 } 12435 } 12436 12437 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12438 if (isPackageDeviceAdmin(packageName, userId)) { 12439 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12440 + "\": has an active device admin"); 12441 return false; 12442 } 12443 12444 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12445 if (packageName.equals(activeLauncherPackageName)) { 12446 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12447 + "\": contains the active launcher"); 12448 return false; 12449 } 12450 12451 if (packageName.equals(mRequiredInstallerPackage)) { 12452 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12453 + "\": required for package installation"); 12454 return false; 12455 } 12456 12457 if (packageName.equals(mRequiredUninstallerPackage)) { 12458 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12459 + "\": required for package uninstallation"); 12460 return false; 12461 } 12462 12463 if (packageName.equals(mRequiredVerifierPackage)) { 12464 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12465 + "\": required for package verification"); 12466 return false; 12467 } 12468 12469 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12470 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12471 + "\": is the default dialer"); 12472 return false; 12473 } 12474 12475 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12476 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12477 + "\": protected package"); 12478 return false; 12479 } 12480 12481 return true; 12482 } 12483 12484 private String getActiveLauncherPackageName(int userId) { 12485 Intent intent = new Intent(Intent.ACTION_MAIN); 12486 intent.addCategory(Intent.CATEGORY_HOME); 12487 ResolveInfo resolveInfo = resolveIntent( 12488 intent, 12489 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12490 PackageManager.MATCH_DEFAULT_ONLY, 12491 userId); 12492 12493 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12494 } 12495 12496 private String getDefaultDialerPackageName(int userId) { 12497 synchronized (mPackages) { 12498 return mSettings.getDefaultDialerPackageNameLPw(userId); 12499 } 12500 } 12501 12502 @Override 12503 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12504 mContext.enforceCallingOrSelfPermission( 12505 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12506 "Only package verification agents can verify applications"); 12507 12508 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12509 final PackageVerificationResponse response = new PackageVerificationResponse( 12510 verificationCode, Binder.getCallingUid()); 12511 msg.arg1 = id; 12512 msg.obj = response; 12513 mHandler.sendMessage(msg); 12514 } 12515 12516 @Override 12517 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12518 long millisecondsToDelay) { 12519 mContext.enforceCallingOrSelfPermission( 12520 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12521 "Only package verification agents can extend verification timeouts"); 12522 12523 final PackageVerificationState state = mPendingVerification.get(id); 12524 final PackageVerificationResponse response = new PackageVerificationResponse( 12525 verificationCodeAtTimeout, Binder.getCallingUid()); 12526 12527 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12528 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12529 } 12530 if (millisecondsToDelay < 0) { 12531 millisecondsToDelay = 0; 12532 } 12533 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12534 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12535 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12536 } 12537 12538 if ((state != null) && !state.timeoutExtended()) { 12539 state.extendTimeout(); 12540 12541 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12542 msg.arg1 = id; 12543 msg.obj = response; 12544 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12545 } 12546 } 12547 12548 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12549 int verificationCode, UserHandle user) { 12550 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12551 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12552 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12553 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12554 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12555 12556 mContext.sendBroadcastAsUser(intent, user, 12557 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12558 } 12559 12560 private ComponentName matchComponentForVerifier(String packageName, 12561 List<ResolveInfo> receivers) { 12562 ActivityInfo targetReceiver = null; 12563 12564 final int NR = receivers.size(); 12565 for (int i = 0; i < NR; i++) { 12566 final ResolveInfo info = receivers.get(i); 12567 if (info.activityInfo == null) { 12568 continue; 12569 } 12570 12571 if (packageName.equals(info.activityInfo.packageName)) { 12572 targetReceiver = info.activityInfo; 12573 break; 12574 } 12575 } 12576 12577 if (targetReceiver == null) { 12578 return null; 12579 } 12580 12581 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12582 } 12583 12584 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12585 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12586 if (pkgInfo.verifiers.length == 0) { 12587 return null; 12588 } 12589 12590 final int N = pkgInfo.verifiers.length; 12591 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12592 for (int i = 0; i < N; i++) { 12593 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12594 12595 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12596 receivers); 12597 if (comp == null) { 12598 continue; 12599 } 12600 12601 final int verifierUid = getUidForVerifier(verifierInfo); 12602 if (verifierUid == -1) { 12603 continue; 12604 } 12605 12606 if (DEBUG_VERIFY) { 12607 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12608 + " with the correct signature"); 12609 } 12610 sufficientVerifiers.add(comp); 12611 verificationState.addSufficientVerifier(verifierUid); 12612 } 12613 12614 return sufficientVerifiers; 12615 } 12616 12617 private int getUidForVerifier(VerifierInfo verifierInfo) { 12618 synchronized (mPackages) { 12619 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12620 if (pkg == null) { 12621 return -1; 12622 } else if (pkg.mSignatures.length != 1) { 12623 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12624 + " has more than one signature; ignoring"); 12625 return -1; 12626 } 12627 12628 /* 12629 * If the public key of the package's signature does not match 12630 * our expected public key, then this is a different package and 12631 * we should skip. 12632 */ 12633 12634 final byte[] expectedPublicKey; 12635 try { 12636 final Signature verifierSig = pkg.mSignatures[0]; 12637 final PublicKey publicKey = verifierSig.getPublicKey(); 12638 expectedPublicKey = publicKey.getEncoded(); 12639 } catch (CertificateException e) { 12640 return -1; 12641 } 12642 12643 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12644 12645 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12646 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12647 + " does not have the expected public key; ignoring"); 12648 return -1; 12649 } 12650 12651 return pkg.applicationInfo.uid; 12652 } 12653 } 12654 12655 @Override 12656 public void finishPackageInstall(int token, boolean didLaunch) { 12657 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12658 12659 if (DEBUG_INSTALL) { 12660 Slog.v(TAG, "BM finishing package install for " + token); 12661 } 12662 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12663 12664 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12665 mHandler.sendMessage(msg); 12666 } 12667 12668 /** 12669 * Get the verification agent timeout. 12670 * 12671 * @return verification timeout in milliseconds 12672 */ 12673 private long getVerificationTimeout() { 12674 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12675 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12676 DEFAULT_VERIFICATION_TIMEOUT); 12677 } 12678 12679 /** 12680 * Get the default verification agent response code. 12681 * 12682 * @return default verification response code 12683 */ 12684 private int getDefaultVerificationResponse() { 12685 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12686 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12687 DEFAULT_VERIFICATION_RESPONSE); 12688 } 12689 12690 /** 12691 * Check whether or not package verification has been enabled. 12692 * 12693 * @return true if verification should be performed 12694 */ 12695 private boolean isVerificationEnabled(int userId, int installFlags) { 12696 if (!DEFAULT_VERIFY_ENABLE) { 12697 return false; 12698 } 12699 // Ephemeral apps don't get the full verification treatment 12700 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12701 if (DEBUG_EPHEMERAL) { 12702 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12703 } 12704 return false; 12705 } 12706 12707 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12708 12709 // Check if installing from ADB 12710 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12711 // Do not run verification in a test harness environment 12712 if (ActivityManager.isRunningInTestHarness()) { 12713 return false; 12714 } 12715 if (ensureVerifyAppsEnabled) { 12716 return true; 12717 } 12718 // Check if the developer does not want package verification for ADB installs 12719 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12720 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12721 return false; 12722 } 12723 } 12724 12725 if (ensureVerifyAppsEnabled) { 12726 return true; 12727 } 12728 12729 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12730 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12731 } 12732 12733 @Override 12734 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12735 throws RemoteException { 12736 mContext.enforceCallingOrSelfPermission( 12737 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12738 "Only intentfilter verification agents can verify applications"); 12739 12740 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12741 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12742 Binder.getCallingUid(), verificationCode, failedDomains); 12743 msg.arg1 = id; 12744 msg.obj = response; 12745 mHandler.sendMessage(msg); 12746 } 12747 12748 @Override 12749 public int getIntentVerificationStatus(String packageName, int userId) { 12750 synchronized (mPackages) { 12751 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12752 } 12753 } 12754 12755 @Override 12756 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12757 mContext.enforceCallingOrSelfPermission( 12758 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12759 12760 boolean result = false; 12761 synchronized (mPackages) { 12762 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12763 } 12764 if (result) { 12765 scheduleWritePackageRestrictionsLocked(userId); 12766 } 12767 return result; 12768 } 12769 12770 @Override 12771 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12772 String packageName) { 12773 synchronized (mPackages) { 12774 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12775 } 12776 } 12777 12778 @Override 12779 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12780 if (TextUtils.isEmpty(packageName)) { 12781 return ParceledListSlice.emptyList(); 12782 } 12783 synchronized (mPackages) { 12784 PackageParser.Package pkg = mPackages.get(packageName); 12785 if (pkg == null || pkg.activities == null) { 12786 return ParceledListSlice.emptyList(); 12787 } 12788 final int count = pkg.activities.size(); 12789 ArrayList<IntentFilter> result = new ArrayList<>(); 12790 for (int n=0; n<count; n++) { 12791 PackageParser.Activity activity = pkg.activities.get(n); 12792 if (activity.intents != null && activity.intents.size() > 0) { 12793 result.addAll(activity.intents); 12794 } 12795 } 12796 return new ParceledListSlice<>(result); 12797 } 12798 } 12799 12800 @Override 12801 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12802 mContext.enforceCallingOrSelfPermission( 12803 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12804 12805 synchronized (mPackages) { 12806 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12807 if (packageName != null) { 12808 result |= updateIntentVerificationStatus(packageName, 12809 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12810 userId); 12811 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12812 packageName, userId); 12813 } 12814 return result; 12815 } 12816 } 12817 12818 @Override 12819 public String getDefaultBrowserPackageName(int userId) { 12820 synchronized (mPackages) { 12821 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12822 } 12823 } 12824 12825 /** 12826 * Get the "allow unknown sources" setting. 12827 * 12828 * @return the current "allow unknown sources" setting 12829 */ 12830 private int getUnknownSourcesSettings() { 12831 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12832 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12833 -1); 12834 } 12835 12836 @Override 12837 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12838 final int uid = Binder.getCallingUid(); 12839 // writer 12840 synchronized (mPackages) { 12841 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12842 if (targetPackageSetting == null) { 12843 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12844 } 12845 12846 PackageSetting installerPackageSetting; 12847 if (installerPackageName != null) { 12848 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12849 if (installerPackageSetting == null) { 12850 throw new IllegalArgumentException("Unknown installer package: " 12851 + installerPackageName); 12852 } 12853 } else { 12854 installerPackageSetting = null; 12855 } 12856 12857 Signature[] callerSignature; 12858 Object obj = mSettings.getUserIdLPr(uid); 12859 if (obj != null) { 12860 if (obj instanceof SharedUserSetting) { 12861 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12862 } else if (obj instanceof PackageSetting) { 12863 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12864 } else { 12865 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12866 } 12867 } else { 12868 throw new SecurityException("Unknown calling UID: " + uid); 12869 } 12870 12871 // Verify: can't set installerPackageName to a package that is 12872 // not signed with the same cert as the caller. 12873 if (installerPackageSetting != null) { 12874 if (compareSignatures(callerSignature, 12875 installerPackageSetting.signatures.mSignatures) 12876 != PackageManager.SIGNATURE_MATCH) { 12877 throw new SecurityException( 12878 "Caller does not have same cert as new installer package " 12879 + installerPackageName); 12880 } 12881 } 12882 12883 // Verify: if target already has an installer package, it must 12884 // be signed with the same cert as the caller. 12885 if (targetPackageSetting.installerPackageName != null) { 12886 PackageSetting setting = mSettings.mPackages.get( 12887 targetPackageSetting.installerPackageName); 12888 // If the currently set package isn't valid, then it's always 12889 // okay to change it. 12890 if (setting != null) { 12891 if (compareSignatures(callerSignature, 12892 setting.signatures.mSignatures) 12893 != PackageManager.SIGNATURE_MATCH) { 12894 throw new SecurityException( 12895 "Caller does not have same cert as old installer package " 12896 + targetPackageSetting.installerPackageName); 12897 } 12898 } 12899 } 12900 12901 // Okay! 12902 targetPackageSetting.installerPackageName = installerPackageName; 12903 if (installerPackageName != null) { 12904 mSettings.mInstallerPackages.add(installerPackageName); 12905 } 12906 scheduleWriteSettingsLocked(); 12907 } 12908 } 12909 12910 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12911 // Queue up an async operation since the package installation may take a little while. 12912 mHandler.post(new Runnable() { 12913 public void run() { 12914 mHandler.removeCallbacks(this); 12915 // Result object to be returned 12916 PackageInstalledInfo res = new PackageInstalledInfo(); 12917 res.setReturnCode(currentStatus); 12918 res.uid = -1; 12919 res.pkg = null; 12920 res.removedInfo = null; 12921 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12922 args.doPreInstall(res.returnCode); 12923 synchronized (mInstallLock) { 12924 installPackageTracedLI(args, res); 12925 } 12926 args.doPostInstall(res.returnCode, res.uid); 12927 } 12928 12929 // A restore should be performed at this point if (a) the install 12930 // succeeded, (b) the operation is not an update, and (c) the new 12931 // package has not opted out of backup participation. 12932 final boolean update = res.removedInfo != null 12933 && res.removedInfo.removedPackage != null; 12934 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12935 boolean doRestore = !update 12936 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12937 12938 // Set up the post-install work request bookkeeping. This will be used 12939 // and cleaned up by the post-install event handling regardless of whether 12940 // there's a restore pass performed. Token values are >= 1. 12941 int token; 12942 if (mNextInstallToken < 0) mNextInstallToken = 1; 12943 token = mNextInstallToken++; 12944 12945 PostInstallData data = new PostInstallData(args, res); 12946 mRunningInstalls.put(token, data); 12947 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12948 12949 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12950 // Pass responsibility to the Backup Manager. It will perform a 12951 // restore if appropriate, then pass responsibility back to the 12952 // Package Manager to run the post-install observer callbacks 12953 // and broadcasts. 12954 IBackupManager bm = IBackupManager.Stub.asInterface( 12955 ServiceManager.getService(Context.BACKUP_SERVICE)); 12956 if (bm != null) { 12957 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12958 + " to BM for possible restore"); 12959 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12960 try { 12961 // TODO: http://b/22388012 12962 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12963 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12964 } else { 12965 doRestore = false; 12966 } 12967 } catch (RemoteException e) { 12968 // can't happen; the backup manager is local 12969 } catch (Exception e) { 12970 Slog.e(TAG, "Exception trying to enqueue restore", e); 12971 doRestore = false; 12972 } 12973 } else { 12974 Slog.e(TAG, "Backup Manager not found!"); 12975 doRestore = false; 12976 } 12977 } 12978 12979 if (!doRestore) { 12980 // No restore possible, or the Backup Manager was mysteriously not 12981 // available -- just fire the post-install work request directly. 12982 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12983 12984 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12985 12986 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12987 mHandler.sendMessage(msg); 12988 } 12989 } 12990 }); 12991 } 12992 12993 /** 12994 * Callback from PackageSettings whenever an app is first transitioned out of the 12995 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12996 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12997 * here whether the app is the target of an ongoing install, and only send the 12998 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12999 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13000 * handling. 13001 */ 13002 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13003 // Serialize this with the rest of the install-process message chain. In the 13004 // restore-at-install case, this Runnable will necessarily run before the 13005 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13006 // are coherent. In the non-restore case, the app has already completed install 13007 // and been launched through some other means, so it is not in a problematic 13008 // state for observers to see the FIRST_LAUNCH signal. 13009 mHandler.post(new Runnable() { 13010 @Override 13011 public void run() { 13012 for (int i = 0; i < mRunningInstalls.size(); i++) { 13013 final PostInstallData data = mRunningInstalls.valueAt(i); 13014 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13015 continue; 13016 } 13017 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13018 // right package; but is it for the right user? 13019 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13020 if (userId == data.res.newUsers[uIndex]) { 13021 if (DEBUG_BACKUP) { 13022 Slog.i(TAG, "Package " + pkgName 13023 + " being restored so deferring FIRST_LAUNCH"); 13024 } 13025 return; 13026 } 13027 } 13028 } 13029 } 13030 // didn't find it, so not being restored 13031 if (DEBUG_BACKUP) { 13032 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13033 } 13034 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13035 } 13036 }); 13037 } 13038 13039 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13040 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13041 installerPkg, null, userIds); 13042 } 13043 13044 private abstract class HandlerParams { 13045 private static final int MAX_RETRIES = 4; 13046 13047 /** 13048 * Number of times startCopy() has been attempted and had a non-fatal 13049 * error. 13050 */ 13051 private int mRetries = 0; 13052 13053 /** User handle for the user requesting the information or installation. */ 13054 private final UserHandle mUser; 13055 String traceMethod; 13056 int traceCookie; 13057 13058 HandlerParams(UserHandle user) { 13059 mUser = user; 13060 } 13061 13062 UserHandle getUser() { 13063 return mUser; 13064 } 13065 13066 HandlerParams setTraceMethod(String traceMethod) { 13067 this.traceMethod = traceMethod; 13068 return this; 13069 } 13070 13071 HandlerParams setTraceCookie(int traceCookie) { 13072 this.traceCookie = traceCookie; 13073 return this; 13074 } 13075 13076 final boolean startCopy() { 13077 boolean res; 13078 try { 13079 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13080 13081 if (++mRetries > MAX_RETRIES) { 13082 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13083 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13084 handleServiceError(); 13085 return false; 13086 } else { 13087 handleStartCopy(); 13088 res = true; 13089 } 13090 } catch (RemoteException e) { 13091 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13092 mHandler.sendEmptyMessage(MCS_RECONNECT); 13093 res = false; 13094 } 13095 handleReturnCode(); 13096 return res; 13097 } 13098 13099 final void serviceError() { 13100 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13101 handleServiceError(); 13102 handleReturnCode(); 13103 } 13104 13105 abstract void handleStartCopy() throws RemoteException; 13106 abstract void handleServiceError(); 13107 abstract void handleReturnCode(); 13108 } 13109 13110 class MeasureParams extends HandlerParams { 13111 private final PackageStats mStats; 13112 private boolean mSuccess; 13113 13114 private final IPackageStatsObserver mObserver; 13115 13116 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 13117 super(new UserHandle(stats.userHandle)); 13118 mObserver = observer; 13119 mStats = stats; 13120 } 13121 13122 @Override 13123 public String toString() { 13124 return "MeasureParams{" 13125 + Integer.toHexString(System.identityHashCode(this)) 13126 + " " + mStats.packageName + "}"; 13127 } 13128 13129 @Override 13130 void handleStartCopy() throws RemoteException { 13131 synchronized (mInstallLock) { 13132 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 13133 } 13134 13135 if (mSuccess) { 13136 boolean mounted = false; 13137 try { 13138 final String status = Environment.getExternalStorageState(); 13139 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13140 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13141 } catch (Exception e) { 13142 } 13143 13144 if (mounted) { 13145 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13146 13147 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13148 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13149 13150 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13151 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13152 13153 // Always subtract cache size, since it's a subdirectory 13154 mStats.externalDataSize -= mStats.externalCacheSize; 13155 13156 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13157 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13158 13159 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13160 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13161 } 13162 } 13163 } 13164 13165 @Override 13166 void handleReturnCode() { 13167 if (mObserver != null) { 13168 try { 13169 mObserver.onGetStatsCompleted(mStats, mSuccess); 13170 } catch (RemoteException e) { 13171 Slog.i(TAG, "Observer no longer exists."); 13172 } 13173 } 13174 } 13175 13176 @Override 13177 void handleServiceError() { 13178 Slog.e(TAG, "Could not measure application " + mStats.packageName 13179 + " external storage"); 13180 } 13181 } 13182 13183 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13184 throws RemoteException { 13185 long result = 0; 13186 for (File path : paths) { 13187 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13188 } 13189 return result; 13190 } 13191 13192 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13193 for (File path : paths) { 13194 try { 13195 mcs.clearDirectory(path.getAbsolutePath()); 13196 } catch (RemoteException e) { 13197 } 13198 } 13199 } 13200 13201 static class OriginInfo { 13202 /** 13203 * Location where install is coming from, before it has been 13204 * copied/renamed into place. This could be a single monolithic APK 13205 * file, or a cluster directory. This location may be untrusted. 13206 */ 13207 final File file; 13208 final String cid; 13209 13210 /** 13211 * Flag indicating that {@link #file} or {@link #cid} has already been 13212 * staged, meaning downstream users don't need to defensively copy the 13213 * contents. 13214 */ 13215 final boolean staged; 13216 13217 /** 13218 * Flag indicating that {@link #file} or {@link #cid} is an already 13219 * installed app that is being moved. 13220 */ 13221 final boolean existing; 13222 13223 final String resolvedPath; 13224 final File resolvedFile; 13225 13226 static OriginInfo fromNothing() { 13227 return new OriginInfo(null, null, false, false); 13228 } 13229 13230 static OriginInfo fromUntrustedFile(File file) { 13231 return new OriginInfo(file, null, false, false); 13232 } 13233 13234 static OriginInfo fromExistingFile(File file) { 13235 return new OriginInfo(file, null, false, true); 13236 } 13237 13238 static OriginInfo fromStagedFile(File file) { 13239 return new OriginInfo(file, null, true, false); 13240 } 13241 13242 static OriginInfo fromStagedContainer(String cid) { 13243 return new OriginInfo(null, cid, true, false); 13244 } 13245 13246 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13247 this.file = file; 13248 this.cid = cid; 13249 this.staged = staged; 13250 this.existing = existing; 13251 13252 if (cid != null) { 13253 resolvedPath = PackageHelper.getSdDir(cid); 13254 resolvedFile = new File(resolvedPath); 13255 } else if (file != null) { 13256 resolvedPath = file.getAbsolutePath(); 13257 resolvedFile = file; 13258 } else { 13259 resolvedPath = null; 13260 resolvedFile = null; 13261 } 13262 } 13263 } 13264 13265 static class MoveInfo { 13266 final int moveId; 13267 final String fromUuid; 13268 final String toUuid; 13269 final String packageName; 13270 final String dataAppName; 13271 final int appId; 13272 final String seinfo; 13273 final int targetSdkVersion; 13274 13275 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13276 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13277 this.moveId = moveId; 13278 this.fromUuid = fromUuid; 13279 this.toUuid = toUuid; 13280 this.packageName = packageName; 13281 this.dataAppName = dataAppName; 13282 this.appId = appId; 13283 this.seinfo = seinfo; 13284 this.targetSdkVersion = targetSdkVersion; 13285 } 13286 } 13287 13288 static class VerificationInfo { 13289 /** A constant used to indicate that a uid value is not present. */ 13290 public static final int NO_UID = -1; 13291 13292 /** URI referencing where the package was downloaded from. */ 13293 final Uri originatingUri; 13294 13295 /** HTTP referrer URI associated with the originatingURI. */ 13296 final Uri referrer; 13297 13298 /** UID of the application that the install request originated from. */ 13299 final int originatingUid; 13300 13301 /** UID of application requesting the install */ 13302 final int installerUid; 13303 13304 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13305 this.originatingUri = originatingUri; 13306 this.referrer = referrer; 13307 this.originatingUid = originatingUid; 13308 this.installerUid = installerUid; 13309 } 13310 } 13311 13312 class InstallParams extends HandlerParams { 13313 final OriginInfo origin; 13314 final MoveInfo move; 13315 final IPackageInstallObserver2 observer; 13316 int installFlags; 13317 final String installerPackageName; 13318 final String volumeUuid; 13319 private InstallArgs mArgs; 13320 private int mRet; 13321 final String packageAbiOverride; 13322 final String[] grantedRuntimePermissions; 13323 final VerificationInfo verificationInfo; 13324 final Certificate[][] certificates; 13325 13326 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13327 int installFlags, String installerPackageName, String volumeUuid, 13328 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13329 String[] grantedPermissions, Certificate[][] certificates) { 13330 super(user); 13331 this.origin = origin; 13332 this.move = move; 13333 this.observer = observer; 13334 this.installFlags = installFlags; 13335 this.installerPackageName = installerPackageName; 13336 this.volumeUuid = volumeUuid; 13337 this.verificationInfo = verificationInfo; 13338 this.packageAbiOverride = packageAbiOverride; 13339 this.grantedRuntimePermissions = grantedPermissions; 13340 this.certificates = certificates; 13341 } 13342 13343 @Override 13344 public String toString() { 13345 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13346 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13347 } 13348 13349 private int installLocationPolicy(PackageInfoLite pkgLite) { 13350 String packageName = pkgLite.packageName; 13351 int installLocation = pkgLite.installLocation; 13352 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13353 // reader 13354 synchronized (mPackages) { 13355 // Currently installed package which the new package is attempting to replace or 13356 // null if no such package is installed. 13357 PackageParser.Package installedPkg = mPackages.get(packageName); 13358 // Package which currently owns the data which the new package will own if installed. 13359 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13360 // will be null whereas dataOwnerPkg will contain information about the package 13361 // which was uninstalled while keeping its data. 13362 PackageParser.Package dataOwnerPkg = installedPkg; 13363 if (dataOwnerPkg == null) { 13364 PackageSetting ps = mSettings.mPackages.get(packageName); 13365 if (ps != null) { 13366 dataOwnerPkg = ps.pkg; 13367 } 13368 } 13369 13370 if (dataOwnerPkg != null) { 13371 // If installed, the package will get access to data left on the device by its 13372 // predecessor. As a security measure, this is permited only if this is not a 13373 // version downgrade or if the predecessor package is marked as debuggable and 13374 // a downgrade is explicitly requested. 13375 // 13376 // On debuggable platform builds, downgrades are permitted even for 13377 // non-debuggable packages to make testing easier. Debuggable platform builds do 13378 // not offer security guarantees and thus it's OK to disable some security 13379 // mechanisms to make debugging/testing easier on those builds. However, even on 13380 // debuggable builds downgrades of packages are permitted only if requested via 13381 // installFlags. This is because we aim to keep the behavior of debuggable 13382 // platform builds as close as possible to the behavior of non-debuggable 13383 // platform builds. 13384 final boolean downgradeRequested = 13385 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13386 final boolean packageDebuggable = 13387 (dataOwnerPkg.applicationInfo.flags 13388 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13389 final boolean downgradePermitted = 13390 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13391 if (!downgradePermitted) { 13392 try { 13393 checkDowngrade(dataOwnerPkg, pkgLite); 13394 } catch (PackageManagerException e) { 13395 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13396 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13397 } 13398 } 13399 } 13400 13401 if (installedPkg != null) { 13402 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13403 // Check for updated system application. 13404 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13405 if (onSd) { 13406 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13407 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13408 } 13409 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13410 } else { 13411 if (onSd) { 13412 // Install flag overrides everything. 13413 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13414 } 13415 // If current upgrade specifies particular preference 13416 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13417 // Application explicitly specified internal. 13418 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13419 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13420 // App explictly prefers external. Let policy decide 13421 } else { 13422 // Prefer previous location 13423 if (isExternal(installedPkg)) { 13424 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13425 } 13426 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13427 } 13428 } 13429 } else { 13430 // Invalid install. Return error code 13431 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13432 } 13433 } 13434 } 13435 // All the special cases have been taken care of. 13436 // Return result based on recommended install location. 13437 if (onSd) { 13438 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13439 } 13440 return pkgLite.recommendedInstallLocation; 13441 } 13442 13443 /* 13444 * Invoke remote method to get package information and install 13445 * location values. Override install location based on default 13446 * policy if needed and then create install arguments based 13447 * on the install location. 13448 */ 13449 public void handleStartCopy() throws RemoteException { 13450 int ret = PackageManager.INSTALL_SUCCEEDED; 13451 13452 // If we're already staged, we've firmly committed to an install location 13453 if (origin.staged) { 13454 if (origin.file != null) { 13455 installFlags |= PackageManager.INSTALL_INTERNAL; 13456 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13457 } else if (origin.cid != null) { 13458 installFlags |= PackageManager.INSTALL_EXTERNAL; 13459 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13460 } else { 13461 throw new IllegalStateException("Invalid stage location"); 13462 } 13463 } 13464 13465 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13466 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13467 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13468 PackageInfoLite pkgLite = null; 13469 13470 if (onInt && onSd) { 13471 // Check if both bits are set. 13472 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13473 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13474 } else if (onSd && ephemeral) { 13475 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13476 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13477 } else { 13478 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13479 packageAbiOverride); 13480 13481 if (DEBUG_EPHEMERAL && ephemeral) { 13482 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13483 } 13484 13485 /* 13486 * If we have too little free space, try to free cache 13487 * before giving up. 13488 */ 13489 if (!origin.staged && pkgLite.recommendedInstallLocation 13490 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13491 // TODO: focus freeing disk space on the target device 13492 final StorageManager storage = StorageManager.from(mContext); 13493 final long lowThreshold = storage.getStorageLowBytes( 13494 Environment.getDataDirectory()); 13495 13496 final long sizeBytes = mContainerService.calculateInstalledSize( 13497 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13498 13499 try { 13500 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13501 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13502 installFlags, packageAbiOverride); 13503 } catch (InstallerException e) { 13504 Slog.w(TAG, "Failed to free cache", e); 13505 } 13506 13507 /* 13508 * The cache free must have deleted the file we 13509 * downloaded to install. 13510 * 13511 * TODO: fix the "freeCache" call to not delete 13512 * the file we care about. 13513 */ 13514 if (pkgLite.recommendedInstallLocation 13515 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13516 pkgLite.recommendedInstallLocation 13517 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13518 } 13519 } 13520 } 13521 13522 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13523 int loc = pkgLite.recommendedInstallLocation; 13524 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13525 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13526 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13527 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13528 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13529 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13530 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13531 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13532 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13533 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13534 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13535 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13536 } else { 13537 // Override with defaults if needed. 13538 loc = installLocationPolicy(pkgLite); 13539 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13540 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13541 } else if (!onSd && !onInt) { 13542 // Override install location with flags 13543 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13544 // Set the flag to install on external media. 13545 installFlags |= PackageManager.INSTALL_EXTERNAL; 13546 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13547 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13548 if (DEBUG_EPHEMERAL) { 13549 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13550 } 13551 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13552 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13553 |PackageManager.INSTALL_INTERNAL); 13554 } else { 13555 // Make sure the flag for installing on external 13556 // media is unset 13557 installFlags |= PackageManager.INSTALL_INTERNAL; 13558 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13559 } 13560 } 13561 } 13562 } 13563 13564 final InstallArgs args = createInstallArgs(this); 13565 mArgs = args; 13566 13567 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13568 // TODO: http://b/22976637 13569 // Apps installed for "all" users use the device owner to verify the app 13570 UserHandle verifierUser = getUser(); 13571 if (verifierUser == UserHandle.ALL) { 13572 verifierUser = UserHandle.SYSTEM; 13573 } 13574 13575 /* 13576 * Determine if we have any installed package verifiers. If we 13577 * do, then we'll defer to them to verify the packages. 13578 */ 13579 final int requiredUid = mRequiredVerifierPackage == null ? -1 13580 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13581 verifierUser.getIdentifier()); 13582 if (!origin.existing && requiredUid != -1 13583 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13584 final Intent verification = new Intent( 13585 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13586 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13587 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13588 PACKAGE_MIME_TYPE); 13589 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13590 13591 // Query all live verifiers based on current user state 13592 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13593 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13594 13595 if (DEBUG_VERIFY) { 13596 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13597 + verification.toString() + " with " + pkgLite.verifiers.length 13598 + " optional verifiers"); 13599 } 13600 13601 final int verificationId = mPendingVerificationToken++; 13602 13603 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13604 13605 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13606 installerPackageName); 13607 13608 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13609 installFlags); 13610 13611 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13612 pkgLite.packageName); 13613 13614 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13615 pkgLite.versionCode); 13616 13617 if (verificationInfo != null) { 13618 if (verificationInfo.originatingUri != null) { 13619 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13620 verificationInfo.originatingUri); 13621 } 13622 if (verificationInfo.referrer != null) { 13623 verification.putExtra(Intent.EXTRA_REFERRER, 13624 verificationInfo.referrer); 13625 } 13626 if (verificationInfo.originatingUid >= 0) { 13627 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13628 verificationInfo.originatingUid); 13629 } 13630 if (verificationInfo.installerUid >= 0) { 13631 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13632 verificationInfo.installerUid); 13633 } 13634 } 13635 13636 final PackageVerificationState verificationState = new PackageVerificationState( 13637 requiredUid, args); 13638 13639 mPendingVerification.append(verificationId, verificationState); 13640 13641 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13642 receivers, verificationState); 13643 13644 /* 13645 * If any sufficient verifiers were listed in the package 13646 * manifest, attempt to ask them. 13647 */ 13648 if (sufficientVerifiers != null) { 13649 final int N = sufficientVerifiers.size(); 13650 if (N == 0) { 13651 Slog.i(TAG, "Additional verifiers required, but none installed."); 13652 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13653 } else { 13654 for (int i = 0; i < N; i++) { 13655 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13656 13657 final Intent sufficientIntent = new Intent(verification); 13658 sufficientIntent.setComponent(verifierComponent); 13659 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13660 } 13661 } 13662 } 13663 13664 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13665 mRequiredVerifierPackage, receivers); 13666 if (ret == PackageManager.INSTALL_SUCCEEDED 13667 && mRequiredVerifierPackage != null) { 13668 Trace.asyncTraceBegin( 13669 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13670 /* 13671 * Send the intent to the required verification agent, 13672 * but only start the verification timeout after the 13673 * target BroadcastReceivers have run. 13674 */ 13675 verification.setComponent(requiredVerifierComponent); 13676 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13677 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13678 new BroadcastReceiver() { 13679 @Override 13680 public void onReceive(Context context, Intent intent) { 13681 final Message msg = mHandler 13682 .obtainMessage(CHECK_PENDING_VERIFICATION); 13683 msg.arg1 = verificationId; 13684 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13685 } 13686 }, null, 0, null, null); 13687 13688 /* 13689 * We don't want the copy to proceed until verification 13690 * succeeds, so null out this field. 13691 */ 13692 mArgs = null; 13693 } 13694 } else { 13695 /* 13696 * No package verification is enabled, so immediately start 13697 * the remote call to initiate copy using temporary file. 13698 */ 13699 ret = args.copyApk(mContainerService, true); 13700 } 13701 } 13702 13703 mRet = ret; 13704 } 13705 13706 @Override 13707 void handleReturnCode() { 13708 // If mArgs is null, then MCS couldn't be reached. When it 13709 // reconnects, it will try again to install. At that point, this 13710 // will succeed. 13711 if (mArgs != null) { 13712 processPendingInstall(mArgs, mRet); 13713 } 13714 } 13715 13716 @Override 13717 void handleServiceError() { 13718 mArgs = createInstallArgs(this); 13719 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13720 } 13721 13722 public boolean isForwardLocked() { 13723 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13724 } 13725 } 13726 13727 /** 13728 * Used during creation of InstallArgs 13729 * 13730 * @param installFlags package installation flags 13731 * @return true if should be installed on external storage 13732 */ 13733 private static boolean installOnExternalAsec(int installFlags) { 13734 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13735 return false; 13736 } 13737 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13738 return true; 13739 } 13740 return false; 13741 } 13742 13743 /** 13744 * Used during creation of InstallArgs 13745 * 13746 * @param installFlags package installation flags 13747 * @return true if should be installed as forward locked 13748 */ 13749 private static boolean installForwardLocked(int installFlags) { 13750 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13751 } 13752 13753 private InstallArgs createInstallArgs(InstallParams params) { 13754 if (params.move != null) { 13755 return new MoveInstallArgs(params); 13756 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13757 return new AsecInstallArgs(params); 13758 } else { 13759 return new FileInstallArgs(params); 13760 } 13761 } 13762 13763 /** 13764 * Create args that describe an existing installed package. Typically used 13765 * when cleaning up old installs, or used as a move source. 13766 */ 13767 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13768 String resourcePath, String[] instructionSets) { 13769 final boolean isInAsec; 13770 if (installOnExternalAsec(installFlags)) { 13771 /* Apps on SD card are always in ASEC containers. */ 13772 isInAsec = true; 13773 } else if (installForwardLocked(installFlags) 13774 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13775 /* 13776 * Forward-locked apps are only in ASEC containers if they're the 13777 * new style 13778 */ 13779 isInAsec = true; 13780 } else { 13781 isInAsec = false; 13782 } 13783 13784 if (isInAsec) { 13785 return new AsecInstallArgs(codePath, instructionSets, 13786 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13787 } else { 13788 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13789 } 13790 } 13791 13792 static abstract class InstallArgs { 13793 /** @see InstallParams#origin */ 13794 final OriginInfo origin; 13795 /** @see InstallParams#move */ 13796 final MoveInfo move; 13797 13798 final IPackageInstallObserver2 observer; 13799 // Always refers to PackageManager flags only 13800 final int installFlags; 13801 final String installerPackageName; 13802 final String volumeUuid; 13803 final UserHandle user; 13804 final String abiOverride; 13805 final String[] installGrantPermissions; 13806 /** If non-null, drop an async trace when the install completes */ 13807 final String traceMethod; 13808 final int traceCookie; 13809 final Certificate[][] certificates; 13810 13811 // The list of instruction sets supported by this app. This is currently 13812 // only used during the rmdex() phase to clean up resources. We can get rid of this 13813 // if we move dex files under the common app path. 13814 /* nullable */ String[] instructionSets; 13815 13816 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13817 int installFlags, String installerPackageName, String volumeUuid, 13818 UserHandle user, String[] instructionSets, 13819 String abiOverride, String[] installGrantPermissions, 13820 String traceMethod, int traceCookie, Certificate[][] certificates) { 13821 this.origin = origin; 13822 this.move = move; 13823 this.installFlags = installFlags; 13824 this.observer = observer; 13825 this.installerPackageName = installerPackageName; 13826 this.volumeUuid = volumeUuid; 13827 this.user = user; 13828 this.instructionSets = instructionSets; 13829 this.abiOverride = abiOverride; 13830 this.installGrantPermissions = installGrantPermissions; 13831 this.traceMethod = traceMethod; 13832 this.traceCookie = traceCookie; 13833 this.certificates = certificates; 13834 } 13835 13836 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13837 abstract int doPreInstall(int status); 13838 13839 /** 13840 * Rename package into final resting place. All paths on the given 13841 * scanned package should be updated to reflect the rename. 13842 */ 13843 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13844 abstract int doPostInstall(int status, int uid); 13845 13846 /** @see PackageSettingBase#codePathString */ 13847 abstract String getCodePath(); 13848 /** @see PackageSettingBase#resourcePathString */ 13849 abstract String getResourcePath(); 13850 13851 // Need installer lock especially for dex file removal. 13852 abstract void cleanUpResourcesLI(); 13853 abstract boolean doPostDeleteLI(boolean delete); 13854 13855 /** 13856 * Called before the source arguments are copied. This is used mostly 13857 * for MoveParams when it needs to read the source file to put it in the 13858 * destination. 13859 */ 13860 int doPreCopy() { 13861 return PackageManager.INSTALL_SUCCEEDED; 13862 } 13863 13864 /** 13865 * Called after the source arguments are copied. This is used mostly for 13866 * MoveParams when it needs to read the source file to put it in the 13867 * destination. 13868 */ 13869 int doPostCopy(int uid) { 13870 return PackageManager.INSTALL_SUCCEEDED; 13871 } 13872 13873 protected boolean isFwdLocked() { 13874 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13875 } 13876 13877 protected boolean isExternalAsec() { 13878 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13879 } 13880 13881 protected boolean isEphemeral() { 13882 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13883 } 13884 13885 UserHandle getUser() { 13886 return user; 13887 } 13888 } 13889 13890 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13891 if (!allCodePaths.isEmpty()) { 13892 if (instructionSets == null) { 13893 throw new IllegalStateException("instructionSet == null"); 13894 } 13895 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13896 for (String codePath : allCodePaths) { 13897 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13898 try { 13899 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13900 } catch (InstallerException ignored) { 13901 } 13902 } 13903 } 13904 } 13905 } 13906 13907 /** 13908 * Logic to handle installation of non-ASEC applications, including copying 13909 * and renaming logic. 13910 */ 13911 class FileInstallArgs extends InstallArgs { 13912 private File codeFile; 13913 private File resourceFile; 13914 13915 // Example topology: 13916 // /data/app/com.example/base.apk 13917 // /data/app/com.example/split_foo.apk 13918 // /data/app/com.example/lib/arm/libfoo.so 13919 // /data/app/com.example/lib/arm64/libfoo.so 13920 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13921 13922 /** New install */ 13923 FileInstallArgs(InstallParams params) { 13924 super(params.origin, params.move, params.observer, params.installFlags, 13925 params.installerPackageName, params.volumeUuid, 13926 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13927 params.grantedRuntimePermissions, 13928 params.traceMethod, params.traceCookie, params.certificates); 13929 if (isFwdLocked()) { 13930 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13931 } 13932 } 13933 13934 /** Existing install */ 13935 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13936 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13937 null, null, null, 0, null /*certificates*/); 13938 this.codeFile = (codePath != null) ? new File(codePath) : null; 13939 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13940 } 13941 13942 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13943 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13944 try { 13945 return doCopyApk(imcs, temp); 13946 } finally { 13947 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13948 } 13949 } 13950 13951 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13952 if (origin.staged) { 13953 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13954 codeFile = origin.file; 13955 resourceFile = origin.file; 13956 return PackageManager.INSTALL_SUCCEEDED; 13957 } 13958 13959 try { 13960 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13961 final File tempDir = 13962 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13963 codeFile = tempDir; 13964 resourceFile = tempDir; 13965 } catch (IOException e) { 13966 Slog.w(TAG, "Failed to create copy file: " + e); 13967 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13968 } 13969 13970 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13971 @Override 13972 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13973 if (!FileUtils.isValidExtFilename(name)) { 13974 throw new IllegalArgumentException("Invalid filename: " + name); 13975 } 13976 try { 13977 final File file = new File(codeFile, name); 13978 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13979 O_RDWR | O_CREAT, 0644); 13980 Os.chmod(file.getAbsolutePath(), 0644); 13981 return new ParcelFileDescriptor(fd); 13982 } catch (ErrnoException e) { 13983 throw new RemoteException("Failed to open: " + e.getMessage()); 13984 } 13985 } 13986 }; 13987 13988 int ret = PackageManager.INSTALL_SUCCEEDED; 13989 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13990 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13991 Slog.e(TAG, "Failed to copy package"); 13992 return ret; 13993 } 13994 13995 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13996 NativeLibraryHelper.Handle handle = null; 13997 try { 13998 handle = NativeLibraryHelper.Handle.create(codeFile); 13999 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14000 abiOverride); 14001 } catch (IOException e) { 14002 Slog.e(TAG, "Copying native libraries failed", e); 14003 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14004 } finally { 14005 IoUtils.closeQuietly(handle); 14006 } 14007 14008 return ret; 14009 } 14010 14011 int doPreInstall(int status) { 14012 if (status != PackageManager.INSTALL_SUCCEEDED) { 14013 cleanUp(); 14014 } 14015 return status; 14016 } 14017 14018 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14019 if (status != PackageManager.INSTALL_SUCCEEDED) { 14020 cleanUp(); 14021 return false; 14022 } 14023 14024 final File targetDir = codeFile.getParentFile(); 14025 final File beforeCodeFile = codeFile; 14026 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14027 14028 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14029 try { 14030 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14031 } catch (ErrnoException e) { 14032 Slog.w(TAG, "Failed to rename", e); 14033 return false; 14034 } 14035 14036 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14037 Slog.w(TAG, "Failed to restorecon"); 14038 return false; 14039 } 14040 14041 // Reflect the rename internally 14042 codeFile = afterCodeFile; 14043 resourceFile = afterCodeFile; 14044 14045 // Reflect the rename in scanned details 14046 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14047 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14048 afterCodeFile, pkg.baseCodePath)); 14049 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14050 afterCodeFile, pkg.splitCodePaths)); 14051 14052 // Reflect the rename in app info 14053 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14054 pkg.setApplicationInfoCodePath(pkg.codePath); 14055 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14056 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14057 pkg.setApplicationInfoResourcePath(pkg.codePath); 14058 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14059 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14060 14061 return true; 14062 } 14063 14064 int doPostInstall(int status, int uid) { 14065 if (status != PackageManager.INSTALL_SUCCEEDED) { 14066 cleanUp(); 14067 } 14068 return status; 14069 } 14070 14071 @Override 14072 String getCodePath() { 14073 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14074 } 14075 14076 @Override 14077 String getResourcePath() { 14078 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14079 } 14080 14081 private boolean cleanUp() { 14082 if (codeFile == null || !codeFile.exists()) { 14083 return false; 14084 } 14085 14086 removeCodePathLI(codeFile); 14087 14088 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14089 resourceFile.delete(); 14090 } 14091 14092 return true; 14093 } 14094 14095 void cleanUpResourcesLI() { 14096 // Try enumerating all code paths before deleting 14097 List<String> allCodePaths = Collections.EMPTY_LIST; 14098 if (codeFile != null && codeFile.exists()) { 14099 try { 14100 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14101 allCodePaths = pkg.getAllCodePaths(); 14102 } catch (PackageParserException e) { 14103 // Ignored; we tried our best 14104 } 14105 } 14106 14107 cleanUp(); 14108 removeDexFiles(allCodePaths, instructionSets); 14109 } 14110 14111 boolean doPostDeleteLI(boolean delete) { 14112 // XXX err, shouldn't we respect the delete flag? 14113 cleanUpResourcesLI(); 14114 return true; 14115 } 14116 } 14117 14118 private boolean isAsecExternal(String cid) { 14119 final String asecPath = PackageHelper.getSdFilesystem(cid); 14120 return !asecPath.startsWith(mAsecInternalPath); 14121 } 14122 14123 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 14124 PackageManagerException { 14125 if (copyRet < 0) { 14126 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 14127 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 14128 throw new PackageManagerException(copyRet, message); 14129 } 14130 } 14131 } 14132 14133 /** 14134 * Extract the StorageManagerService "container ID" from the full code path of an 14135 * .apk. 14136 */ 14137 static String cidFromCodePath(String fullCodePath) { 14138 int eidx = fullCodePath.lastIndexOf("/"); 14139 String subStr1 = fullCodePath.substring(0, eidx); 14140 int sidx = subStr1.lastIndexOf("/"); 14141 return subStr1.substring(sidx+1, eidx); 14142 } 14143 14144 /** 14145 * Logic to handle installation of ASEC applications, including copying and 14146 * renaming logic. 14147 */ 14148 class AsecInstallArgs extends InstallArgs { 14149 static final String RES_FILE_NAME = "pkg.apk"; 14150 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14151 14152 String cid; 14153 String packagePath; 14154 String resourcePath; 14155 14156 /** New install */ 14157 AsecInstallArgs(InstallParams params) { 14158 super(params.origin, params.move, params.observer, params.installFlags, 14159 params.installerPackageName, params.volumeUuid, 14160 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14161 params.grantedRuntimePermissions, 14162 params.traceMethod, params.traceCookie, params.certificates); 14163 } 14164 14165 /** Existing install */ 14166 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14167 boolean isExternal, boolean isForwardLocked) { 14168 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14169 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14170 instructionSets, null, null, null, 0, null /*certificates*/); 14171 // Hackily pretend we're still looking at a full code path 14172 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14173 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14174 } 14175 14176 // Extract cid from fullCodePath 14177 int eidx = fullCodePath.lastIndexOf("/"); 14178 String subStr1 = fullCodePath.substring(0, eidx); 14179 int sidx = subStr1.lastIndexOf("/"); 14180 cid = subStr1.substring(sidx+1, eidx); 14181 setMountPath(subStr1); 14182 } 14183 14184 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14185 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14186 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14187 instructionSets, null, null, null, 0, null /*certificates*/); 14188 this.cid = cid; 14189 setMountPath(PackageHelper.getSdDir(cid)); 14190 } 14191 14192 void createCopyFile() { 14193 cid = mInstallerService.allocateExternalStageCidLegacy(); 14194 } 14195 14196 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14197 if (origin.staged && origin.cid != null) { 14198 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14199 cid = origin.cid; 14200 setMountPath(PackageHelper.getSdDir(cid)); 14201 return PackageManager.INSTALL_SUCCEEDED; 14202 } 14203 14204 if (temp) { 14205 createCopyFile(); 14206 } else { 14207 /* 14208 * Pre-emptively destroy the container since it's destroyed if 14209 * copying fails due to it existing anyway. 14210 */ 14211 PackageHelper.destroySdDir(cid); 14212 } 14213 14214 final String newMountPath = imcs.copyPackageToContainer( 14215 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14216 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14217 14218 if (newMountPath != null) { 14219 setMountPath(newMountPath); 14220 return PackageManager.INSTALL_SUCCEEDED; 14221 } else { 14222 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14223 } 14224 } 14225 14226 @Override 14227 String getCodePath() { 14228 return packagePath; 14229 } 14230 14231 @Override 14232 String getResourcePath() { 14233 return resourcePath; 14234 } 14235 14236 int doPreInstall(int status) { 14237 if (status != PackageManager.INSTALL_SUCCEEDED) { 14238 // Destroy container 14239 PackageHelper.destroySdDir(cid); 14240 } else { 14241 boolean mounted = PackageHelper.isContainerMounted(cid); 14242 if (!mounted) { 14243 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14244 Process.SYSTEM_UID); 14245 if (newMountPath != null) { 14246 setMountPath(newMountPath); 14247 } else { 14248 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14249 } 14250 } 14251 } 14252 return status; 14253 } 14254 14255 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14256 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14257 String newMountPath = null; 14258 if (PackageHelper.isContainerMounted(cid)) { 14259 // Unmount the container 14260 if (!PackageHelper.unMountSdDir(cid)) { 14261 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14262 return false; 14263 } 14264 } 14265 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14266 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14267 " which might be stale. Will try to clean up."); 14268 // Clean up the stale container and proceed to recreate. 14269 if (!PackageHelper.destroySdDir(newCacheId)) { 14270 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14271 return false; 14272 } 14273 // Successfully cleaned up stale container. Try to rename again. 14274 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14275 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14276 + " inspite of cleaning it up."); 14277 return false; 14278 } 14279 } 14280 if (!PackageHelper.isContainerMounted(newCacheId)) { 14281 Slog.w(TAG, "Mounting container " + newCacheId); 14282 newMountPath = PackageHelper.mountSdDir(newCacheId, 14283 getEncryptKey(), Process.SYSTEM_UID); 14284 } else { 14285 newMountPath = PackageHelper.getSdDir(newCacheId); 14286 } 14287 if (newMountPath == null) { 14288 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14289 return false; 14290 } 14291 Log.i(TAG, "Succesfully renamed " + cid + 14292 " to " + newCacheId + 14293 " at new path: " + newMountPath); 14294 cid = newCacheId; 14295 14296 final File beforeCodeFile = new File(packagePath); 14297 setMountPath(newMountPath); 14298 final File afterCodeFile = new File(packagePath); 14299 14300 // Reflect the rename in scanned details 14301 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14302 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14303 afterCodeFile, pkg.baseCodePath)); 14304 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14305 afterCodeFile, pkg.splitCodePaths)); 14306 14307 // Reflect the rename in app info 14308 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14309 pkg.setApplicationInfoCodePath(pkg.codePath); 14310 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14311 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14312 pkg.setApplicationInfoResourcePath(pkg.codePath); 14313 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14314 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14315 14316 return true; 14317 } 14318 14319 private void setMountPath(String mountPath) { 14320 final File mountFile = new File(mountPath); 14321 14322 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14323 if (monolithicFile.exists()) { 14324 packagePath = monolithicFile.getAbsolutePath(); 14325 if (isFwdLocked()) { 14326 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14327 } else { 14328 resourcePath = packagePath; 14329 } 14330 } else { 14331 packagePath = mountFile.getAbsolutePath(); 14332 resourcePath = packagePath; 14333 } 14334 } 14335 14336 int doPostInstall(int status, int uid) { 14337 if (status != PackageManager.INSTALL_SUCCEEDED) { 14338 cleanUp(); 14339 } else { 14340 final int groupOwner; 14341 final String protectedFile; 14342 if (isFwdLocked()) { 14343 groupOwner = UserHandle.getSharedAppGid(uid); 14344 protectedFile = RES_FILE_NAME; 14345 } else { 14346 groupOwner = -1; 14347 protectedFile = null; 14348 } 14349 14350 if (uid < Process.FIRST_APPLICATION_UID 14351 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14352 Slog.e(TAG, "Failed to finalize " + cid); 14353 PackageHelper.destroySdDir(cid); 14354 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14355 } 14356 14357 boolean mounted = PackageHelper.isContainerMounted(cid); 14358 if (!mounted) { 14359 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14360 } 14361 } 14362 return status; 14363 } 14364 14365 private void cleanUp() { 14366 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14367 14368 // Destroy secure container 14369 PackageHelper.destroySdDir(cid); 14370 } 14371 14372 private List<String> getAllCodePaths() { 14373 final File codeFile = new File(getCodePath()); 14374 if (codeFile != null && codeFile.exists()) { 14375 try { 14376 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14377 return pkg.getAllCodePaths(); 14378 } catch (PackageParserException e) { 14379 // Ignored; we tried our best 14380 } 14381 } 14382 return Collections.EMPTY_LIST; 14383 } 14384 14385 void cleanUpResourcesLI() { 14386 // Enumerate all code paths before deleting 14387 cleanUpResourcesLI(getAllCodePaths()); 14388 } 14389 14390 private void cleanUpResourcesLI(List<String> allCodePaths) { 14391 cleanUp(); 14392 removeDexFiles(allCodePaths, instructionSets); 14393 } 14394 14395 String getPackageName() { 14396 return getAsecPackageName(cid); 14397 } 14398 14399 boolean doPostDeleteLI(boolean delete) { 14400 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14401 final List<String> allCodePaths = getAllCodePaths(); 14402 boolean mounted = PackageHelper.isContainerMounted(cid); 14403 if (mounted) { 14404 // Unmount first 14405 if (PackageHelper.unMountSdDir(cid)) { 14406 mounted = false; 14407 } 14408 } 14409 if (!mounted && delete) { 14410 cleanUpResourcesLI(allCodePaths); 14411 } 14412 return !mounted; 14413 } 14414 14415 @Override 14416 int doPreCopy() { 14417 if (isFwdLocked()) { 14418 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14419 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14420 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14421 } 14422 } 14423 14424 return PackageManager.INSTALL_SUCCEEDED; 14425 } 14426 14427 @Override 14428 int doPostCopy(int uid) { 14429 if (isFwdLocked()) { 14430 if (uid < Process.FIRST_APPLICATION_UID 14431 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14432 RES_FILE_NAME)) { 14433 Slog.e(TAG, "Failed to finalize " + cid); 14434 PackageHelper.destroySdDir(cid); 14435 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14436 } 14437 } 14438 14439 return PackageManager.INSTALL_SUCCEEDED; 14440 } 14441 } 14442 14443 /** 14444 * Logic to handle movement of existing installed applications. 14445 */ 14446 class MoveInstallArgs extends InstallArgs { 14447 private File codeFile; 14448 private File resourceFile; 14449 14450 /** New install */ 14451 MoveInstallArgs(InstallParams params) { 14452 super(params.origin, params.move, params.observer, params.installFlags, 14453 params.installerPackageName, params.volumeUuid, 14454 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14455 params.grantedRuntimePermissions, 14456 params.traceMethod, params.traceCookie, params.certificates); 14457 } 14458 14459 int copyApk(IMediaContainerService imcs, boolean temp) { 14460 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14461 + move.fromUuid + " to " + move.toUuid); 14462 synchronized (mInstaller) { 14463 try { 14464 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14465 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14466 } catch (InstallerException e) { 14467 Slog.w(TAG, "Failed to move app", e); 14468 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14469 } 14470 } 14471 14472 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14473 resourceFile = codeFile; 14474 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14475 14476 return PackageManager.INSTALL_SUCCEEDED; 14477 } 14478 14479 int doPreInstall(int status) { 14480 if (status != PackageManager.INSTALL_SUCCEEDED) { 14481 cleanUp(move.toUuid); 14482 } 14483 return status; 14484 } 14485 14486 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14487 if (status != PackageManager.INSTALL_SUCCEEDED) { 14488 cleanUp(move.toUuid); 14489 return false; 14490 } 14491 14492 // Reflect the move in app info 14493 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14494 pkg.setApplicationInfoCodePath(pkg.codePath); 14495 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14496 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14497 pkg.setApplicationInfoResourcePath(pkg.codePath); 14498 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14499 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14500 14501 return true; 14502 } 14503 14504 int doPostInstall(int status, int uid) { 14505 if (status == PackageManager.INSTALL_SUCCEEDED) { 14506 cleanUp(move.fromUuid); 14507 } else { 14508 cleanUp(move.toUuid); 14509 } 14510 return status; 14511 } 14512 14513 @Override 14514 String getCodePath() { 14515 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14516 } 14517 14518 @Override 14519 String getResourcePath() { 14520 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14521 } 14522 14523 private boolean cleanUp(String volumeUuid) { 14524 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14525 move.dataAppName); 14526 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14527 final int[] userIds = sUserManager.getUserIds(); 14528 synchronized (mInstallLock) { 14529 // Clean up both app data and code 14530 // All package moves are frozen until finished 14531 for (int userId : userIds) { 14532 try { 14533 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14534 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14535 } catch (InstallerException e) { 14536 Slog.w(TAG, String.valueOf(e)); 14537 } 14538 } 14539 removeCodePathLI(codeFile); 14540 } 14541 return true; 14542 } 14543 14544 void cleanUpResourcesLI() { 14545 throw new UnsupportedOperationException(); 14546 } 14547 14548 boolean doPostDeleteLI(boolean delete) { 14549 throw new UnsupportedOperationException(); 14550 } 14551 } 14552 14553 static String getAsecPackageName(String packageCid) { 14554 int idx = packageCid.lastIndexOf("-"); 14555 if (idx == -1) { 14556 return packageCid; 14557 } 14558 return packageCid.substring(0, idx); 14559 } 14560 14561 // Utility method used to create code paths based on package name and available index. 14562 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14563 String idxStr = ""; 14564 int idx = 1; 14565 // Fall back to default value of idx=1 if prefix is not 14566 // part of oldCodePath 14567 if (oldCodePath != null) { 14568 String subStr = oldCodePath; 14569 // Drop the suffix right away 14570 if (suffix != null && subStr.endsWith(suffix)) { 14571 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14572 } 14573 // If oldCodePath already contains prefix find out the 14574 // ending index to either increment or decrement. 14575 int sidx = subStr.lastIndexOf(prefix); 14576 if (sidx != -1) { 14577 subStr = subStr.substring(sidx + prefix.length()); 14578 if (subStr != null) { 14579 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14580 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14581 } 14582 try { 14583 idx = Integer.parseInt(subStr); 14584 if (idx <= 1) { 14585 idx++; 14586 } else { 14587 idx--; 14588 } 14589 } catch(NumberFormatException e) { 14590 } 14591 } 14592 } 14593 } 14594 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14595 return prefix + idxStr; 14596 } 14597 14598 private File getNextCodePath(File targetDir, String packageName) { 14599 File result; 14600 SecureRandom random = new SecureRandom(); 14601 byte[] bytes = new byte[16]; 14602 do { 14603 random.nextBytes(bytes); 14604 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14605 result = new File(targetDir, packageName + "-" + suffix); 14606 } while (result.exists()); 14607 return result; 14608 } 14609 14610 // Utility method that returns the relative package path with respect 14611 // to the installation directory. Like say for /data/data/com.test-1.apk 14612 // string com.test-1 is returned. 14613 static String deriveCodePathName(String codePath) { 14614 if (codePath == null) { 14615 return null; 14616 } 14617 final File codeFile = new File(codePath); 14618 final String name = codeFile.getName(); 14619 if (codeFile.isDirectory()) { 14620 return name; 14621 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14622 final int lastDot = name.lastIndexOf('.'); 14623 return name.substring(0, lastDot); 14624 } else { 14625 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14626 return null; 14627 } 14628 } 14629 14630 static class PackageInstalledInfo { 14631 String name; 14632 int uid; 14633 // The set of users that originally had this package installed. 14634 int[] origUsers; 14635 // The set of users that now have this package installed. 14636 int[] newUsers; 14637 PackageParser.Package pkg; 14638 int returnCode; 14639 String returnMsg; 14640 PackageRemovedInfo removedInfo; 14641 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14642 14643 public void setError(int code, String msg) { 14644 setReturnCode(code); 14645 setReturnMessage(msg); 14646 Slog.w(TAG, msg); 14647 } 14648 14649 public void setError(String msg, PackageParserException e) { 14650 setReturnCode(e.error); 14651 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14652 Slog.w(TAG, msg, e); 14653 } 14654 14655 public void setError(String msg, PackageManagerException e) { 14656 returnCode = e.error; 14657 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14658 Slog.w(TAG, msg, e); 14659 } 14660 14661 public void setReturnCode(int returnCode) { 14662 this.returnCode = returnCode; 14663 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14664 for (int i = 0; i < childCount; i++) { 14665 addedChildPackages.valueAt(i).returnCode = returnCode; 14666 } 14667 } 14668 14669 private void setReturnMessage(String returnMsg) { 14670 this.returnMsg = returnMsg; 14671 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14672 for (int i = 0; i < childCount; i++) { 14673 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14674 } 14675 } 14676 14677 // In some error cases we want to convey more info back to the observer 14678 String origPackage; 14679 String origPermission; 14680 } 14681 14682 /* 14683 * Install a non-existing package. 14684 */ 14685 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14686 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14687 PackageInstalledInfo res) { 14688 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14689 14690 // Remember this for later, in case we need to rollback this install 14691 String pkgName = pkg.packageName; 14692 14693 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14694 14695 synchronized(mPackages) { 14696 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14697 if (renamedPackage != null) { 14698 // A package with the same name is already installed, though 14699 // it has been renamed to an older name. The package we 14700 // are trying to install should be installed as an update to 14701 // the existing one, but that has not been requested, so bail. 14702 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14703 + " without first uninstalling package running as " 14704 + renamedPackage); 14705 return; 14706 } 14707 if (mPackages.containsKey(pkgName)) { 14708 // Don't allow installation over an existing package with the same name. 14709 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14710 + " without first uninstalling."); 14711 return; 14712 } 14713 } 14714 14715 try { 14716 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14717 System.currentTimeMillis(), user); 14718 14719 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14720 14721 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14722 prepareAppDataAfterInstallLIF(newPackage); 14723 14724 } else { 14725 // Remove package from internal structures, but keep around any 14726 // data that might have already existed 14727 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14728 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14729 } 14730 } catch (PackageManagerException e) { 14731 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14732 } 14733 14734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14735 } 14736 14737 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14738 // Can't rotate keys during boot or if sharedUser. 14739 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14740 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14741 return false; 14742 } 14743 // app is using upgradeKeySets; make sure all are valid 14744 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14745 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14746 for (int i = 0; i < upgradeKeySets.length; i++) { 14747 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14748 Slog.wtf(TAG, "Package " 14749 + (oldPs.name != null ? oldPs.name : "<null>") 14750 + " contains upgrade-key-set reference to unknown key-set: " 14751 + upgradeKeySets[i] 14752 + " reverting to signatures check."); 14753 return false; 14754 } 14755 } 14756 return true; 14757 } 14758 14759 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14760 // Upgrade keysets are being used. Determine if new package has a superset of the 14761 // required keys. 14762 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14763 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14764 for (int i = 0; i < upgradeKeySets.length; i++) { 14765 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14766 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14767 return true; 14768 } 14769 } 14770 return false; 14771 } 14772 14773 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14774 try (DigestInputStream digestStream = 14775 new DigestInputStream(new FileInputStream(file), digest)) { 14776 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14777 } 14778 } 14779 14780 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14781 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14782 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14783 14784 final PackageParser.Package oldPackage; 14785 final String pkgName = pkg.packageName; 14786 final int[] allUsers; 14787 final int[] installedUsers; 14788 14789 synchronized(mPackages) { 14790 oldPackage = mPackages.get(pkgName); 14791 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14792 14793 // don't allow upgrade to target a release SDK from a pre-release SDK 14794 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14795 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14796 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14797 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14798 if (oldTargetsPreRelease 14799 && !newTargetsPreRelease 14800 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14801 Slog.w(TAG, "Can't install package targeting released sdk"); 14802 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14803 return; 14804 } 14805 14806 // don't allow an upgrade from full to ephemeral 14807 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14808 if (isEphemeral && !oldIsEphemeral) { 14809 // can't downgrade from full to ephemeral 14810 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14811 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14812 return; 14813 } 14814 14815 // verify signatures are valid 14816 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14817 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14818 if (!checkUpgradeKeySetLP(ps, pkg)) { 14819 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14820 "New package not signed by keys specified by upgrade-keysets: " 14821 + pkgName); 14822 return; 14823 } 14824 } else { 14825 // default to original signature matching 14826 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14827 != PackageManager.SIGNATURE_MATCH) { 14828 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14829 "New package has a different signature: " + pkgName); 14830 return; 14831 } 14832 } 14833 14834 // don't allow a system upgrade unless the upgrade hash matches 14835 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14836 byte[] digestBytes = null; 14837 try { 14838 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14839 updateDigest(digest, new File(pkg.baseCodePath)); 14840 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14841 for (String path : pkg.splitCodePaths) { 14842 updateDigest(digest, new File(path)); 14843 } 14844 } 14845 digestBytes = digest.digest(); 14846 } catch (NoSuchAlgorithmException | IOException e) { 14847 res.setError(INSTALL_FAILED_INVALID_APK, 14848 "Could not compute hash: " + pkgName); 14849 return; 14850 } 14851 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14852 res.setError(INSTALL_FAILED_INVALID_APK, 14853 "New package fails restrict-update check: " + pkgName); 14854 return; 14855 } 14856 // retain upgrade restriction 14857 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14858 } 14859 14860 // Check for shared user id changes 14861 String invalidPackageName = 14862 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14863 if (invalidPackageName != null) { 14864 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14865 "Package " + invalidPackageName + " tried to change user " 14866 + oldPackage.mSharedUserId); 14867 return; 14868 } 14869 14870 // In case of rollback, remember per-user/profile install state 14871 allUsers = sUserManager.getUserIds(); 14872 installedUsers = ps.queryInstalledUsers(allUsers, true); 14873 } 14874 14875 // Update what is removed 14876 res.removedInfo = new PackageRemovedInfo(); 14877 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14878 res.removedInfo.removedPackage = oldPackage.packageName; 14879 res.removedInfo.isUpdate = true; 14880 res.removedInfo.origUsers = installedUsers; 14881 final int childCount = (oldPackage.childPackages != null) 14882 ? oldPackage.childPackages.size() : 0; 14883 for (int i = 0; i < childCount; i++) { 14884 boolean childPackageUpdated = false; 14885 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14886 if (res.addedChildPackages != null) { 14887 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14888 if (childRes != null) { 14889 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14890 childRes.removedInfo.removedPackage = childPkg.packageName; 14891 childRes.removedInfo.isUpdate = true; 14892 childPackageUpdated = true; 14893 } 14894 } 14895 if (!childPackageUpdated) { 14896 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14897 childRemovedRes.removedPackage = childPkg.packageName; 14898 childRemovedRes.isUpdate = false; 14899 childRemovedRes.dataRemoved = true; 14900 synchronized (mPackages) { 14901 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14902 if (childPs != null) { 14903 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14904 } 14905 } 14906 if (res.removedInfo.removedChildPackages == null) { 14907 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14908 } 14909 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14910 } 14911 } 14912 14913 boolean sysPkg = (isSystemApp(oldPackage)); 14914 if (sysPkg) { 14915 // Set the system/privileged flags as needed 14916 final boolean privileged = 14917 (oldPackage.applicationInfo.privateFlags 14918 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14919 final int systemPolicyFlags = policyFlags 14920 | PackageParser.PARSE_IS_SYSTEM 14921 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14922 14923 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14924 user, allUsers, installerPackageName, res); 14925 } else { 14926 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14927 user, allUsers, installerPackageName, res); 14928 } 14929 } 14930 14931 public List<String> getPreviousCodePaths(String packageName) { 14932 final PackageSetting ps = mSettings.mPackages.get(packageName); 14933 final List<String> result = new ArrayList<String>(); 14934 if (ps != null && ps.oldCodePaths != null) { 14935 result.addAll(ps.oldCodePaths); 14936 } 14937 return result; 14938 } 14939 14940 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14941 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14942 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14943 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14944 + deletedPackage); 14945 14946 String pkgName = deletedPackage.packageName; 14947 boolean deletedPkg = true; 14948 boolean addedPkg = false; 14949 boolean updatedSettings = false; 14950 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14951 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14952 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14953 14954 final long origUpdateTime = (pkg.mExtras != null) 14955 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14956 14957 // First delete the existing package while retaining the data directory 14958 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14959 res.removedInfo, true, pkg)) { 14960 // If the existing package wasn't successfully deleted 14961 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14962 deletedPkg = false; 14963 } else { 14964 // Successfully deleted the old package; proceed with replace. 14965 14966 // If deleted package lived in a container, give users a chance to 14967 // relinquish resources before killing. 14968 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14969 if (DEBUG_INSTALL) { 14970 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14971 } 14972 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14973 final ArrayList<String> pkgList = new ArrayList<String>(1); 14974 pkgList.add(deletedPackage.applicationInfo.packageName); 14975 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14976 } 14977 14978 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14979 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14980 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14981 14982 try { 14983 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14984 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14985 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14986 14987 // Update the in-memory copy of the previous code paths. 14988 PackageSetting ps = mSettings.mPackages.get(pkgName); 14989 if (!killApp) { 14990 if (ps.oldCodePaths == null) { 14991 ps.oldCodePaths = new ArraySet<>(); 14992 } 14993 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14994 if (deletedPackage.splitCodePaths != null) { 14995 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14996 } 14997 } else { 14998 ps.oldCodePaths = null; 14999 } 15000 if (ps.childPackageNames != null) { 15001 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15002 final String childPkgName = ps.childPackageNames.get(i); 15003 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15004 childPs.oldCodePaths = ps.oldCodePaths; 15005 } 15006 } 15007 prepareAppDataAfterInstallLIF(newPackage); 15008 addedPkg = true; 15009 } catch (PackageManagerException e) { 15010 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15011 } 15012 } 15013 15014 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15015 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15016 15017 // Revert all internal state mutations and added folders for the failed install 15018 if (addedPkg) { 15019 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15020 res.removedInfo, true, null); 15021 } 15022 15023 // Restore the old package 15024 if (deletedPkg) { 15025 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15026 File restoreFile = new File(deletedPackage.codePath); 15027 // Parse old package 15028 boolean oldExternal = isExternal(deletedPackage); 15029 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15030 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15031 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15032 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15033 try { 15034 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15035 null); 15036 } catch (PackageManagerException e) { 15037 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15038 + e.getMessage()); 15039 return; 15040 } 15041 15042 synchronized (mPackages) { 15043 // Ensure the installer package name up to date 15044 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15045 15046 // Update permissions for restored package 15047 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15048 15049 mSettings.writeLPr(); 15050 } 15051 15052 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15053 } 15054 } else { 15055 synchronized (mPackages) { 15056 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15057 if (ps != null) { 15058 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15059 if (res.removedInfo.removedChildPackages != null) { 15060 final int childCount = res.removedInfo.removedChildPackages.size(); 15061 // Iterate in reverse as we may modify the collection 15062 for (int i = childCount - 1; i >= 0; i--) { 15063 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15064 if (res.addedChildPackages.containsKey(childPackageName)) { 15065 res.removedInfo.removedChildPackages.removeAt(i); 15066 } else { 15067 PackageRemovedInfo childInfo = res.removedInfo 15068 .removedChildPackages.valueAt(i); 15069 childInfo.removedForAllUsers = mPackages.get( 15070 childInfo.removedPackage) == null; 15071 } 15072 } 15073 } 15074 } 15075 } 15076 } 15077 } 15078 15079 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15080 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15081 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 15082 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15083 + ", old=" + deletedPackage); 15084 15085 final boolean disabledSystem; 15086 15087 // Remove existing system package 15088 removePackageLI(deletedPackage, true); 15089 15090 synchronized (mPackages) { 15091 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15092 } 15093 if (!disabledSystem) { 15094 // We didn't need to disable the .apk as a current system package, 15095 // which means we are replacing another update that is already 15096 // installed. We need to make sure to delete the older one's .apk. 15097 res.removedInfo.args = createInstallArgsForExisting(0, 15098 deletedPackage.applicationInfo.getCodePath(), 15099 deletedPackage.applicationInfo.getResourcePath(), 15100 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15101 } else { 15102 res.removedInfo.args = null; 15103 } 15104 15105 // Successfully disabled the old package. Now proceed with re-installation 15106 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15107 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15108 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15109 15110 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15111 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15112 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15113 15114 PackageParser.Package newPackage = null; 15115 try { 15116 // Add the package to the internal data structures 15117 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 15118 15119 // Set the update and install times 15120 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15121 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15122 System.currentTimeMillis()); 15123 15124 // Update the package dynamic state if succeeded 15125 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15126 // Now that the install succeeded make sure we remove data 15127 // directories for any child package the update removed. 15128 final int deletedChildCount = (deletedPackage.childPackages != null) 15129 ? deletedPackage.childPackages.size() : 0; 15130 final int newChildCount = (newPackage.childPackages != null) 15131 ? newPackage.childPackages.size() : 0; 15132 for (int i = 0; i < deletedChildCount; i++) { 15133 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15134 boolean childPackageDeleted = true; 15135 for (int j = 0; j < newChildCount; j++) { 15136 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15137 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15138 childPackageDeleted = false; 15139 break; 15140 } 15141 } 15142 if (childPackageDeleted) { 15143 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15144 deletedChildPkg.packageName); 15145 if (ps != null && res.removedInfo.removedChildPackages != null) { 15146 PackageRemovedInfo removedChildRes = res.removedInfo 15147 .removedChildPackages.get(deletedChildPkg.packageName); 15148 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15149 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15150 } 15151 } 15152 } 15153 15154 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15155 prepareAppDataAfterInstallLIF(newPackage); 15156 } 15157 } catch (PackageManagerException e) { 15158 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15159 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15160 } 15161 15162 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15163 // Re installation failed. Restore old information 15164 // Remove new pkg information 15165 if (newPackage != null) { 15166 removeInstalledPackageLI(newPackage, true); 15167 } 15168 // Add back the old system package 15169 try { 15170 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15171 } catch (PackageManagerException e) { 15172 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15173 } 15174 15175 synchronized (mPackages) { 15176 if (disabledSystem) { 15177 enableSystemPackageLPw(deletedPackage); 15178 } 15179 15180 // Ensure the installer package name up to date 15181 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15182 15183 // Update permissions for restored package 15184 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15185 15186 mSettings.writeLPr(); 15187 } 15188 15189 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15190 + " after failed upgrade"); 15191 } 15192 } 15193 15194 /** 15195 * Checks whether the parent or any of the child packages have a change shared 15196 * user. For a package to be a valid update the shred users of the parent and 15197 * the children should match. We may later support changing child shared users. 15198 * @param oldPkg The updated package. 15199 * @param newPkg The update package. 15200 * @return The shared user that change between the versions. 15201 */ 15202 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15203 PackageParser.Package newPkg) { 15204 // Check parent shared user 15205 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15206 return newPkg.packageName; 15207 } 15208 // Check child shared users 15209 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15210 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15211 for (int i = 0; i < newChildCount; i++) { 15212 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15213 // If this child was present, did it have the same shared user? 15214 for (int j = 0; j < oldChildCount; j++) { 15215 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15216 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15217 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15218 return newChildPkg.packageName; 15219 } 15220 } 15221 } 15222 return null; 15223 } 15224 15225 private void removeNativeBinariesLI(PackageSetting ps) { 15226 // Remove the lib path for the parent package 15227 if (ps != null) { 15228 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15229 // Remove the lib path for the child packages 15230 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15231 for (int i = 0; i < childCount; i++) { 15232 PackageSetting childPs = null; 15233 synchronized (mPackages) { 15234 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15235 } 15236 if (childPs != null) { 15237 NativeLibraryHelper.removeNativeBinariesLI(childPs 15238 .legacyNativeLibraryPathString); 15239 } 15240 } 15241 } 15242 } 15243 15244 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15245 // Enable the parent package 15246 mSettings.enableSystemPackageLPw(pkg.packageName); 15247 // Enable the child packages 15248 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15249 for (int i = 0; i < childCount; i++) { 15250 PackageParser.Package childPkg = pkg.childPackages.get(i); 15251 mSettings.enableSystemPackageLPw(childPkg.packageName); 15252 } 15253 } 15254 15255 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15256 PackageParser.Package newPkg) { 15257 // Disable the parent package (parent always replaced) 15258 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15259 // Disable the child packages 15260 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15261 for (int i = 0; i < childCount; i++) { 15262 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15263 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15264 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15265 } 15266 return disabled; 15267 } 15268 15269 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15270 String installerPackageName) { 15271 // Enable the parent package 15272 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15273 // Enable the child packages 15274 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15275 for (int i = 0; i < childCount; i++) { 15276 PackageParser.Package childPkg = pkg.childPackages.get(i); 15277 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15278 } 15279 } 15280 15281 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15282 // Collect all used permissions in the UID 15283 ArraySet<String> usedPermissions = new ArraySet<>(); 15284 final int packageCount = su.packages.size(); 15285 for (int i = 0; i < packageCount; i++) { 15286 PackageSetting ps = su.packages.valueAt(i); 15287 if (ps.pkg == null) { 15288 continue; 15289 } 15290 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15291 for (int j = 0; j < requestedPermCount; j++) { 15292 String permission = ps.pkg.requestedPermissions.get(j); 15293 BasePermission bp = mSettings.mPermissions.get(permission); 15294 if (bp != null) { 15295 usedPermissions.add(permission); 15296 } 15297 } 15298 } 15299 15300 PermissionsState permissionsState = su.getPermissionsState(); 15301 // Prune install permissions 15302 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15303 final int installPermCount = installPermStates.size(); 15304 for (int i = installPermCount - 1; i >= 0; i--) { 15305 PermissionState permissionState = installPermStates.get(i); 15306 if (!usedPermissions.contains(permissionState.getName())) { 15307 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15308 if (bp != null) { 15309 permissionsState.revokeInstallPermission(bp); 15310 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15311 PackageManager.MASK_PERMISSION_FLAGS, 0); 15312 } 15313 } 15314 } 15315 15316 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15317 15318 // Prune runtime permissions 15319 for (int userId : allUserIds) { 15320 List<PermissionState> runtimePermStates = permissionsState 15321 .getRuntimePermissionStates(userId); 15322 final int runtimePermCount = runtimePermStates.size(); 15323 for (int i = runtimePermCount - 1; i >= 0; i--) { 15324 PermissionState permissionState = runtimePermStates.get(i); 15325 if (!usedPermissions.contains(permissionState.getName())) { 15326 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15327 if (bp != null) { 15328 permissionsState.revokeRuntimePermission(bp, userId); 15329 permissionsState.updatePermissionFlags(bp, userId, 15330 PackageManager.MASK_PERMISSION_FLAGS, 0); 15331 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15332 runtimePermissionChangedUserIds, userId); 15333 } 15334 } 15335 } 15336 } 15337 15338 return runtimePermissionChangedUserIds; 15339 } 15340 15341 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15342 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15343 // Update the parent package setting 15344 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15345 res, user); 15346 // Update the child packages setting 15347 final int childCount = (newPackage.childPackages != null) 15348 ? newPackage.childPackages.size() : 0; 15349 for (int i = 0; i < childCount; i++) { 15350 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15351 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15352 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15353 childRes.origUsers, childRes, user); 15354 } 15355 } 15356 15357 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15358 String installerPackageName, int[] allUsers, int[] installedForUsers, 15359 PackageInstalledInfo res, UserHandle user) { 15360 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15361 15362 String pkgName = newPackage.packageName; 15363 synchronized (mPackages) { 15364 //write settings. the installStatus will be incomplete at this stage. 15365 //note that the new package setting would have already been 15366 //added to mPackages. It hasn't been persisted yet. 15367 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15368 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15369 mSettings.writeLPr(); 15370 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15371 } 15372 15373 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15374 synchronized (mPackages) { 15375 updatePermissionsLPw(newPackage.packageName, newPackage, 15376 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15377 ? UPDATE_PERMISSIONS_ALL : 0)); 15378 // For system-bundled packages, we assume that installing an upgraded version 15379 // of the package implies that the user actually wants to run that new code, 15380 // so we enable the package. 15381 PackageSetting ps = mSettings.mPackages.get(pkgName); 15382 final int userId = user.getIdentifier(); 15383 if (ps != null) { 15384 if (isSystemApp(newPackage)) { 15385 if (DEBUG_INSTALL) { 15386 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15387 } 15388 // Enable system package for requested users 15389 if (res.origUsers != null) { 15390 for (int origUserId : res.origUsers) { 15391 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15392 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15393 origUserId, installerPackageName); 15394 } 15395 } 15396 } 15397 // Also convey the prior install/uninstall state 15398 if (allUsers != null && installedForUsers != null) { 15399 for (int currentUserId : allUsers) { 15400 final boolean installed = ArrayUtils.contains( 15401 installedForUsers, currentUserId); 15402 if (DEBUG_INSTALL) { 15403 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15404 } 15405 ps.setInstalled(installed, currentUserId); 15406 } 15407 // these install state changes will be persisted in the 15408 // upcoming call to mSettings.writeLPr(). 15409 } 15410 } 15411 // It's implied that when a user requests installation, they want the app to be 15412 // installed and enabled. 15413 if (userId != UserHandle.USER_ALL) { 15414 ps.setInstalled(true, userId); 15415 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15416 } 15417 } 15418 res.name = pkgName; 15419 res.uid = newPackage.applicationInfo.uid; 15420 res.pkg = newPackage; 15421 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15422 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15423 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15424 //to update install status 15425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15426 mSettings.writeLPr(); 15427 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15428 } 15429 15430 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15431 } 15432 15433 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15434 try { 15435 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15436 installPackageLI(args, res); 15437 } finally { 15438 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15439 } 15440 } 15441 15442 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15443 final int installFlags = args.installFlags; 15444 final String installerPackageName = args.installerPackageName; 15445 final String volumeUuid = args.volumeUuid; 15446 final File tmpPackageFile = new File(args.getCodePath()); 15447 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15448 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15449 || (args.volumeUuid != null)); 15450 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15451 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15452 boolean replace = false; 15453 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15454 if (args.move != null) { 15455 // moving a complete application; perform an initial scan on the new install location 15456 scanFlags |= SCAN_INITIAL; 15457 } 15458 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15459 scanFlags |= SCAN_DONT_KILL_APP; 15460 } 15461 15462 // Result object to be returned 15463 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15464 15465 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15466 15467 // Sanity check 15468 if (ephemeral && (forwardLocked || onExternal)) { 15469 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15470 + " external=" + onExternal); 15471 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15472 return; 15473 } 15474 15475 // Retrieve PackageSettings and parse package 15476 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15477 | PackageParser.PARSE_ENFORCE_CODE 15478 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15479 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15480 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15481 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15482 PackageParser pp = new PackageParser(); 15483 pp.setSeparateProcesses(mSeparateProcesses); 15484 pp.setDisplayMetrics(mMetrics); 15485 15486 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15487 final PackageParser.Package pkg; 15488 try { 15489 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15490 } catch (PackageParserException e) { 15491 res.setError("Failed parse during installPackageLI", e); 15492 return; 15493 } finally { 15494 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15495 } 15496 15497 // Ephemeral apps must have target SDK >= O. 15498 // TODO: Update conditional and error message when O gets locked down 15499 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 15500 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 15501 "Ephemeral apps must have target SDK version of at least O"); 15502 return; 15503 } 15504 15505 // If we are installing a clustered package add results for the children 15506 if (pkg.childPackages != null) { 15507 synchronized (mPackages) { 15508 final int childCount = pkg.childPackages.size(); 15509 for (int i = 0; i < childCount; i++) { 15510 PackageParser.Package childPkg = pkg.childPackages.get(i); 15511 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15512 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15513 childRes.pkg = childPkg; 15514 childRes.name = childPkg.packageName; 15515 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15516 if (childPs != null) { 15517 childRes.origUsers = childPs.queryInstalledUsers( 15518 sUserManager.getUserIds(), true); 15519 } 15520 if ((mPackages.containsKey(childPkg.packageName))) { 15521 childRes.removedInfo = new PackageRemovedInfo(); 15522 childRes.removedInfo.removedPackage = childPkg.packageName; 15523 } 15524 if (res.addedChildPackages == null) { 15525 res.addedChildPackages = new ArrayMap<>(); 15526 } 15527 res.addedChildPackages.put(childPkg.packageName, childRes); 15528 } 15529 } 15530 } 15531 15532 // If package doesn't declare API override, mark that we have an install 15533 // time CPU ABI override. 15534 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15535 pkg.cpuAbiOverride = args.abiOverride; 15536 } 15537 15538 String pkgName = res.name = pkg.packageName; 15539 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15540 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15541 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15542 return; 15543 } 15544 } 15545 15546 try { 15547 // either use what we've been given or parse directly from the APK 15548 if (args.certificates != null) { 15549 try { 15550 PackageParser.populateCertificates(pkg, args.certificates); 15551 } catch (PackageParserException e) { 15552 // there was something wrong with the certificates we were given; 15553 // try to pull them from the APK 15554 PackageParser.collectCertificates(pkg, parseFlags); 15555 } 15556 } else { 15557 PackageParser.collectCertificates(pkg, parseFlags); 15558 } 15559 } catch (PackageParserException e) { 15560 res.setError("Failed collect during installPackageLI", e); 15561 return; 15562 } 15563 15564 // Get rid of all references to package scan path via parser. 15565 pp = null; 15566 String oldCodePath = null; 15567 boolean systemApp = false; 15568 synchronized (mPackages) { 15569 // Check if installing already existing package 15570 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15571 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15572 if (pkg.mOriginalPackages != null 15573 && pkg.mOriginalPackages.contains(oldName) 15574 && mPackages.containsKey(oldName)) { 15575 // This package is derived from an original package, 15576 // and this device has been updating from that original 15577 // name. We must continue using the original name, so 15578 // rename the new package here. 15579 pkg.setPackageName(oldName); 15580 pkgName = pkg.packageName; 15581 replace = true; 15582 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15583 + oldName + " pkgName=" + pkgName); 15584 } else if (mPackages.containsKey(pkgName)) { 15585 // This package, under its official name, already exists 15586 // on the device; we should replace it. 15587 replace = true; 15588 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15589 } 15590 15591 // Child packages are installed through the parent package 15592 if (pkg.parentPackage != null) { 15593 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15594 "Package " + pkg.packageName + " is child of package " 15595 + pkg.parentPackage.parentPackage + ". Child packages " 15596 + "can be updated only through the parent package."); 15597 return; 15598 } 15599 15600 if (replace) { 15601 // Prevent apps opting out from runtime permissions 15602 PackageParser.Package oldPackage = mPackages.get(pkgName); 15603 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15604 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15605 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15606 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15607 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15608 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15609 + " doesn't support runtime permissions but the old" 15610 + " target SDK " + oldTargetSdk + " does."); 15611 return; 15612 } 15613 15614 // Prevent installing of child packages 15615 if (oldPackage.parentPackage != null) { 15616 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15617 "Package " + pkg.packageName + " is child of package " 15618 + oldPackage.parentPackage + ". Child packages " 15619 + "can be updated only through the parent package."); 15620 return; 15621 } 15622 } 15623 } 15624 15625 PackageSetting ps = mSettings.mPackages.get(pkgName); 15626 if (ps != null) { 15627 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15628 15629 // Quick sanity check that we're signed correctly if updating; 15630 // we'll check this again later when scanning, but we want to 15631 // bail early here before tripping over redefined permissions. 15632 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15633 if (!checkUpgradeKeySetLP(ps, pkg)) { 15634 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15635 + pkg.packageName + " upgrade keys do not match the " 15636 + "previously installed version"); 15637 return; 15638 } 15639 } else { 15640 try { 15641 verifySignaturesLP(ps, pkg); 15642 } catch (PackageManagerException e) { 15643 res.setError(e.error, e.getMessage()); 15644 return; 15645 } 15646 } 15647 15648 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15649 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15650 systemApp = (ps.pkg.applicationInfo.flags & 15651 ApplicationInfo.FLAG_SYSTEM) != 0; 15652 } 15653 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15654 } 15655 15656 // Check whether the newly-scanned package wants to define an already-defined perm 15657 int N = pkg.permissions.size(); 15658 for (int i = N-1; i >= 0; i--) { 15659 PackageParser.Permission perm = pkg.permissions.get(i); 15660 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15661 if (bp != null) { 15662 // If the defining package is signed with our cert, it's okay. This 15663 // also includes the "updating the same package" case, of course. 15664 // "updating same package" could also involve key-rotation. 15665 final boolean sigsOk; 15666 if (bp.sourcePackage.equals(pkg.packageName) 15667 && (bp.packageSetting instanceof PackageSetting) 15668 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15669 scanFlags))) { 15670 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15671 } else { 15672 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15673 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15674 } 15675 if (!sigsOk) { 15676 // If the owning package is the system itself, we log but allow 15677 // install to proceed; we fail the install on all other permission 15678 // redefinitions. 15679 if (!bp.sourcePackage.equals("android")) { 15680 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15681 + pkg.packageName + " attempting to redeclare permission " 15682 + perm.info.name + " already owned by " + bp.sourcePackage); 15683 res.origPermission = perm.info.name; 15684 res.origPackage = bp.sourcePackage; 15685 return; 15686 } else { 15687 Slog.w(TAG, "Package " + pkg.packageName 15688 + " attempting to redeclare system permission " 15689 + perm.info.name + "; ignoring new declaration"); 15690 pkg.permissions.remove(i); 15691 } 15692 } 15693 } 15694 } 15695 } 15696 15697 if (systemApp) { 15698 if (onExternal) { 15699 // Abort update; system app can't be replaced with app on sdcard 15700 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15701 "Cannot install updates to system apps on sdcard"); 15702 return; 15703 } else if (ephemeral) { 15704 // Abort update; system app can't be replaced with an ephemeral app 15705 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15706 "Cannot update a system app with an ephemeral app"); 15707 return; 15708 } 15709 } 15710 15711 if (args.move != null) { 15712 // We did an in-place move, so dex is ready to roll 15713 scanFlags |= SCAN_NO_DEX; 15714 scanFlags |= SCAN_MOVE; 15715 15716 synchronized (mPackages) { 15717 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15718 if (ps == null) { 15719 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15720 "Missing settings for moved package " + pkgName); 15721 } 15722 15723 // We moved the entire application as-is, so bring over the 15724 // previously derived ABI information. 15725 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15726 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15727 } 15728 15729 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15730 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15731 scanFlags |= SCAN_NO_DEX; 15732 15733 try { 15734 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15735 args.abiOverride : pkg.cpuAbiOverride); 15736 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15737 true /*extractLibs*/, mAppLib32InstallDir); 15738 } catch (PackageManagerException pme) { 15739 Slog.e(TAG, "Error deriving application ABI", pme); 15740 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15741 return; 15742 } 15743 15744 // Shared libraries for the package need to be updated. 15745 synchronized (mPackages) { 15746 try { 15747 updateSharedLibrariesLPr(pkg, null); 15748 } catch (PackageManagerException e) { 15749 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15750 } 15751 } 15752 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15753 // Do not run PackageDexOptimizer through the local performDexOpt 15754 // method because `pkg` may not be in `mPackages` yet. 15755 // 15756 // Also, don't fail application installs if the dexopt step fails. 15757 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15758 null /* instructionSets */, false /* checkProfiles */, 15759 getCompilerFilterForReason(REASON_INSTALL), 15760 getOrCreateCompilerPackageStats(pkg)); 15761 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15762 15763 // Notify BackgroundDexOptService that the package has been changed. 15764 // If this is an update of a package which used to fail to compile, 15765 // BDOS will remove it from its blacklist. 15766 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15767 } 15768 15769 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15770 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15771 return; 15772 } 15773 15774 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15775 15776 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15777 "installPackageLI")) { 15778 if (replace) { 15779 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15780 installerPackageName, res); 15781 } else { 15782 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15783 args.user, installerPackageName, volumeUuid, res); 15784 } 15785 } 15786 synchronized (mPackages) { 15787 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15788 if (ps != null) { 15789 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15790 } 15791 15792 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15793 for (int i = 0; i < childCount; i++) { 15794 PackageParser.Package childPkg = pkg.childPackages.get(i); 15795 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15796 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15797 if (childPs != null) { 15798 childRes.newUsers = childPs.queryInstalledUsers( 15799 sUserManager.getUserIds(), true); 15800 } 15801 } 15802 } 15803 } 15804 15805 private void startIntentFilterVerifications(int userId, boolean replacing, 15806 PackageParser.Package pkg) { 15807 if (mIntentFilterVerifierComponent == null) { 15808 Slog.w(TAG, "No IntentFilter verification will not be done as " 15809 + "there is no IntentFilterVerifier available!"); 15810 return; 15811 } 15812 15813 final int verifierUid = getPackageUid( 15814 mIntentFilterVerifierComponent.getPackageName(), 15815 MATCH_DEBUG_TRIAGED_MISSING, 15816 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15817 15818 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15819 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15820 mHandler.sendMessage(msg); 15821 15822 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15823 for (int i = 0; i < childCount; i++) { 15824 PackageParser.Package childPkg = pkg.childPackages.get(i); 15825 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15826 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15827 mHandler.sendMessage(msg); 15828 } 15829 } 15830 15831 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15832 PackageParser.Package pkg) { 15833 int size = pkg.activities.size(); 15834 if (size == 0) { 15835 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15836 "No activity, so no need to verify any IntentFilter!"); 15837 return; 15838 } 15839 15840 final boolean hasDomainURLs = hasDomainURLs(pkg); 15841 if (!hasDomainURLs) { 15842 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15843 "No domain URLs, so no need to verify any IntentFilter!"); 15844 return; 15845 } 15846 15847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15848 + " if any IntentFilter from the " + size 15849 + " Activities needs verification ..."); 15850 15851 int count = 0; 15852 final String packageName = pkg.packageName; 15853 15854 synchronized (mPackages) { 15855 // If this is a new install and we see that we've already run verification for this 15856 // package, we have nothing to do: it means the state was restored from backup. 15857 if (!replacing) { 15858 IntentFilterVerificationInfo ivi = 15859 mSettings.getIntentFilterVerificationLPr(packageName); 15860 if (ivi != null) { 15861 if (DEBUG_DOMAIN_VERIFICATION) { 15862 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15863 + ivi.getStatusString()); 15864 } 15865 return; 15866 } 15867 } 15868 15869 // If any filters need to be verified, then all need to be. 15870 boolean needToVerify = false; 15871 for (PackageParser.Activity a : pkg.activities) { 15872 for (ActivityIntentInfo filter : a.intents) { 15873 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15874 if (DEBUG_DOMAIN_VERIFICATION) { 15875 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15876 } 15877 needToVerify = true; 15878 break; 15879 } 15880 } 15881 } 15882 15883 if (needToVerify) { 15884 final int verificationId = mIntentFilterVerificationToken++; 15885 for (PackageParser.Activity a : pkg.activities) { 15886 for (ActivityIntentInfo filter : a.intents) { 15887 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15888 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15889 "Verification needed for IntentFilter:" + filter.toString()); 15890 mIntentFilterVerifier.addOneIntentFilterVerification( 15891 verifierUid, userId, verificationId, filter, packageName); 15892 count++; 15893 } 15894 } 15895 } 15896 } 15897 } 15898 15899 if (count > 0) { 15900 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15901 + " IntentFilter verification" + (count > 1 ? "s" : "") 15902 + " for userId:" + userId); 15903 mIntentFilterVerifier.startVerifications(userId); 15904 } else { 15905 if (DEBUG_DOMAIN_VERIFICATION) { 15906 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15907 } 15908 } 15909 } 15910 15911 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15912 final ComponentName cn = filter.activity.getComponentName(); 15913 final String packageName = cn.getPackageName(); 15914 15915 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15916 packageName); 15917 if (ivi == null) { 15918 return true; 15919 } 15920 int status = ivi.getStatus(); 15921 switch (status) { 15922 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15923 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15924 return true; 15925 15926 default: 15927 // Nothing to do 15928 return false; 15929 } 15930 } 15931 15932 private static boolean isMultiArch(ApplicationInfo info) { 15933 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15934 } 15935 15936 private static boolean isExternal(PackageParser.Package pkg) { 15937 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15938 } 15939 15940 private static boolean isExternal(PackageSetting ps) { 15941 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15942 } 15943 15944 private static boolean isEphemeral(PackageParser.Package pkg) { 15945 return pkg.applicationInfo.isEphemeralApp(); 15946 } 15947 15948 private static boolean isEphemeral(PackageSetting ps) { 15949 return ps.pkg != null && isEphemeral(ps.pkg); 15950 } 15951 15952 private static boolean isSystemApp(PackageParser.Package pkg) { 15953 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15954 } 15955 15956 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15957 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15958 } 15959 15960 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15961 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15962 } 15963 15964 private static boolean isSystemApp(PackageSetting ps) { 15965 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15966 } 15967 15968 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15969 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15970 } 15971 15972 private int packageFlagsToInstallFlags(PackageSetting ps) { 15973 int installFlags = 0; 15974 if (isEphemeral(ps)) { 15975 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15976 } 15977 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15978 // This existing package was an external ASEC install when we have 15979 // the external flag without a UUID 15980 installFlags |= PackageManager.INSTALL_EXTERNAL; 15981 } 15982 if (ps.isForwardLocked()) { 15983 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15984 } 15985 return installFlags; 15986 } 15987 15988 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15989 if (isExternal(pkg)) { 15990 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15991 return StorageManager.UUID_PRIMARY_PHYSICAL; 15992 } else { 15993 return pkg.volumeUuid; 15994 } 15995 } else { 15996 return StorageManager.UUID_PRIVATE_INTERNAL; 15997 } 15998 } 15999 16000 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16001 if (isExternal(pkg)) { 16002 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16003 return mSettings.getExternalVersion(); 16004 } else { 16005 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16006 } 16007 } else { 16008 return mSettings.getInternalVersion(); 16009 } 16010 } 16011 16012 private void deleteTempPackageFiles() { 16013 final FilenameFilter filter = new FilenameFilter() { 16014 public boolean accept(File dir, String name) { 16015 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16016 } 16017 }; 16018 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16019 file.delete(); 16020 } 16021 } 16022 16023 @Override 16024 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 16025 int flags) { 16026 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 16027 flags); 16028 } 16029 16030 @Override 16031 public void deletePackage(final String packageName, 16032 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16033 mContext.enforceCallingOrSelfPermission( 16034 android.Manifest.permission.DELETE_PACKAGES, null); 16035 Preconditions.checkNotNull(packageName); 16036 Preconditions.checkNotNull(observer); 16037 final int uid = Binder.getCallingUid(); 16038 if (!isOrphaned(packageName) 16039 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 16040 try { 16041 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16042 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16043 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16044 observer.onUserActionRequired(intent); 16045 } catch (RemoteException re) { 16046 } 16047 return; 16048 } 16049 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16050 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16051 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16052 mContext.enforceCallingOrSelfPermission( 16053 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16054 "deletePackage for user " + userId); 16055 } 16056 16057 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16058 try { 16059 observer.onPackageDeleted(packageName, 16060 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16061 } catch (RemoteException re) { 16062 } 16063 return; 16064 } 16065 16066 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 16067 try { 16068 observer.onPackageDeleted(packageName, 16069 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16070 } catch (RemoteException re) { 16071 } 16072 return; 16073 } 16074 16075 if (DEBUG_REMOVE) { 16076 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 16077 + " deleteAllUsers: " + deleteAllUsers ); 16078 } 16079 // Queue up an async operation since the package deletion may take a little while. 16080 mHandler.post(new Runnable() { 16081 public void run() { 16082 mHandler.removeCallbacks(this); 16083 int returnCode; 16084 if (!deleteAllUsers) { 16085 returnCode = deletePackageX(packageName, userId, deleteFlags); 16086 } else { 16087 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 16088 // If nobody is blocking uninstall, proceed with delete for all users 16089 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16090 returnCode = deletePackageX(packageName, userId, deleteFlags); 16091 } else { 16092 // Otherwise uninstall individually for users with blockUninstalls=false 16093 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16094 for (int userId : users) { 16095 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16096 returnCode = deletePackageX(packageName, userId, userFlags); 16097 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16098 Slog.w(TAG, "Package delete failed for user " + userId 16099 + ", returnCode " + returnCode); 16100 } 16101 } 16102 } 16103 // The app has only been marked uninstalled for certain users. 16104 // We still need to report that delete was blocked 16105 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16106 } 16107 } 16108 try { 16109 observer.onPackageDeleted(packageName, returnCode, null); 16110 } catch (RemoteException e) { 16111 Log.i(TAG, "Observer no longer exists."); 16112 } //end catch 16113 } //end run 16114 }); 16115 } 16116 16117 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 16118 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 16119 || callingUid == Process.SYSTEM_UID) { 16120 return true; 16121 } 16122 final int callingUserId = UserHandle.getUserId(callingUid); 16123 // If the caller installed the pkgName, then allow it to silently uninstall. 16124 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 16125 return true; 16126 } 16127 16128 // Allow package verifier to silently uninstall. 16129 if (mRequiredVerifierPackage != null && 16130 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 16131 return true; 16132 } 16133 16134 // Allow package uninstaller to silently uninstall. 16135 if (mRequiredUninstallerPackage != null && 16136 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 16137 return true; 16138 } 16139 16140 // Allow storage manager to silently uninstall. 16141 if (mStorageManagerPackage != null && 16142 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 16143 return true; 16144 } 16145 return false; 16146 } 16147 16148 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16149 int[] result = EMPTY_INT_ARRAY; 16150 for (int userId : userIds) { 16151 if (getBlockUninstallForUser(packageName, userId)) { 16152 result = ArrayUtils.appendInt(result, userId); 16153 } 16154 } 16155 return result; 16156 } 16157 16158 @Override 16159 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16160 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16161 } 16162 16163 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16164 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16165 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16166 try { 16167 if (dpm != null) { 16168 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16169 /* callingUserOnly =*/ false); 16170 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16171 : deviceOwnerComponentName.getPackageName(); 16172 // Does the package contains the device owner? 16173 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16174 // this check is probably not needed, since DO should be registered as a device 16175 // admin on some user too. (Original bug for this: b/17657954) 16176 if (packageName.equals(deviceOwnerPackageName)) { 16177 return true; 16178 } 16179 // Does it contain a device admin for any user? 16180 int[] users; 16181 if (userId == UserHandle.USER_ALL) { 16182 users = sUserManager.getUserIds(); 16183 } else { 16184 users = new int[]{userId}; 16185 } 16186 for (int i = 0; i < users.length; ++i) { 16187 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16188 return true; 16189 } 16190 } 16191 } 16192 } catch (RemoteException e) { 16193 } 16194 return false; 16195 } 16196 16197 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16198 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16199 } 16200 16201 /** 16202 * This method is an internal method that could be get invoked either 16203 * to delete an installed package or to clean up a failed installation. 16204 * After deleting an installed package, a broadcast is sent to notify any 16205 * listeners that the package has been removed. For cleaning up a failed 16206 * installation, the broadcast is not necessary since the package's 16207 * installation wouldn't have sent the initial broadcast either 16208 * The key steps in deleting a package are 16209 * deleting the package information in internal structures like mPackages, 16210 * deleting the packages base directories through installd 16211 * updating mSettings to reflect current status 16212 * persisting settings for later use 16213 * sending a broadcast if necessary 16214 */ 16215 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16216 final PackageRemovedInfo info = new PackageRemovedInfo(); 16217 final boolean res; 16218 16219 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16220 ? UserHandle.USER_ALL : userId; 16221 16222 if (isPackageDeviceAdmin(packageName, removeUser)) { 16223 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16224 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16225 } 16226 16227 PackageSetting uninstalledPs = null; 16228 16229 // for the uninstall-updates case and restricted profiles, remember the per- 16230 // user handle installed state 16231 int[] allUsers; 16232 synchronized (mPackages) { 16233 uninstalledPs = mSettings.mPackages.get(packageName); 16234 if (uninstalledPs == null) { 16235 Slog.w(TAG, "Not removing non-existent package " + packageName); 16236 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16237 } 16238 allUsers = sUserManager.getUserIds(); 16239 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16240 } 16241 16242 final int freezeUser; 16243 if (isUpdatedSystemApp(uninstalledPs) 16244 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16245 // We're downgrading a system app, which will apply to all users, so 16246 // freeze them all during the downgrade 16247 freezeUser = UserHandle.USER_ALL; 16248 } else { 16249 freezeUser = removeUser; 16250 } 16251 16252 synchronized (mInstallLock) { 16253 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16254 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16255 deleteFlags, "deletePackageX")) { 16256 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16257 deleteFlags | REMOVE_CHATTY, info, true, null); 16258 } 16259 synchronized (mPackages) { 16260 if (res) { 16261 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16262 } 16263 } 16264 } 16265 16266 if (res) { 16267 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16268 info.sendPackageRemovedBroadcasts(killApp); 16269 info.sendSystemPackageUpdatedBroadcasts(); 16270 info.sendSystemPackageAppearedBroadcasts(); 16271 } 16272 // Force a gc here. 16273 Runtime.getRuntime().gc(); 16274 // Delete the resources here after sending the broadcast to let 16275 // other processes clean up before deleting resources. 16276 if (info.args != null) { 16277 synchronized (mInstallLock) { 16278 info.args.doPostDeleteLI(true); 16279 } 16280 } 16281 16282 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16283 } 16284 16285 class PackageRemovedInfo { 16286 String removedPackage; 16287 int uid = -1; 16288 int removedAppId = -1; 16289 int[] origUsers; 16290 int[] removedUsers = null; 16291 boolean isRemovedPackageSystemUpdate = false; 16292 boolean isUpdate; 16293 boolean dataRemoved; 16294 boolean removedForAllUsers; 16295 // Clean up resources deleted packages. 16296 InstallArgs args = null; 16297 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16298 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16299 16300 void sendPackageRemovedBroadcasts(boolean killApp) { 16301 sendPackageRemovedBroadcastInternal(killApp); 16302 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16303 for (int i = 0; i < childCount; i++) { 16304 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16305 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16306 } 16307 } 16308 16309 void sendSystemPackageUpdatedBroadcasts() { 16310 if (isRemovedPackageSystemUpdate) { 16311 sendSystemPackageUpdatedBroadcastsInternal(); 16312 final int childCount = (removedChildPackages != null) 16313 ? removedChildPackages.size() : 0; 16314 for (int i = 0; i < childCount; i++) { 16315 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16316 if (childInfo.isRemovedPackageSystemUpdate) { 16317 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16318 } 16319 } 16320 } 16321 } 16322 16323 void sendSystemPackageAppearedBroadcasts() { 16324 final int packageCount = (appearedChildPackages != null) 16325 ? appearedChildPackages.size() : 0; 16326 for (int i = 0; i < packageCount; i++) { 16327 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16328 sendPackageAddedForNewUsers(installedInfo.name, true, 16329 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16330 } 16331 } 16332 16333 private void sendSystemPackageUpdatedBroadcastsInternal() { 16334 Bundle extras = new Bundle(2); 16335 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16336 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16337 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16338 extras, 0, null, null, null); 16339 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16340 extras, 0, null, null, null); 16341 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16342 null, 0, removedPackage, null, null); 16343 } 16344 16345 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16346 Bundle extras = new Bundle(2); 16347 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16348 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16349 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16350 if (isUpdate || isRemovedPackageSystemUpdate) { 16351 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16352 } 16353 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16354 if (removedPackage != null) { 16355 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16356 extras, 0, null, null, removedUsers); 16357 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16358 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16359 removedPackage, extras, 0, null, null, removedUsers); 16360 } 16361 } 16362 if (removedAppId >= 0) { 16363 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16364 removedUsers); 16365 } 16366 } 16367 } 16368 16369 /* 16370 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16371 * flag is not set, the data directory is removed as well. 16372 * make sure this flag is set for partially installed apps. If not its meaningless to 16373 * delete a partially installed application. 16374 */ 16375 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16376 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16377 String packageName = ps.name; 16378 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16379 // Retrieve object to delete permissions for shared user later on 16380 final PackageParser.Package deletedPkg; 16381 final PackageSetting deletedPs; 16382 // reader 16383 synchronized (mPackages) { 16384 deletedPkg = mPackages.get(packageName); 16385 deletedPs = mSettings.mPackages.get(packageName); 16386 if (outInfo != null) { 16387 outInfo.removedPackage = packageName; 16388 outInfo.removedUsers = deletedPs != null 16389 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16390 : null; 16391 } 16392 } 16393 16394 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16395 16396 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16397 final PackageParser.Package resolvedPkg; 16398 if (deletedPkg != null) { 16399 resolvedPkg = deletedPkg; 16400 } else { 16401 // We don't have a parsed package when it lives on an ejected 16402 // adopted storage device, so fake something together 16403 resolvedPkg = new PackageParser.Package(ps.name); 16404 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16405 } 16406 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16407 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16408 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16409 if (outInfo != null) { 16410 outInfo.dataRemoved = true; 16411 } 16412 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16413 } 16414 16415 // writer 16416 synchronized (mPackages) { 16417 if (deletedPs != null) { 16418 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16419 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16420 clearDefaultBrowserIfNeeded(packageName); 16421 if (outInfo != null) { 16422 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16423 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16424 } 16425 updatePermissionsLPw(deletedPs.name, null, 0); 16426 if (deletedPs.sharedUser != null) { 16427 // Remove permissions associated with package. Since runtime 16428 // permissions are per user we have to kill the removed package 16429 // or packages running under the shared user of the removed 16430 // package if revoking the permissions requested only by the removed 16431 // package is successful and this causes a change in gids. 16432 for (int userId : UserManagerService.getInstance().getUserIds()) { 16433 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16434 userId); 16435 if (userIdToKill == UserHandle.USER_ALL 16436 || userIdToKill >= UserHandle.USER_SYSTEM) { 16437 // If gids changed for this user, kill all affected packages. 16438 mHandler.post(new Runnable() { 16439 @Override 16440 public void run() { 16441 // This has to happen with no lock held. 16442 killApplication(deletedPs.name, deletedPs.appId, 16443 KILL_APP_REASON_GIDS_CHANGED); 16444 } 16445 }); 16446 break; 16447 } 16448 } 16449 } 16450 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16451 } 16452 // make sure to preserve per-user disabled state if this removal was just 16453 // a downgrade of a system app to the factory package 16454 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16455 if (DEBUG_REMOVE) { 16456 Slog.d(TAG, "Propagating install state across downgrade"); 16457 } 16458 for (int userId : allUserHandles) { 16459 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16460 if (DEBUG_REMOVE) { 16461 Slog.d(TAG, " user " + userId + " => " + installed); 16462 } 16463 ps.setInstalled(installed, userId); 16464 } 16465 } 16466 } 16467 // can downgrade to reader 16468 if (writeSettings) { 16469 // Save settings now 16470 mSettings.writeLPr(); 16471 } 16472 } 16473 if (outInfo != null) { 16474 // A user ID was deleted here. Go through all users and remove it 16475 // from KeyStore. 16476 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16477 } 16478 } 16479 16480 static boolean locationIsPrivileged(File path) { 16481 try { 16482 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16483 .getCanonicalPath(); 16484 return path.getCanonicalPath().startsWith(privilegedAppDir); 16485 } catch (IOException e) { 16486 Slog.e(TAG, "Unable to access code path " + path); 16487 } 16488 return false; 16489 } 16490 16491 /* 16492 * Tries to delete system package. 16493 */ 16494 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16495 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16496 boolean writeSettings) { 16497 if (deletedPs.parentPackageName != null) { 16498 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16499 return false; 16500 } 16501 16502 final boolean applyUserRestrictions 16503 = (allUserHandles != null) && (outInfo.origUsers != null); 16504 final PackageSetting disabledPs; 16505 // Confirm if the system package has been updated 16506 // An updated system app can be deleted. This will also have to restore 16507 // the system pkg from system partition 16508 // reader 16509 synchronized (mPackages) { 16510 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16511 } 16512 16513 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16514 + " disabledPs=" + disabledPs); 16515 16516 if (disabledPs == null) { 16517 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16518 return false; 16519 } else if (DEBUG_REMOVE) { 16520 Slog.d(TAG, "Deleting system pkg from data partition"); 16521 } 16522 16523 if (DEBUG_REMOVE) { 16524 if (applyUserRestrictions) { 16525 Slog.d(TAG, "Remembering install states:"); 16526 for (int userId : allUserHandles) { 16527 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16528 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16529 } 16530 } 16531 } 16532 16533 // Delete the updated package 16534 outInfo.isRemovedPackageSystemUpdate = true; 16535 if (outInfo.removedChildPackages != null) { 16536 final int childCount = (deletedPs.childPackageNames != null) 16537 ? deletedPs.childPackageNames.size() : 0; 16538 for (int i = 0; i < childCount; i++) { 16539 String childPackageName = deletedPs.childPackageNames.get(i); 16540 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16541 .contains(childPackageName)) { 16542 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16543 childPackageName); 16544 if (childInfo != null) { 16545 childInfo.isRemovedPackageSystemUpdate = true; 16546 } 16547 } 16548 } 16549 } 16550 16551 if (disabledPs.versionCode < deletedPs.versionCode) { 16552 // Delete data for downgrades 16553 flags &= ~PackageManager.DELETE_KEEP_DATA; 16554 } else { 16555 // Preserve data by setting flag 16556 flags |= PackageManager.DELETE_KEEP_DATA; 16557 } 16558 16559 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16560 outInfo, writeSettings, disabledPs.pkg); 16561 if (!ret) { 16562 return false; 16563 } 16564 16565 // writer 16566 synchronized (mPackages) { 16567 // Reinstate the old system package 16568 enableSystemPackageLPw(disabledPs.pkg); 16569 // Remove any native libraries from the upgraded package. 16570 removeNativeBinariesLI(deletedPs); 16571 } 16572 16573 // Install the system package 16574 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16575 int parseFlags = mDefParseFlags 16576 | PackageParser.PARSE_MUST_BE_APK 16577 | PackageParser.PARSE_IS_SYSTEM 16578 | PackageParser.PARSE_IS_SYSTEM_DIR; 16579 if (locationIsPrivileged(disabledPs.codePath)) { 16580 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16581 } 16582 16583 final PackageParser.Package newPkg; 16584 try { 16585 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16586 0 /* currentTime */, null); 16587 } catch (PackageManagerException e) { 16588 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16589 + e.getMessage()); 16590 return false; 16591 } 16592 try { 16593 // update shared libraries for the newly re-installed system package 16594 updateSharedLibrariesLPr(newPkg, null); 16595 } catch (PackageManagerException e) { 16596 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16597 } 16598 16599 prepareAppDataAfterInstallLIF(newPkg); 16600 16601 // writer 16602 synchronized (mPackages) { 16603 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16604 16605 // Propagate the permissions state as we do not want to drop on the floor 16606 // runtime permissions. The update permissions method below will take 16607 // care of removing obsolete permissions and grant install permissions. 16608 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16609 updatePermissionsLPw(newPkg.packageName, newPkg, 16610 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16611 16612 if (applyUserRestrictions) { 16613 if (DEBUG_REMOVE) { 16614 Slog.d(TAG, "Propagating install state across reinstall"); 16615 } 16616 for (int userId : allUserHandles) { 16617 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16618 if (DEBUG_REMOVE) { 16619 Slog.d(TAG, " user " + userId + " => " + installed); 16620 } 16621 ps.setInstalled(installed, userId); 16622 16623 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16624 } 16625 // Regardless of writeSettings we need to ensure that this restriction 16626 // state propagation is persisted 16627 mSettings.writeAllUsersPackageRestrictionsLPr(); 16628 } 16629 // can downgrade to reader here 16630 if (writeSettings) { 16631 mSettings.writeLPr(); 16632 } 16633 } 16634 return true; 16635 } 16636 16637 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16638 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16639 PackageRemovedInfo outInfo, boolean writeSettings, 16640 PackageParser.Package replacingPackage) { 16641 synchronized (mPackages) { 16642 if (outInfo != null) { 16643 outInfo.uid = ps.appId; 16644 } 16645 16646 if (outInfo != null && outInfo.removedChildPackages != null) { 16647 final int childCount = (ps.childPackageNames != null) 16648 ? ps.childPackageNames.size() : 0; 16649 for (int i = 0; i < childCount; i++) { 16650 String childPackageName = ps.childPackageNames.get(i); 16651 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16652 if (childPs == null) { 16653 return false; 16654 } 16655 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16656 childPackageName); 16657 if (childInfo != null) { 16658 childInfo.uid = childPs.appId; 16659 } 16660 } 16661 } 16662 } 16663 16664 // Delete package data from internal structures and also remove data if flag is set 16665 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16666 16667 // Delete the child packages data 16668 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16669 for (int i = 0; i < childCount; i++) { 16670 PackageSetting childPs; 16671 synchronized (mPackages) { 16672 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16673 } 16674 if (childPs != null) { 16675 PackageRemovedInfo childOutInfo = (outInfo != null 16676 && outInfo.removedChildPackages != null) 16677 ? outInfo.removedChildPackages.get(childPs.name) : null; 16678 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16679 && (replacingPackage != null 16680 && !replacingPackage.hasChildPackage(childPs.name)) 16681 ? flags & ~DELETE_KEEP_DATA : flags; 16682 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16683 deleteFlags, writeSettings); 16684 } 16685 } 16686 16687 // Delete application code and resources only for parent packages 16688 if (ps.parentPackageName == null) { 16689 if (deleteCodeAndResources && (outInfo != null)) { 16690 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16691 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16692 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16693 } 16694 } 16695 16696 return true; 16697 } 16698 16699 @Override 16700 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16701 int userId) { 16702 mContext.enforceCallingOrSelfPermission( 16703 android.Manifest.permission.DELETE_PACKAGES, null); 16704 synchronized (mPackages) { 16705 PackageSetting ps = mSettings.mPackages.get(packageName); 16706 if (ps == null) { 16707 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16708 return false; 16709 } 16710 if (!ps.getInstalled(userId)) { 16711 // Can't block uninstall for an app that is not installed or enabled. 16712 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16713 return false; 16714 } 16715 ps.setBlockUninstall(blockUninstall, userId); 16716 mSettings.writePackageRestrictionsLPr(userId); 16717 } 16718 return true; 16719 } 16720 16721 @Override 16722 public boolean getBlockUninstallForUser(String packageName, int userId) { 16723 synchronized (mPackages) { 16724 PackageSetting ps = mSettings.mPackages.get(packageName); 16725 if (ps == null) { 16726 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16727 return false; 16728 } 16729 return ps.getBlockUninstall(userId); 16730 } 16731 } 16732 16733 @Override 16734 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16735 int callingUid = Binder.getCallingUid(); 16736 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16737 throw new SecurityException( 16738 "setRequiredForSystemUser can only be run by the system or root"); 16739 } 16740 synchronized (mPackages) { 16741 PackageSetting ps = mSettings.mPackages.get(packageName); 16742 if (ps == null) { 16743 Log.w(TAG, "Package doesn't exist: " + packageName); 16744 return false; 16745 } 16746 if (systemUserApp) { 16747 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16748 } else { 16749 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16750 } 16751 mSettings.writeLPr(); 16752 } 16753 return true; 16754 } 16755 16756 /* 16757 * This method handles package deletion in general 16758 */ 16759 private boolean deletePackageLIF(String packageName, UserHandle user, 16760 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16761 PackageRemovedInfo outInfo, boolean writeSettings, 16762 PackageParser.Package replacingPackage) { 16763 if (packageName == null) { 16764 Slog.w(TAG, "Attempt to delete null packageName."); 16765 return false; 16766 } 16767 16768 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16769 16770 PackageSetting ps; 16771 16772 synchronized (mPackages) { 16773 ps = mSettings.mPackages.get(packageName); 16774 if (ps == null) { 16775 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16776 return false; 16777 } 16778 16779 if (ps.parentPackageName != null && (!isSystemApp(ps) 16780 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16781 if (DEBUG_REMOVE) { 16782 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16783 + ((user == null) ? UserHandle.USER_ALL : user)); 16784 } 16785 final int removedUserId = (user != null) ? user.getIdentifier() 16786 : UserHandle.USER_ALL; 16787 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16788 return false; 16789 } 16790 markPackageUninstalledForUserLPw(ps, user); 16791 scheduleWritePackageRestrictionsLocked(user); 16792 return true; 16793 } 16794 } 16795 16796 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16797 && user.getIdentifier() != UserHandle.USER_ALL)) { 16798 // The caller is asking that the package only be deleted for a single 16799 // user. To do this, we just mark its uninstalled state and delete 16800 // its data. If this is a system app, we only allow this to happen if 16801 // they have set the special DELETE_SYSTEM_APP which requests different 16802 // semantics than normal for uninstalling system apps. 16803 markPackageUninstalledForUserLPw(ps, user); 16804 16805 if (!isSystemApp(ps)) { 16806 // Do not uninstall the APK if an app should be cached 16807 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16808 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16809 // Other user still have this package installed, so all 16810 // we need to do is clear this user's data and save that 16811 // it is uninstalled. 16812 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16813 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16814 return false; 16815 } 16816 scheduleWritePackageRestrictionsLocked(user); 16817 return true; 16818 } else { 16819 // We need to set it back to 'installed' so the uninstall 16820 // broadcasts will be sent correctly. 16821 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16822 ps.setInstalled(true, user.getIdentifier()); 16823 } 16824 } else { 16825 // This is a system app, so we assume that the 16826 // other users still have this package installed, so all 16827 // we need to do is clear this user's data and save that 16828 // it is uninstalled. 16829 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16830 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16831 return false; 16832 } 16833 scheduleWritePackageRestrictionsLocked(user); 16834 return true; 16835 } 16836 } 16837 16838 // If we are deleting a composite package for all users, keep track 16839 // of result for each child. 16840 if (ps.childPackageNames != null && outInfo != null) { 16841 synchronized (mPackages) { 16842 final int childCount = ps.childPackageNames.size(); 16843 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16844 for (int i = 0; i < childCount; i++) { 16845 String childPackageName = ps.childPackageNames.get(i); 16846 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16847 childInfo.removedPackage = childPackageName; 16848 outInfo.removedChildPackages.put(childPackageName, childInfo); 16849 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16850 if (childPs != null) { 16851 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16852 } 16853 } 16854 } 16855 } 16856 16857 boolean ret = false; 16858 if (isSystemApp(ps)) { 16859 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16860 // When an updated system application is deleted we delete the existing resources 16861 // as well and fall back to existing code in system partition 16862 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16863 } else { 16864 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16865 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16866 outInfo, writeSettings, replacingPackage); 16867 } 16868 16869 // Take a note whether we deleted the package for all users 16870 if (outInfo != null) { 16871 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16872 if (outInfo.removedChildPackages != null) { 16873 synchronized (mPackages) { 16874 final int childCount = outInfo.removedChildPackages.size(); 16875 for (int i = 0; i < childCount; i++) { 16876 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16877 if (childInfo != null) { 16878 childInfo.removedForAllUsers = mPackages.get( 16879 childInfo.removedPackage) == null; 16880 } 16881 } 16882 } 16883 } 16884 // If we uninstalled an update to a system app there may be some 16885 // child packages that appeared as they are declared in the system 16886 // app but were not declared in the update. 16887 if (isSystemApp(ps)) { 16888 synchronized (mPackages) { 16889 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16890 final int childCount = (updatedPs.childPackageNames != null) 16891 ? updatedPs.childPackageNames.size() : 0; 16892 for (int i = 0; i < childCount; i++) { 16893 String childPackageName = updatedPs.childPackageNames.get(i); 16894 if (outInfo.removedChildPackages == null 16895 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16896 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16897 if (childPs == null) { 16898 continue; 16899 } 16900 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16901 installRes.name = childPackageName; 16902 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16903 installRes.pkg = mPackages.get(childPackageName); 16904 installRes.uid = childPs.pkg.applicationInfo.uid; 16905 if (outInfo.appearedChildPackages == null) { 16906 outInfo.appearedChildPackages = new ArrayMap<>(); 16907 } 16908 outInfo.appearedChildPackages.put(childPackageName, installRes); 16909 } 16910 } 16911 } 16912 } 16913 } 16914 16915 return ret; 16916 } 16917 16918 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16919 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16920 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16921 for (int nextUserId : userIds) { 16922 if (DEBUG_REMOVE) { 16923 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16924 } 16925 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16926 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16927 false /*hidden*/, false /*suspended*/, null, null, null, 16928 false /*blockUninstall*/, 16929 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16930 } 16931 } 16932 16933 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16934 PackageRemovedInfo outInfo) { 16935 final PackageParser.Package pkg; 16936 synchronized (mPackages) { 16937 pkg = mPackages.get(ps.name); 16938 } 16939 16940 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16941 : new int[] {userId}; 16942 for (int nextUserId : userIds) { 16943 if (DEBUG_REMOVE) { 16944 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16945 + nextUserId); 16946 } 16947 16948 destroyAppDataLIF(pkg, userId, 16949 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16950 destroyAppProfilesLIF(pkg, userId); 16951 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16952 schedulePackageCleaning(ps.name, nextUserId, false); 16953 synchronized (mPackages) { 16954 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16955 scheduleWritePackageRestrictionsLocked(nextUserId); 16956 } 16957 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16958 } 16959 } 16960 16961 if (outInfo != null) { 16962 outInfo.removedPackage = ps.name; 16963 outInfo.removedAppId = ps.appId; 16964 outInfo.removedUsers = userIds; 16965 } 16966 16967 return true; 16968 } 16969 16970 private final class ClearStorageConnection implements ServiceConnection { 16971 IMediaContainerService mContainerService; 16972 16973 @Override 16974 public void onServiceConnected(ComponentName name, IBinder service) { 16975 synchronized (this) { 16976 mContainerService = IMediaContainerService.Stub 16977 .asInterface(Binder.allowBlocking(service)); 16978 notifyAll(); 16979 } 16980 } 16981 16982 @Override 16983 public void onServiceDisconnected(ComponentName name) { 16984 } 16985 } 16986 16987 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16988 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16989 16990 final boolean mounted; 16991 if (Environment.isExternalStorageEmulated()) { 16992 mounted = true; 16993 } else { 16994 final String status = Environment.getExternalStorageState(); 16995 16996 mounted = status.equals(Environment.MEDIA_MOUNTED) 16997 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16998 } 16999 17000 if (!mounted) { 17001 return; 17002 } 17003 17004 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 17005 int[] users; 17006 if (userId == UserHandle.USER_ALL) { 17007 users = sUserManager.getUserIds(); 17008 } else { 17009 users = new int[] { userId }; 17010 } 17011 final ClearStorageConnection conn = new ClearStorageConnection(); 17012 if (mContext.bindServiceAsUser( 17013 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 17014 try { 17015 for (int curUser : users) { 17016 long timeout = SystemClock.uptimeMillis() + 5000; 17017 synchronized (conn) { 17018 long now; 17019 while (conn.mContainerService == null && 17020 (now = SystemClock.uptimeMillis()) < timeout) { 17021 try { 17022 conn.wait(timeout - now); 17023 } catch (InterruptedException e) { 17024 } 17025 } 17026 } 17027 if (conn.mContainerService == null) { 17028 return; 17029 } 17030 17031 final UserEnvironment userEnv = new UserEnvironment(curUser); 17032 clearDirectory(conn.mContainerService, 17033 userEnv.buildExternalStorageAppCacheDirs(packageName)); 17034 if (allData) { 17035 clearDirectory(conn.mContainerService, 17036 userEnv.buildExternalStorageAppDataDirs(packageName)); 17037 clearDirectory(conn.mContainerService, 17038 userEnv.buildExternalStorageAppMediaDirs(packageName)); 17039 } 17040 } 17041 } finally { 17042 mContext.unbindService(conn); 17043 } 17044 } 17045 } 17046 17047 @Override 17048 public void clearApplicationProfileData(String packageName) { 17049 enforceSystemOrRoot("Only the system can clear all profile data"); 17050 17051 final PackageParser.Package pkg; 17052 synchronized (mPackages) { 17053 pkg = mPackages.get(packageName); 17054 } 17055 17056 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 17057 synchronized (mInstallLock) { 17058 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 17059 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 17060 true /* removeBaseMarker */); 17061 } 17062 } 17063 } 17064 17065 @Override 17066 public void clearApplicationUserData(final String packageName, 17067 final IPackageDataObserver observer, final int userId) { 17068 mContext.enforceCallingOrSelfPermission( 17069 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 17070 17071 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17072 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 17073 17074 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 17075 throw new SecurityException("Cannot clear data for a protected package: " 17076 + packageName); 17077 } 17078 // Queue up an async operation since the package deletion may take a little while. 17079 mHandler.post(new Runnable() { 17080 public void run() { 17081 mHandler.removeCallbacks(this); 17082 final boolean succeeded; 17083 try (PackageFreezer freezer = freezePackage(packageName, 17084 "clearApplicationUserData")) { 17085 synchronized (mInstallLock) { 17086 succeeded = clearApplicationUserDataLIF(packageName, userId); 17087 } 17088 clearExternalStorageDataSync(packageName, userId, true); 17089 } 17090 if (succeeded) { 17091 // invoke DeviceStorageMonitor's update method to clear any notifications 17092 DeviceStorageMonitorInternal dsm = LocalServices 17093 .getService(DeviceStorageMonitorInternal.class); 17094 if (dsm != null) { 17095 dsm.checkMemory(); 17096 } 17097 } 17098 if(observer != null) { 17099 try { 17100 observer.onRemoveCompleted(packageName, succeeded); 17101 } catch (RemoteException e) { 17102 Log.i(TAG, "Observer no longer exists."); 17103 } 17104 } //end if observer 17105 } //end run 17106 }); 17107 } 17108 17109 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 17110 if (packageName == null) { 17111 Slog.w(TAG, "Attempt to delete null packageName."); 17112 return false; 17113 } 17114 17115 // Try finding details about the requested package 17116 PackageParser.Package pkg; 17117 synchronized (mPackages) { 17118 pkg = mPackages.get(packageName); 17119 if (pkg == null) { 17120 final PackageSetting ps = mSettings.mPackages.get(packageName); 17121 if (ps != null) { 17122 pkg = ps.pkg; 17123 } 17124 } 17125 17126 if (pkg == null) { 17127 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17128 return false; 17129 } 17130 17131 PackageSetting ps = (PackageSetting) pkg.mExtras; 17132 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17133 } 17134 17135 clearAppDataLIF(pkg, userId, 17136 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17137 17138 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17139 removeKeystoreDataIfNeeded(userId, appId); 17140 17141 UserManagerInternal umInternal = getUserManagerInternal(); 17142 final int flags; 17143 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17144 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17145 } else if (umInternal.isUserRunning(userId)) { 17146 flags = StorageManager.FLAG_STORAGE_DE; 17147 } else { 17148 flags = 0; 17149 } 17150 prepareAppDataContentsLIF(pkg, userId, flags); 17151 17152 return true; 17153 } 17154 17155 /** 17156 * Reverts user permission state changes (permissions and flags) in 17157 * all packages for a given user. 17158 * 17159 * @param userId The device user for which to do a reset. 17160 */ 17161 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17162 final int packageCount = mPackages.size(); 17163 for (int i = 0; i < packageCount; i++) { 17164 PackageParser.Package pkg = mPackages.valueAt(i); 17165 PackageSetting ps = (PackageSetting) pkg.mExtras; 17166 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17167 } 17168 } 17169 17170 private void resetNetworkPolicies(int userId) { 17171 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17172 } 17173 17174 /** 17175 * Reverts user permission state changes (permissions and flags). 17176 * 17177 * @param ps The package for which to reset. 17178 * @param userId The device user for which to do a reset. 17179 */ 17180 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17181 final PackageSetting ps, final int userId) { 17182 if (ps.pkg == null) { 17183 return; 17184 } 17185 17186 // These are flags that can change base on user actions. 17187 final int userSettableMask = FLAG_PERMISSION_USER_SET 17188 | FLAG_PERMISSION_USER_FIXED 17189 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17190 | FLAG_PERMISSION_REVIEW_REQUIRED; 17191 17192 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17193 | FLAG_PERMISSION_POLICY_FIXED; 17194 17195 boolean writeInstallPermissions = false; 17196 boolean writeRuntimePermissions = false; 17197 17198 final int permissionCount = ps.pkg.requestedPermissions.size(); 17199 for (int i = 0; i < permissionCount; i++) { 17200 String permission = ps.pkg.requestedPermissions.get(i); 17201 17202 BasePermission bp = mSettings.mPermissions.get(permission); 17203 if (bp == null) { 17204 continue; 17205 } 17206 17207 // If shared user we just reset the state to which only this app contributed. 17208 if (ps.sharedUser != null) { 17209 boolean used = false; 17210 final int packageCount = ps.sharedUser.packages.size(); 17211 for (int j = 0; j < packageCount; j++) { 17212 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17213 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17214 && pkg.pkg.requestedPermissions.contains(permission)) { 17215 used = true; 17216 break; 17217 } 17218 } 17219 if (used) { 17220 continue; 17221 } 17222 } 17223 17224 PermissionsState permissionsState = ps.getPermissionsState(); 17225 17226 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17227 17228 // Always clear the user settable flags. 17229 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17230 bp.name) != null; 17231 // If permission review is enabled and this is a legacy app, mark the 17232 // permission as requiring a review as this is the initial state. 17233 int flags = 0; 17234 if (mPermissionReviewRequired 17235 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17236 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17237 } 17238 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17239 if (hasInstallState) { 17240 writeInstallPermissions = true; 17241 } else { 17242 writeRuntimePermissions = true; 17243 } 17244 } 17245 17246 // Below is only runtime permission handling. 17247 if (!bp.isRuntime()) { 17248 continue; 17249 } 17250 17251 // Never clobber system or policy. 17252 if ((oldFlags & policyOrSystemFlags) != 0) { 17253 continue; 17254 } 17255 17256 // If this permission was granted by default, make sure it is. 17257 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17258 if (permissionsState.grantRuntimePermission(bp, userId) 17259 != PERMISSION_OPERATION_FAILURE) { 17260 writeRuntimePermissions = true; 17261 } 17262 // If permission review is enabled the permissions for a legacy apps 17263 // are represented as constantly granted runtime ones, so don't revoke. 17264 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17265 // Otherwise, reset the permission. 17266 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17267 switch (revokeResult) { 17268 case PERMISSION_OPERATION_SUCCESS: 17269 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17270 writeRuntimePermissions = true; 17271 final int appId = ps.appId; 17272 mHandler.post(new Runnable() { 17273 @Override 17274 public void run() { 17275 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17276 } 17277 }); 17278 } break; 17279 } 17280 } 17281 } 17282 17283 // Synchronously write as we are taking permissions away. 17284 if (writeRuntimePermissions) { 17285 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17286 } 17287 17288 // Synchronously write as we are taking permissions away. 17289 if (writeInstallPermissions) { 17290 mSettings.writeLPr(); 17291 } 17292 } 17293 17294 /** 17295 * Remove entries from the keystore daemon. Will only remove it if the 17296 * {@code appId} is valid. 17297 */ 17298 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17299 if (appId < 0) { 17300 return; 17301 } 17302 17303 final KeyStore keyStore = KeyStore.getInstance(); 17304 if (keyStore != null) { 17305 if (userId == UserHandle.USER_ALL) { 17306 for (final int individual : sUserManager.getUserIds()) { 17307 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17308 } 17309 } else { 17310 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17311 } 17312 } else { 17313 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17314 } 17315 } 17316 17317 @Override 17318 public void deleteApplicationCacheFiles(final String packageName, 17319 final IPackageDataObserver observer) { 17320 final int userId = UserHandle.getCallingUserId(); 17321 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17322 } 17323 17324 @Override 17325 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17326 final IPackageDataObserver observer) { 17327 mContext.enforceCallingOrSelfPermission( 17328 android.Manifest.permission.DELETE_CACHE_FILES, null); 17329 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17330 /* requireFullPermission= */ true, /* checkShell= */ false, 17331 "delete application cache files"); 17332 17333 final PackageParser.Package pkg; 17334 synchronized (mPackages) { 17335 pkg = mPackages.get(packageName); 17336 } 17337 17338 // Queue up an async operation since the package deletion may take a little while. 17339 mHandler.post(new Runnable() { 17340 public void run() { 17341 synchronized (mInstallLock) { 17342 final int flags = StorageManager.FLAG_STORAGE_DE 17343 | StorageManager.FLAG_STORAGE_CE; 17344 // We're only clearing cache files, so we don't care if the 17345 // app is unfrozen and still able to run 17346 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17347 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17348 } 17349 clearExternalStorageDataSync(packageName, userId, false); 17350 if (observer != null) { 17351 try { 17352 observer.onRemoveCompleted(packageName, true); 17353 } catch (RemoteException e) { 17354 Log.i(TAG, "Observer no longer exists."); 17355 } 17356 } 17357 } 17358 }); 17359 } 17360 17361 @Override 17362 public void getPackageSizeInfo(final String packageName, int userHandle, 17363 final IPackageStatsObserver observer) { 17364 mContext.enforceCallingOrSelfPermission( 17365 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17366 if (packageName == null) { 17367 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17368 } 17369 17370 PackageStats stats = new PackageStats(packageName, userHandle); 17371 17372 /* 17373 * Queue up an async operation since the package measurement may take a 17374 * little while. 17375 */ 17376 Message msg = mHandler.obtainMessage(INIT_COPY); 17377 msg.obj = new MeasureParams(stats, observer); 17378 mHandler.sendMessage(msg); 17379 } 17380 17381 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17382 final PackageSetting ps; 17383 synchronized (mPackages) { 17384 ps = mSettings.mPackages.get(packageName); 17385 if (ps == null) { 17386 Slog.w(TAG, "Failed to find settings for " + packageName); 17387 return false; 17388 } 17389 } 17390 try { 17391 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17392 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17393 ps.getCeDataInode(userId), ps.codePathString, stats); 17394 } catch (InstallerException e) { 17395 Slog.w(TAG, String.valueOf(e)); 17396 return false; 17397 } 17398 17399 // For now, ignore code size of packages on system partition 17400 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17401 stats.codeSize = 0; 17402 } 17403 17404 return true; 17405 } 17406 17407 private int getUidTargetSdkVersionLockedLPr(int uid) { 17408 Object obj = mSettings.getUserIdLPr(uid); 17409 if (obj instanceof SharedUserSetting) { 17410 final SharedUserSetting sus = (SharedUserSetting) obj; 17411 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17412 final Iterator<PackageSetting> it = sus.packages.iterator(); 17413 while (it.hasNext()) { 17414 final PackageSetting ps = it.next(); 17415 if (ps.pkg != null) { 17416 int v = ps.pkg.applicationInfo.targetSdkVersion; 17417 if (v < vers) vers = v; 17418 } 17419 } 17420 return vers; 17421 } else if (obj instanceof PackageSetting) { 17422 final PackageSetting ps = (PackageSetting) obj; 17423 if (ps.pkg != null) { 17424 return ps.pkg.applicationInfo.targetSdkVersion; 17425 } 17426 } 17427 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17428 } 17429 17430 @Override 17431 public void addPreferredActivity(IntentFilter filter, int match, 17432 ComponentName[] set, ComponentName activity, int userId) { 17433 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17434 "Adding preferred"); 17435 } 17436 17437 private void addPreferredActivityInternal(IntentFilter filter, int match, 17438 ComponentName[] set, ComponentName activity, boolean always, int userId, 17439 String opname) { 17440 // writer 17441 int callingUid = Binder.getCallingUid(); 17442 enforceCrossUserPermission(callingUid, userId, 17443 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17444 if (filter.countActions() == 0) { 17445 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17446 return; 17447 } 17448 synchronized (mPackages) { 17449 if (mContext.checkCallingOrSelfPermission( 17450 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17451 != PackageManager.PERMISSION_GRANTED) { 17452 if (getUidTargetSdkVersionLockedLPr(callingUid) 17453 < Build.VERSION_CODES.FROYO) { 17454 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17455 + callingUid); 17456 return; 17457 } 17458 mContext.enforceCallingOrSelfPermission( 17459 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17460 } 17461 17462 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17463 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17464 + userId + ":"); 17465 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17466 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17467 scheduleWritePackageRestrictionsLocked(userId); 17468 postPreferredActivityChangedBroadcast(userId); 17469 } 17470 } 17471 17472 private void postPreferredActivityChangedBroadcast(int userId) { 17473 mHandler.post(() -> { 17474 final IActivityManager am = ActivityManager.getService(); 17475 if (am == null) { 17476 return; 17477 } 17478 17479 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17480 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17481 try { 17482 am.broadcastIntent(null, intent, null, null, 17483 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17484 null, false, false, userId); 17485 } catch (RemoteException e) { 17486 } 17487 }); 17488 } 17489 17490 @Override 17491 public void replacePreferredActivity(IntentFilter filter, int match, 17492 ComponentName[] set, ComponentName activity, int userId) { 17493 if (filter.countActions() != 1) { 17494 throw new IllegalArgumentException( 17495 "replacePreferredActivity expects filter to have only 1 action."); 17496 } 17497 if (filter.countDataAuthorities() != 0 17498 || filter.countDataPaths() != 0 17499 || filter.countDataSchemes() > 1 17500 || filter.countDataTypes() != 0) { 17501 throw new IllegalArgumentException( 17502 "replacePreferredActivity expects filter to have no data authorities, " + 17503 "paths, or types; and at most one scheme."); 17504 } 17505 17506 final int callingUid = Binder.getCallingUid(); 17507 enforceCrossUserPermission(callingUid, userId, 17508 true /* requireFullPermission */, false /* checkShell */, 17509 "replace preferred activity"); 17510 synchronized (mPackages) { 17511 if (mContext.checkCallingOrSelfPermission( 17512 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17513 != PackageManager.PERMISSION_GRANTED) { 17514 if (getUidTargetSdkVersionLockedLPr(callingUid) 17515 < Build.VERSION_CODES.FROYO) { 17516 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17517 + Binder.getCallingUid()); 17518 return; 17519 } 17520 mContext.enforceCallingOrSelfPermission( 17521 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17522 } 17523 17524 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17525 if (pir != null) { 17526 // Get all of the existing entries that exactly match this filter. 17527 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17528 if (existing != null && existing.size() == 1) { 17529 PreferredActivity cur = existing.get(0); 17530 if (DEBUG_PREFERRED) { 17531 Slog.i(TAG, "Checking replace of preferred:"); 17532 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17533 if (!cur.mPref.mAlways) { 17534 Slog.i(TAG, " -- CUR; not mAlways!"); 17535 } else { 17536 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17537 Slog.i(TAG, " -- CUR: mSet=" 17538 + Arrays.toString(cur.mPref.mSetComponents)); 17539 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17540 Slog.i(TAG, " -- NEW: mMatch=" 17541 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17542 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17543 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17544 } 17545 } 17546 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17547 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17548 && cur.mPref.sameSet(set)) { 17549 // Setting the preferred activity to what it happens to be already 17550 if (DEBUG_PREFERRED) { 17551 Slog.i(TAG, "Replacing with same preferred activity " 17552 + cur.mPref.mShortComponent + " for user " 17553 + userId + ":"); 17554 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17555 } 17556 return; 17557 } 17558 } 17559 17560 if (existing != null) { 17561 if (DEBUG_PREFERRED) { 17562 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17563 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17564 } 17565 for (int i = 0; i < existing.size(); i++) { 17566 PreferredActivity pa = existing.get(i); 17567 if (DEBUG_PREFERRED) { 17568 Slog.i(TAG, "Removing existing preferred activity " 17569 + pa.mPref.mComponent + ":"); 17570 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17571 } 17572 pir.removeFilter(pa); 17573 } 17574 } 17575 } 17576 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17577 "Replacing preferred"); 17578 } 17579 } 17580 17581 @Override 17582 public void clearPackagePreferredActivities(String packageName) { 17583 final int uid = Binder.getCallingUid(); 17584 // writer 17585 synchronized (mPackages) { 17586 PackageParser.Package pkg = mPackages.get(packageName); 17587 if (pkg == null || pkg.applicationInfo.uid != uid) { 17588 if (mContext.checkCallingOrSelfPermission( 17589 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17590 != PackageManager.PERMISSION_GRANTED) { 17591 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17592 < Build.VERSION_CODES.FROYO) { 17593 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17594 + Binder.getCallingUid()); 17595 return; 17596 } 17597 mContext.enforceCallingOrSelfPermission( 17598 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17599 } 17600 } 17601 17602 int user = UserHandle.getCallingUserId(); 17603 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17604 scheduleWritePackageRestrictionsLocked(user); 17605 } 17606 } 17607 } 17608 17609 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17610 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17611 ArrayList<PreferredActivity> removed = null; 17612 boolean changed = false; 17613 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17614 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17615 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17616 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17617 continue; 17618 } 17619 Iterator<PreferredActivity> it = pir.filterIterator(); 17620 while (it.hasNext()) { 17621 PreferredActivity pa = it.next(); 17622 // Mark entry for removal only if it matches the package name 17623 // and the entry is of type "always". 17624 if (packageName == null || 17625 (pa.mPref.mComponent.getPackageName().equals(packageName) 17626 && pa.mPref.mAlways)) { 17627 if (removed == null) { 17628 removed = new ArrayList<PreferredActivity>(); 17629 } 17630 removed.add(pa); 17631 } 17632 } 17633 if (removed != null) { 17634 for (int j=0; j<removed.size(); j++) { 17635 PreferredActivity pa = removed.get(j); 17636 pir.removeFilter(pa); 17637 } 17638 changed = true; 17639 } 17640 } 17641 if (changed) { 17642 postPreferredActivityChangedBroadcast(userId); 17643 } 17644 return changed; 17645 } 17646 17647 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17648 private void clearIntentFilterVerificationsLPw(int userId) { 17649 final int packageCount = mPackages.size(); 17650 for (int i = 0; i < packageCount; i++) { 17651 PackageParser.Package pkg = mPackages.valueAt(i); 17652 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17653 } 17654 } 17655 17656 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17657 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17658 if (userId == UserHandle.USER_ALL) { 17659 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17660 sUserManager.getUserIds())) { 17661 for (int oneUserId : sUserManager.getUserIds()) { 17662 scheduleWritePackageRestrictionsLocked(oneUserId); 17663 } 17664 } 17665 } else { 17666 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17667 scheduleWritePackageRestrictionsLocked(userId); 17668 } 17669 } 17670 } 17671 17672 void clearDefaultBrowserIfNeeded(String packageName) { 17673 for (int oneUserId : sUserManager.getUserIds()) { 17674 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17675 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17676 if (packageName.equals(defaultBrowserPackageName)) { 17677 setDefaultBrowserPackageName(null, oneUserId); 17678 } 17679 } 17680 } 17681 17682 @Override 17683 public void resetApplicationPreferences(int userId) { 17684 mContext.enforceCallingOrSelfPermission( 17685 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17686 final long identity = Binder.clearCallingIdentity(); 17687 // writer 17688 try { 17689 synchronized (mPackages) { 17690 clearPackagePreferredActivitiesLPw(null, userId); 17691 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17692 // TODO: We have to reset the default SMS and Phone. This requires 17693 // significant refactoring to keep all default apps in the package 17694 // manager (cleaner but more work) or have the services provide 17695 // callbacks to the package manager to request a default app reset. 17696 applyFactoryDefaultBrowserLPw(userId); 17697 clearIntentFilterVerificationsLPw(userId); 17698 primeDomainVerificationsLPw(userId); 17699 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17700 scheduleWritePackageRestrictionsLocked(userId); 17701 } 17702 resetNetworkPolicies(userId); 17703 } finally { 17704 Binder.restoreCallingIdentity(identity); 17705 } 17706 } 17707 17708 @Override 17709 public int getPreferredActivities(List<IntentFilter> outFilters, 17710 List<ComponentName> outActivities, String packageName) { 17711 17712 int num = 0; 17713 final int userId = UserHandle.getCallingUserId(); 17714 // reader 17715 synchronized (mPackages) { 17716 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17717 if (pir != null) { 17718 final Iterator<PreferredActivity> it = pir.filterIterator(); 17719 while (it.hasNext()) { 17720 final PreferredActivity pa = it.next(); 17721 if (packageName == null 17722 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17723 && pa.mPref.mAlways)) { 17724 if (outFilters != null) { 17725 outFilters.add(new IntentFilter(pa)); 17726 } 17727 if (outActivities != null) { 17728 outActivities.add(pa.mPref.mComponent); 17729 } 17730 } 17731 } 17732 } 17733 } 17734 17735 return num; 17736 } 17737 17738 @Override 17739 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17740 int userId) { 17741 int callingUid = Binder.getCallingUid(); 17742 if (callingUid != Process.SYSTEM_UID) { 17743 throw new SecurityException( 17744 "addPersistentPreferredActivity can only be run by the system"); 17745 } 17746 if (filter.countActions() == 0) { 17747 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17748 return; 17749 } 17750 synchronized (mPackages) { 17751 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17752 ":"); 17753 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17754 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17755 new PersistentPreferredActivity(filter, activity)); 17756 scheduleWritePackageRestrictionsLocked(userId); 17757 postPreferredActivityChangedBroadcast(userId); 17758 } 17759 } 17760 17761 @Override 17762 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17763 int callingUid = Binder.getCallingUid(); 17764 if (callingUid != Process.SYSTEM_UID) { 17765 throw new SecurityException( 17766 "clearPackagePersistentPreferredActivities can only be run by the system"); 17767 } 17768 ArrayList<PersistentPreferredActivity> removed = null; 17769 boolean changed = false; 17770 synchronized (mPackages) { 17771 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17772 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17773 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17774 .valueAt(i); 17775 if (userId != thisUserId) { 17776 continue; 17777 } 17778 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17779 while (it.hasNext()) { 17780 PersistentPreferredActivity ppa = it.next(); 17781 // Mark entry for removal only if it matches the package name. 17782 if (ppa.mComponent.getPackageName().equals(packageName)) { 17783 if (removed == null) { 17784 removed = new ArrayList<PersistentPreferredActivity>(); 17785 } 17786 removed.add(ppa); 17787 } 17788 } 17789 if (removed != null) { 17790 for (int j=0; j<removed.size(); j++) { 17791 PersistentPreferredActivity ppa = removed.get(j); 17792 ppir.removeFilter(ppa); 17793 } 17794 changed = true; 17795 } 17796 } 17797 17798 if (changed) { 17799 scheduleWritePackageRestrictionsLocked(userId); 17800 postPreferredActivityChangedBroadcast(userId); 17801 } 17802 } 17803 } 17804 17805 /** 17806 * Common machinery for picking apart a restored XML blob and passing 17807 * it to a caller-supplied functor to be applied to the running system. 17808 */ 17809 private void restoreFromXml(XmlPullParser parser, int userId, 17810 String expectedStartTag, BlobXmlRestorer functor) 17811 throws IOException, XmlPullParserException { 17812 int type; 17813 while ((type = parser.next()) != XmlPullParser.START_TAG 17814 && type != XmlPullParser.END_DOCUMENT) { 17815 } 17816 if (type != XmlPullParser.START_TAG) { 17817 // oops didn't find a start tag?! 17818 if (DEBUG_BACKUP) { 17819 Slog.e(TAG, "Didn't find start tag during restore"); 17820 } 17821 return; 17822 } 17823Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17824 // this is supposed to be TAG_PREFERRED_BACKUP 17825 if (!expectedStartTag.equals(parser.getName())) { 17826 if (DEBUG_BACKUP) { 17827 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17828 } 17829 return; 17830 } 17831 17832 // skip interfering stuff, then we're aligned with the backing implementation 17833 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17834Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17835 functor.apply(parser, userId); 17836 } 17837 17838 private interface BlobXmlRestorer { 17839 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17840 } 17841 17842 /** 17843 * Non-Binder method, support for the backup/restore mechanism: write the 17844 * full set of preferred activities in its canonical XML format. Returns the 17845 * XML output as a byte array, or null if there is none. 17846 */ 17847 @Override 17848 public byte[] getPreferredActivityBackup(int userId) { 17849 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17850 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17851 } 17852 17853 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17854 try { 17855 final XmlSerializer serializer = new FastXmlSerializer(); 17856 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17857 serializer.startDocument(null, true); 17858 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17859 17860 synchronized (mPackages) { 17861 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17862 } 17863 17864 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17865 serializer.endDocument(); 17866 serializer.flush(); 17867 } catch (Exception e) { 17868 if (DEBUG_BACKUP) { 17869 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17870 } 17871 return null; 17872 } 17873 17874 return dataStream.toByteArray(); 17875 } 17876 17877 @Override 17878 public void restorePreferredActivities(byte[] backup, int userId) { 17879 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17880 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17881 } 17882 17883 try { 17884 final XmlPullParser parser = Xml.newPullParser(); 17885 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17886 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17887 new BlobXmlRestorer() { 17888 @Override 17889 public void apply(XmlPullParser parser, int userId) 17890 throws XmlPullParserException, IOException { 17891 synchronized (mPackages) { 17892 mSettings.readPreferredActivitiesLPw(parser, userId); 17893 } 17894 } 17895 } ); 17896 } catch (Exception e) { 17897 if (DEBUG_BACKUP) { 17898 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17899 } 17900 } 17901 } 17902 17903 /** 17904 * Non-Binder method, support for the backup/restore mechanism: write the 17905 * default browser (etc) settings in its canonical XML format. Returns the default 17906 * browser XML representation as a byte array, or null if there is none. 17907 */ 17908 @Override 17909 public byte[] getDefaultAppsBackup(int userId) { 17910 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17911 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17912 } 17913 17914 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17915 try { 17916 final XmlSerializer serializer = new FastXmlSerializer(); 17917 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17918 serializer.startDocument(null, true); 17919 serializer.startTag(null, TAG_DEFAULT_APPS); 17920 17921 synchronized (mPackages) { 17922 mSettings.writeDefaultAppsLPr(serializer, userId); 17923 } 17924 17925 serializer.endTag(null, TAG_DEFAULT_APPS); 17926 serializer.endDocument(); 17927 serializer.flush(); 17928 } catch (Exception e) { 17929 if (DEBUG_BACKUP) { 17930 Slog.e(TAG, "Unable to write default apps for backup", e); 17931 } 17932 return null; 17933 } 17934 17935 return dataStream.toByteArray(); 17936 } 17937 17938 @Override 17939 public void restoreDefaultApps(byte[] backup, int userId) { 17940 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17941 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17942 } 17943 17944 try { 17945 final XmlPullParser parser = Xml.newPullParser(); 17946 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17947 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17948 new BlobXmlRestorer() { 17949 @Override 17950 public void apply(XmlPullParser parser, int userId) 17951 throws XmlPullParserException, IOException { 17952 synchronized (mPackages) { 17953 mSettings.readDefaultAppsLPw(parser, userId); 17954 } 17955 } 17956 } ); 17957 } catch (Exception e) { 17958 if (DEBUG_BACKUP) { 17959 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17960 } 17961 } 17962 } 17963 17964 @Override 17965 public byte[] getIntentFilterVerificationBackup(int userId) { 17966 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17967 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17968 } 17969 17970 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17971 try { 17972 final XmlSerializer serializer = new FastXmlSerializer(); 17973 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17974 serializer.startDocument(null, true); 17975 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17976 17977 synchronized (mPackages) { 17978 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17979 } 17980 17981 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17982 serializer.endDocument(); 17983 serializer.flush(); 17984 } catch (Exception e) { 17985 if (DEBUG_BACKUP) { 17986 Slog.e(TAG, "Unable to write default apps for backup", e); 17987 } 17988 return null; 17989 } 17990 17991 return dataStream.toByteArray(); 17992 } 17993 17994 @Override 17995 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17996 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17997 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17998 } 17999 18000 try { 18001 final XmlPullParser parser = Xml.newPullParser(); 18002 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18003 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 18004 new BlobXmlRestorer() { 18005 @Override 18006 public void apply(XmlPullParser parser, int userId) 18007 throws XmlPullParserException, IOException { 18008 synchronized (mPackages) { 18009 mSettings.readAllDomainVerificationsLPr(parser, userId); 18010 mSettings.writeLPr(); 18011 } 18012 } 18013 } ); 18014 } catch (Exception e) { 18015 if (DEBUG_BACKUP) { 18016 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18017 } 18018 } 18019 } 18020 18021 @Override 18022 public byte[] getPermissionGrantBackup(int userId) { 18023 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18024 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 18025 } 18026 18027 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18028 try { 18029 final XmlSerializer serializer = new FastXmlSerializer(); 18030 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18031 serializer.startDocument(null, true); 18032 serializer.startTag(null, TAG_PERMISSION_BACKUP); 18033 18034 synchronized (mPackages) { 18035 serializeRuntimePermissionGrantsLPr(serializer, userId); 18036 } 18037 18038 serializer.endTag(null, TAG_PERMISSION_BACKUP); 18039 serializer.endDocument(); 18040 serializer.flush(); 18041 } catch (Exception e) { 18042 if (DEBUG_BACKUP) { 18043 Slog.e(TAG, "Unable to write default apps for backup", e); 18044 } 18045 return null; 18046 } 18047 18048 return dataStream.toByteArray(); 18049 } 18050 18051 @Override 18052 public void restorePermissionGrants(byte[] backup, int userId) { 18053 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18054 throw new SecurityException("Only the system may call restorePermissionGrants()"); 18055 } 18056 18057 try { 18058 final XmlPullParser parser = Xml.newPullParser(); 18059 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18060 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 18061 new BlobXmlRestorer() { 18062 @Override 18063 public void apply(XmlPullParser parser, int userId) 18064 throws XmlPullParserException, IOException { 18065 synchronized (mPackages) { 18066 processRestoredPermissionGrantsLPr(parser, userId); 18067 } 18068 } 18069 } ); 18070 } catch (Exception e) { 18071 if (DEBUG_BACKUP) { 18072 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18073 } 18074 } 18075 } 18076 18077 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 18078 throws IOException { 18079 serializer.startTag(null, TAG_ALL_GRANTS); 18080 18081 final int N = mSettings.mPackages.size(); 18082 for (int i = 0; i < N; i++) { 18083 final PackageSetting ps = mSettings.mPackages.valueAt(i); 18084 boolean pkgGrantsKnown = false; 18085 18086 PermissionsState packagePerms = ps.getPermissionsState(); 18087 18088 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 18089 final int grantFlags = state.getFlags(); 18090 // only look at grants that are not system/policy fixed 18091 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 18092 final boolean isGranted = state.isGranted(); 18093 // And only back up the user-twiddled state bits 18094 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 18095 final String packageName = mSettings.mPackages.keyAt(i); 18096 if (!pkgGrantsKnown) { 18097 serializer.startTag(null, TAG_GRANT); 18098 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 18099 pkgGrantsKnown = true; 18100 } 18101 18102 final boolean userSet = 18103 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 18104 final boolean userFixed = 18105 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 18106 final boolean revoke = 18107 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 18108 18109 serializer.startTag(null, TAG_PERMISSION); 18110 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 18111 if (isGranted) { 18112 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 18113 } 18114 if (userSet) { 18115 serializer.attribute(null, ATTR_USER_SET, "true"); 18116 } 18117 if (userFixed) { 18118 serializer.attribute(null, ATTR_USER_FIXED, "true"); 18119 } 18120 if (revoke) { 18121 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 18122 } 18123 serializer.endTag(null, TAG_PERMISSION); 18124 } 18125 } 18126 } 18127 18128 if (pkgGrantsKnown) { 18129 serializer.endTag(null, TAG_GRANT); 18130 } 18131 } 18132 18133 serializer.endTag(null, TAG_ALL_GRANTS); 18134 } 18135 18136 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 18137 throws XmlPullParserException, IOException { 18138 String pkgName = null; 18139 int outerDepth = parser.getDepth(); 18140 int type; 18141 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 18142 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 18143 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18144 continue; 18145 } 18146 18147 final String tagName = parser.getName(); 18148 if (tagName.equals(TAG_GRANT)) { 18149 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18150 if (DEBUG_BACKUP) { 18151 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18152 } 18153 } else if (tagName.equals(TAG_PERMISSION)) { 18154 18155 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18156 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18157 18158 int newFlagSet = 0; 18159 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18160 newFlagSet |= FLAG_PERMISSION_USER_SET; 18161 } 18162 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18163 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18164 } 18165 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18166 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18167 } 18168 if (DEBUG_BACKUP) { 18169 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18170 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18171 } 18172 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18173 if (ps != null) { 18174 // Already installed so we apply the grant immediately 18175 if (DEBUG_BACKUP) { 18176 Slog.v(TAG, " + already installed; applying"); 18177 } 18178 PermissionsState perms = ps.getPermissionsState(); 18179 BasePermission bp = mSettings.mPermissions.get(permName); 18180 if (bp != null) { 18181 if (isGranted) { 18182 perms.grantRuntimePermission(bp, userId); 18183 } 18184 if (newFlagSet != 0) { 18185 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18186 } 18187 } 18188 } else { 18189 // Need to wait for post-restore install to apply the grant 18190 if (DEBUG_BACKUP) { 18191 Slog.v(TAG, " - not yet installed; saving for later"); 18192 } 18193 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18194 isGranted, newFlagSet, userId); 18195 } 18196 } else { 18197 PackageManagerService.reportSettingsProblem(Log.WARN, 18198 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18199 XmlUtils.skipCurrentTag(parser); 18200 } 18201 } 18202 18203 scheduleWriteSettingsLocked(); 18204 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18205 } 18206 18207 @Override 18208 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18209 int sourceUserId, int targetUserId, int flags) { 18210 mContext.enforceCallingOrSelfPermission( 18211 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18212 int callingUid = Binder.getCallingUid(); 18213 enforceOwnerRights(ownerPackage, callingUid); 18214 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18215 if (intentFilter.countActions() == 0) { 18216 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18217 return; 18218 } 18219 synchronized (mPackages) { 18220 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18221 ownerPackage, targetUserId, flags); 18222 CrossProfileIntentResolver resolver = 18223 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18224 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18225 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18226 if (existing != null) { 18227 int size = existing.size(); 18228 for (int i = 0; i < size; i++) { 18229 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18230 return; 18231 } 18232 } 18233 } 18234 resolver.addFilter(newFilter); 18235 scheduleWritePackageRestrictionsLocked(sourceUserId); 18236 } 18237 } 18238 18239 @Override 18240 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18241 mContext.enforceCallingOrSelfPermission( 18242 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18243 int callingUid = Binder.getCallingUid(); 18244 enforceOwnerRights(ownerPackage, callingUid); 18245 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18246 synchronized (mPackages) { 18247 CrossProfileIntentResolver resolver = 18248 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18249 ArraySet<CrossProfileIntentFilter> set = 18250 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18251 for (CrossProfileIntentFilter filter : set) { 18252 if (filter.getOwnerPackage().equals(ownerPackage)) { 18253 resolver.removeFilter(filter); 18254 } 18255 } 18256 scheduleWritePackageRestrictionsLocked(sourceUserId); 18257 } 18258 } 18259 18260 // Enforcing that callingUid is owning pkg on userId 18261 private void enforceOwnerRights(String pkg, int callingUid) { 18262 // The system owns everything. 18263 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18264 return; 18265 } 18266 int callingUserId = UserHandle.getUserId(callingUid); 18267 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18268 if (pi == null) { 18269 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18270 + callingUserId); 18271 } 18272 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18273 throw new SecurityException("Calling uid " + callingUid 18274 + " does not own package " + pkg); 18275 } 18276 } 18277 18278 @Override 18279 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18280 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18281 } 18282 18283 private Intent getHomeIntent() { 18284 Intent intent = new Intent(Intent.ACTION_MAIN); 18285 intent.addCategory(Intent.CATEGORY_HOME); 18286 intent.addCategory(Intent.CATEGORY_DEFAULT); 18287 return intent; 18288 } 18289 18290 private IntentFilter getHomeFilter() { 18291 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18292 filter.addCategory(Intent.CATEGORY_HOME); 18293 filter.addCategory(Intent.CATEGORY_DEFAULT); 18294 return filter; 18295 } 18296 18297 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18298 int userId) { 18299 Intent intent = getHomeIntent(); 18300 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18301 PackageManager.GET_META_DATA, userId); 18302 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18303 true, false, false, userId); 18304 18305 allHomeCandidates.clear(); 18306 if (list != null) { 18307 for (ResolveInfo ri : list) { 18308 allHomeCandidates.add(ri); 18309 } 18310 } 18311 return (preferred == null || preferred.activityInfo == null) 18312 ? null 18313 : new ComponentName(preferred.activityInfo.packageName, 18314 preferred.activityInfo.name); 18315 } 18316 18317 @Override 18318 public void setHomeActivity(ComponentName comp, int userId) { 18319 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18320 getHomeActivitiesAsUser(homeActivities, userId); 18321 18322 boolean found = false; 18323 18324 final int size = homeActivities.size(); 18325 final ComponentName[] set = new ComponentName[size]; 18326 for (int i = 0; i < size; i++) { 18327 final ResolveInfo candidate = homeActivities.get(i); 18328 final ActivityInfo info = candidate.activityInfo; 18329 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18330 set[i] = activityName; 18331 if (!found && activityName.equals(comp)) { 18332 found = true; 18333 } 18334 } 18335 if (!found) { 18336 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18337 + userId); 18338 } 18339 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18340 set, comp, userId); 18341 } 18342 18343 private @Nullable String getSetupWizardPackageName() { 18344 final Intent intent = new Intent(Intent.ACTION_MAIN); 18345 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18346 18347 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18348 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18349 | MATCH_DISABLED_COMPONENTS, 18350 UserHandle.myUserId()); 18351 if (matches.size() == 1) { 18352 return matches.get(0).getComponentInfo().packageName; 18353 } else { 18354 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18355 + ": matches=" + matches); 18356 return null; 18357 } 18358 } 18359 18360 private @Nullable String getStorageManagerPackageName() { 18361 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18362 18363 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18364 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18365 | MATCH_DISABLED_COMPONENTS, 18366 UserHandle.myUserId()); 18367 if (matches.size() == 1) { 18368 return matches.get(0).getComponentInfo().packageName; 18369 } else { 18370 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18371 + matches.size() + ": matches=" + matches); 18372 return null; 18373 } 18374 } 18375 18376 @Override 18377 public void setApplicationEnabledSetting(String appPackageName, 18378 int newState, int flags, int userId, String callingPackage) { 18379 if (!sUserManager.exists(userId)) return; 18380 if (callingPackage == null) { 18381 callingPackage = Integer.toString(Binder.getCallingUid()); 18382 } 18383 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18384 } 18385 18386 @Override 18387 public void setComponentEnabledSetting(ComponentName componentName, 18388 int newState, int flags, int userId) { 18389 if (!sUserManager.exists(userId)) return; 18390 setEnabledSetting(componentName.getPackageName(), 18391 componentName.getClassName(), newState, flags, userId, null); 18392 } 18393 18394 private void setEnabledSetting(final String packageName, String className, int newState, 18395 final int flags, int userId, String callingPackage) { 18396 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18397 || newState == COMPONENT_ENABLED_STATE_ENABLED 18398 || newState == COMPONENT_ENABLED_STATE_DISABLED 18399 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18400 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18401 throw new IllegalArgumentException("Invalid new component state: " 18402 + newState); 18403 } 18404 PackageSetting pkgSetting; 18405 final int uid = Binder.getCallingUid(); 18406 final int permission; 18407 if (uid == Process.SYSTEM_UID) { 18408 permission = PackageManager.PERMISSION_GRANTED; 18409 } else { 18410 permission = mContext.checkCallingOrSelfPermission( 18411 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18412 } 18413 enforceCrossUserPermission(uid, userId, 18414 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18415 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18416 boolean sendNow = false; 18417 boolean isApp = (className == null); 18418 String componentName = isApp ? packageName : className; 18419 int packageUid = -1; 18420 ArrayList<String> components; 18421 18422 // writer 18423 synchronized (mPackages) { 18424 pkgSetting = mSettings.mPackages.get(packageName); 18425 if (pkgSetting == null) { 18426 if (className == null) { 18427 throw new IllegalArgumentException("Unknown package: " + packageName); 18428 } 18429 throw new IllegalArgumentException( 18430 "Unknown component: " + packageName + "/" + className); 18431 } 18432 } 18433 18434 // Limit who can change which apps 18435 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18436 // Don't allow apps that don't have permission to modify other apps 18437 if (!allowedByPermission) { 18438 throw new SecurityException( 18439 "Permission Denial: attempt to change component state from pid=" 18440 + Binder.getCallingPid() 18441 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18442 } 18443 // Don't allow changing protected packages. 18444 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18445 throw new SecurityException("Cannot disable a protected package: " + packageName); 18446 } 18447 } 18448 18449 synchronized (mPackages) { 18450 if (uid == Process.SHELL_UID 18451 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18452 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18453 // unless it is a test package. 18454 int oldState = pkgSetting.getEnabled(userId); 18455 if (className == null 18456 && 18457 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18458 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18459 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18460 && 18461 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18462 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18463 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18464 // ok 18465 } else { 18466 throw new SecurityException( 18467 "Shell cannot change component state for " + packageName + "/" 18468 + className + " to " + newState); 18469 } 18470 } 18471 if (className == null) { 18472 // We're dealing with an application/package level state change 18473 if (pkgSetting.getEnabled(userId) == newState) { 18474 // Nothing to do 18475 return; 18476 } 18477 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18478 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18479 // Don't care about who enables an app. 18480 callingPackage = null; 18481 } 18482 pkgSetting.setEnabled(newState, userId, callingPackage); 18483 // pkgSetting.pkg.mSetEnabled = newState; 18484 } else { 18485 // We're dealing with a component level state change 18486 // First, verify that this is a valid class name. 18487 PackageParser.Package pkg = pkgSetting.pkg; 18488 if (pkg == null || !pkg.hasComponentClassName(className)) { 18489 if (pkg != null && 18490 pkg.applicationInfo.targetSdkVersion >= 18491 Build.VERSION_CODES.JELLY_BEAN) { 18492 throw new IllegalArgumentException("Component class " + className 18493 + " does not exist in " + packageName); 18494 } else { 18495 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18496 + className + " does not exist in " + packageName); 18497 } 18498 } 18499 switch (newState) { 18500 case COMPONENT_ENABLED_STATE_ENABLED: 18501 if (!pkgSetting.enableComponentLPw(className, userId)) { 18502 return; 18503 } 18504 break; 18505 case COMPONENT_ENABLED_STATE_DISABLED: 18506 if (!pkgSetting.disableComponentLPw(className, userId)) { 18507 return; 18508 } 18509 break; 18510 case COMPONENT_ENABLED_STATE_DEFAULT: 18511 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18512 return; 18513 } 18514 break; 18515 default: 18516 Slog.e(TAG, "Invalid new component state: " + newState); 18517 return; 18518 } 18519 } 18520 scheduleWritePackageRestrictionsLocked(userId); 18521 components = mPendingBroadcasts.get(userId, packageName); 18522 final boolean newPackage = components == null; 18523 if (newPackage) { 18524 components = new ArrayList<String>(); 18525 } 18526 if (!components.contains(componentName)) { 18527 components.add(componentName); 18528 } 18529 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18530 sendNow = true; 18531 // Purge entry from pending broadcast list if another one exists already 18532 // since we are sending one right away. 18533 mPendingBroadcasts.remove(userId, packageName); 18534 } else { 18535 if (newPackage) { 18536 mPendingBroadcasts.put(userId, packageName, components); 18537 } 18538 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18539 // Schedule a message 18540 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18541 } 18542 } 18543 } 18544 18545 long callingId = Binder.clearCallingIdentity(); 18546 try { 18547 if (sendNow) { 18548 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18549 sendPackageChangedBroadcast(packageName, 18550 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18551 } 18552 } finally { 18553 Binder.restoreCallingIdentity(callingId); 18554 } 18555 } 18556 18557 @Override 18558 public void flushPackageRestrictionsAsUser(int userId) { 18559 if (!sUserManager.exists(userId)) { 18560 return; 18561 } 18562 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18563 false /* checkShell */, "flushPackageRestrictions"); 18564 synchronized (mPackages) { 18565 mSettings.writePackageRestrictionsLPr(userId); 18566 mDirtyUsers.remove(userId); 18567 if (mDirtyUsers.isEmpty()) { 18568 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18569 } 18570 } 18571 } 18572 18573 private void sendPackageChangedBroadcast(String packageName, 18574 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18575 if (DEBUG_INSTALL) 18576 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18577 + componentNames); 18578 Bundle extras = new Bundle(4); 18579 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18580 String nameList[] = new String[componentNames.size()]; 18581 componentNames.toArray(nameList); 18582 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18583 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18584 extras.putInt(Intent.EXTRA_UID, packageUid); 18585 // If this is not reporting a change of the overall package, then only send it 18586 // to registered receivers. We don't want to launch a swath of apps for every 18587 // little component state change. 18588 final int flags = !componentNames.contains(packageName) 18589 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18590 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18591 new int[] {UserHandle.getUserId(packageUid)}); 18592 } 18593 18594 @Override 18595 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18596 if (!sUserManager.exists(userId)) return; 18597 final int uid = Binder.getCallingUid(); 18598 final int permission = mContext.checkCallingOrSelfPermission( 18599 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18600 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18601 enforceCrossUserPermission(uid, userId, 18602 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18603 // writer 18604 synchronized (mPackages) { 18605 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18606 allowedByPermission, uid, userId)) { 18607 scheduleWritePackageRestrictionsLocked(userId); 18608 } 18609 } 18610 } 18611 18612 @Override 18613 public String getInstallerPackageName(String packageName) { 18614 // reader 18615 synchronized (mPackages) { 18616 return mSettings.getInstallerPackageNameLPr(packageName); 18617 } 18618 } 18619 18620 public boolean isOrphaned(String packageName) { 18621 // reader 18622 synchronized (mPackages) { 18623 return mSettings.isOrphaned(packageName); 18624 } 18625 } 18626 18627 @Override 18628 public int getApplicationEnabledSetting(String packageName, int userId) { 18629 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18630 int uid = Binder.getCallingUid(); 18631 enforceCrossUserPermission(uid, userId, 18632 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18633 // reader 18634 synchronized (mPackages) { 18635 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18636 } 18637 } 18638 18639 @Override 18640 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18641 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18642 int uid = Binder.getCallingUid(); 18643 enforceCrossUserPermission(uid, userId, 18644 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18645 // reader 18646 synchronized (mPackages) { 18647 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18648 } 18649 } 18650 18651 @Override 18652 public void enterSafeMode() { 18653 enforceSystemOrRoot("Only the system can request entering safe mode"); 18654 18655 if (!mSystemReady) { 18656 mSafeMode = true; 18657 } 18658 } 18659 18660 @Override 18661 public void systemReady() { 18662 mSystemReady = true; 18663 18664 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18665 // disabled after already being started. 18666 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18667 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18668 18669 // Read the compatibilty setting when the system is ready. 18670 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18671 mContext.getContentResolver(), 18672 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18673 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18674 if (DEBUG_SETTINGS) { 18675 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18676 } 18677 18678 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18679 18680 synchronized (mPackages) { 18681 // Verify that all of the preferred activity components actually 18682 // exist. It is possible for applications to be updated and at 18683 // that point remove a previously declared activity component that 18684 // had been set as a preferred activity. We try to clean this up 18685 // the next time we encounter that preferred activity, but it is 18686 // possible for the user flow to never be able to return to that 18687 // situation so here we do a sanity check to make sure we haven't 18688 // left any junk around. 18689 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18690 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18691 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18692 removed.clear(); 18693 for (PreferredActivity pa : pir.filterSet()) { 18694 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18695 removed.add(pa); 18696 } 18697 } 18698 if (removed.size() > 0) { 18699 for (int r=0; r<removed.size(); r++) { 18700 PreferredActivity pa = removed.get(r); 18701 Slog.w(TAG, "Removing dangling preferred activity: " 18702 + pa.mPref.mComponent); 18703 pir.removeFilter(pa); 18704 } 18705 mSettings.writePackageRestrictionsLPr( 18706 mSettings.mPreferredActivities.keyAt(i)); 18707 } 18708 } 18709 18710 for (int userId : UserManagerService.getInstance().getUserIds()) { 18711 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18712 grantPermissionsUserIds = ArrayUtils.appendInt( 18713 grantPermissionsUserIds, userId); 18714 } 18715 } 18716 } 18717 sUserManager.systemReady(); 18718 18719 // If we upgraded grant all default permissions before kicking off. 18720 for (int userId : grantPermissionsUserIds) { 18721 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18722 } 18723 18724 // If we did not grant default permissions, we preload from this the 18725 // default permission exceptions lazily to ensure we don't hit the 18726 // disk on a new user creation. 18727 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18728 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18729 } 18730 18731 // Kick off any messages waiting for system ready 18732 if (mPostSystemReadyMessages != null) { 18733 for (Message msg : mPostSystemReadyMessages) { 18734 msg.sendToTarget(); 18735 } 18736 mPostSystemReadyMessages = null; 18737 } 18738 18739 // Watch for external volumes that come and go over time 18740 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18741 storage.registerListener(mStorageListener); 18742 18743 mInstallerService.systemReady(); 18744 mPackageDexOptimizer.systemReady(); 18745 18746 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18747 StorageManagerInternal.class); 18748 StorageManagerInternal.addExternalStoragePolicy( 18749 new StorageManagerInternal.ExternalStorageMountPolicy() { 18750 @Override 18751 public int getMountMode(int uid, String packageName) { 18752 if (Process.isIsolated(uid)) { 18753 return Zygote.MOUNT_EXTERNAL_NONE; 18754 } 18755 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18756 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18757 } 18758 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18759 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18760 } 18761 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18762 return Zygote.MOUNT_EXTERNAL_READ; 18763 } 18764 return Zygote.MOUNT_EXTERNAL_WRITE; 18765 } 18766 18767 @Override 18768 public boolean hasExternalStorage(int uid, String packageName) { 18769 return true; 18770 } 18771 }); 18772 18773 // Now that we're mostly running, clean up stale users and apps 18774 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18775 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18776 } 18777 18778 @Override 18779 public boolean isSafeMode() { 18780 return mSafeMode; 18781 } 18782 18783 @Override 18784 public boolean hasSystemUidErrors() { 18785 return mHasSystemUidErrors; 18786 } 18787 18788 static String arrayToString(int[] array) { 18789 StringBuffer buf = new StringBuffer(128); 18790 buf.append('['); 18791 if (array != null) { 18792 for (int i=0; i<array.length; i++) { 18793 if (i > 0) buf.append(", "); 18794 buf.append(array[i]); 18795 } 18796 } 18797 buf.append(']'); 18798 return buf.toString(); 18799 } 18800 18801 static class DumpState { 18802 public static final int DUMP_LIBS = 1 << 0; 18803 public static final int DUMP_FEATURES = 1 << 1; 18804 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18805 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18806 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18807 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18808 public static final int DUMP_PERMISSIONS = 1 << 6; 18809 public static final int DUMP_PACKAGES = 1 << 7; 18810 public static final int DUMP_SHARED_USERS = 1 << 8; 18811 public static final int DUMP_MESSAGES = 1 << 9; 18812 public static final int DUMP_PROVIDERS = 1 << 10; 18813 public static final int DUMP_VERIFIERS = 1 << 11; 18814 public static final int DUMP_PREFERRED = 1 << 12; 18815 public static final int DUMP_PREFERRED_XML = 1 << 13; 18816 public static final int DUMP_KEYSETS = 1 << 14; 18817 public static final int DUMP_VERSION = 1 << 15; 18818 public static final int DUMP_INSTALLS = 1 << 16; 18819 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18820 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18821 public static final int DUMP_FROZEN = 1 << 19; 18822 public static final int DUMP_DEXOPT = 1 << 20; 18823 public static final int DUMP_COMPILER_STATS = 1 << 21; 18824 18825 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18826 18827 private int mTypes; 18828 18829 private int mOptions; 18830 18831 private boolean mTitlePrinted; 18832 18833 private SharedUserSetting mSharedUser; 18834 18835 public boolean isDumping(int type) { 18836 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18837 return true; 18838 } 18839 18840 return (mTypes & type) != 0; 18841 } 18842 18843 public void setDump(int type) { 18844 mTypes |= type; 18845 } 18846 18847 public boolean isOptionEnabled(int option) { 18848 return (mOptions & option) != 0; 18849 } 18850 18851 public void setOptionEnabled(int option) { 18852 mOptions |= option; 18853 } 18854 18855 public boolean onTitlePrinted() { 18856 final boolean printed = mTitlePrinted; 18857 mTitlePrinted = true; 18858 return printed; 18859 } 18860 18861 public boolean getTitlePrinted() { 18862 return mTitlePrinted; 18863 } 18864 18865 public void setTitlePrinted(boolean enabled) { 18866 mTitlePrinted = enabled; 18867 } 18868 18869 public SharedUserSetting getSharedUser() { 18870 return mSharedUser; 18871 } 18872 18873 public void setSharedUser(SharedUserSetting user) { 18874 mSharedUser = user; 18875 } 18876 } 18877 18878 @Override 18879 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18880 FileDescriptor err, String[] args, ShellCallback callback, 18881 ResultReceiver resultReceiver) { 18882 (new PackageManagerShellCommand(this)).exec( 18883 this, in, out, err, args, callback, resultReceiver); 18884 } 18885 18886 @Override 18887 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18888 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18889 != PackageManager.PERMISSION_GRANTED) { 18890 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18891 + Binder.getCallingPid() 18892 + ", uid=" + Binder.getCallingUid() 18893 + " without permission " 18894 + android.Manifest.permission.DUMP); 18895 return; 18896 } 18897 18898 DumpState dumpState = new DumpState(); 18899 boolean fullPreferred = false; 18900 boolean checkin = false; 18901 18902 String packageName = null; 18903 ArraySet<String> permissionNames = null; 18904 18905 int opti = 0; 18906 while (opti < args.length) { 18907 String opt = args[opti]; 18908 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18909 break; 18910 } 18911 opti++; 18912 18913 if ("-a".equals(opt)) { 18914 // Right now we only know how to print all. 18915 } else if ("-h".equals(opt)) { 18916 pw.println("Package manager dump options:"); 18917 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18918 pw.println(" --checkin: dump for a checkin"); 18919 pw.println(" -f: print details of intent filters"); 18920 pw.println(" -h: print this help"); 18921 pw.println(" cmd may be one of:"); 18922 pw.println(" l[ibraries]: list known shared libraries"); 18923 pw.println(" f[eatures]: list device features"); 18924 pw.println(" k[eysets]: print known keysets"); 18925 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18926 pw.println(" perm[issions]: dump permissions"); 18927 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18928 pw.println(" pref[erred]: print preferred package settings"); 18929 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18930 pw.println(" prov[iders]: dump content providers"); 18931 pw.println(" p[ackages]: dump installed packages"); 18932 pw.println(" s[hared-users]: dump shared user IDs"); 18933 pw.println(" m[essages]: print collected runtime messages"); 18934 pw.println(" v[erifiers]: print package verifier info"); 18935 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18936 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18937 pw.println(" version: print database version info"); 18938 pw.println(" write: write current settings now"); 18939 pw.println(" installs: details about install sessions"); 18940 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18941 pw.println(" dexopt: dump dexopt state"); 18942 pw.println(" compiler-stats: dump compiler statistics"); 18943 pw.println(" <package.name>: info about given package"); 18944 return; 18945 } else if ("--checkin".equals(opt)) { 18946 checkin = true; 18947 } else if ("-f".equals(opt)) { 18948 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18949 } else { 18950 pw.println("Unknown argument: " + opt + "; use -h for help"); 18951 } 18952 } 18953 18954 // Is the caller requesting to dump a particular piece of data? 18955 if (opti < args.length) { 18956 String cmd = args[opti]; 18957 opti++; 18958 // Is this a package name? 18959 if ("android".equals(cmd) || cmd.contains(".")) { 18960 packageName = cmd; 18961 // When dumping a single package, we always dump all of its 18962 // filter information since the amount of data will be reasonable. 18963 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18964 } else if ("check-permission".equals(cmd)) { 18965 if (opti >= args.length) { 18966 pw.println("Error: check-permission missing permission argument"); 18967 return; 18968 } 18969 String perm = args[opti]; 18970 opti++; 18971 if (opti >= args.length) { 18972 pw.println("Error: check-permission missing package argument"); 18973 return; 18974 } 18975 String pkg = args[opti]; 18976 opti++; 18977 int user = UserHandle.getUserId(Binder.getCallingUid()); 18978 if (opti < args.length) { 18979 try { 18980 user = Integer.parseInt(args[opti]); 18981 } catch (NumberFormatException e) { 18982 pw.println("Error: check-permission user argument is not a number: " 18983 + args[opti]); 18984 return; 18985 } 18986 } 18987 pw.println(checkPermission(perm, pkg, user)); 18988 return; 18989 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18990 dumpState.setDump(DumpState.DUMP_LIBS); 18991 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18992 dumpState.setDump(DumpState.DUMP_FEATURES); 18993 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18994 if (opti >= args.length) { 18995 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18996 | DumpState.DUMP_SERVICE_RESOLVERS 18997 | DumpState.DUMP_RECEIVER_RESOLVERS 18998 | DumpState.DUMP_CONTENT_RESOLVERS); 18999 } else { 19000 while (opti < args.length) { 19001 String name = args[opti]; 19002 if ("a".equals(name) || "activity".equals(name)) { 19003 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 19004 } else if ("s".equals(name) || "service".equals(name)) { 19005 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 19006 } else if ("r".equals(name) || "receiver".equals(name)) { 19007 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 19008 } else if ("c".equals(name) || "content".equals(name)) { 19009 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 19010 } else { 19011 pw.println("Error: unknown resolver table type: " + name); 19012 return; 19013 } 19014 opti++; 19015 } 19016 } 19017 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 19018 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 19019 } else if ("permission".equals(cmd)) { 19020 if (opti >= args.length) { 19021 pw.println("Error: permission requires permission name"); 19022 return; 19023 } 19024 permissionNames = new ArraySet<>(); 19025 while (opti < args.length) { 19026 permissionNames.add(args[opti]); 19027 opti++; 19028 } 19029 dumpState.setDump(DumpState.DUMP_PERMISSIONS 19030 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 19031 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 19032 dumpState.setDump(DumpState.DUMP_PREFERRED); 19033 } else if ("preferred-xml".equals(cmd)) { 19034 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 19035 if (opti < args.length && "--full".equals(args[opti])) { 19036 fullPreferred = true; 19037 opti++; 19038 } 19039 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 19040 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 19041 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 19042 dumpState.setDump(DumpState.DUMP_PACKAGES); 19043 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 19044 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 19045 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 19046 dumpState.setDump(DumpState.DUMP_PROVIDERS); 19047 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 19048 dumpState.setDump(DumpState.DUMP_MESSAGES); 19049 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 19050 dumpState.setDump(DumpState.DUMP_VERIFIERS); 19051 } else if ("i".equals(cmd) || "ifv".equals(cmd) 19052 || "intent-filter-verifiers".equals(cmd)) { 19053 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 19054 } else if ("version".equals(cmd)) { 19055 dumpState.setDump(DumpState.DUMP_VERSION); 19056 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 19057 dumpState.setDump(DumpState.DUMP_KEYSETS); 19058 } else if ("installs".equals(cmd)) { 19059 dumpState.setDump(DumpState.DUMP_INSTALLS); 19060 } else if ("frozen".equals(cmd)) { 19061 dumpState.setDump(DumpState.DUMP_FROZEN); 19062 } else if ("dexopt".equals(cmd)) { 19063 dumpState.setDump(DumpState.DUMP_DEXOPT); 19064 } else if ("compiler-stats".equals(cmd)) { 19065 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 19066 } else if ("write".equals(cmd)) { 19067 synchronized (mPackages) { 19068 mSettings.writeLPr(); 19069 pw.println("Settings written."); 19070 return; 19071 } 19072 } 19073 } 19074 19075 if (checkin) { 19076 pw.println("vers,1"); 19077 } 19078 19079 // reader 19080 synchronized (mPackages) { 19081 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 19082 if (!checkin) { 19083 if (dumpState.onTitlePrinted()) 19084 pw.println(); 19085 pw.println("Database versions:"); 19086 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 19087 } 19088 } 19089 19090 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 19091 if (!checkin) { 19092 if (dumpState.onTitlePrinted()) 19093 pw.println(); 19094 pw.println("Verifiers:"); 19095 pw.print(" Required: "); 19096 pw.print(mRequiredVerifierPackage); 19097 pw.print(" (uid="); 19098 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19099 UserHandle.USER_SYSTEM)); 19100 pw.println(")"); 19101 } else if (mRequiredVerifierPackage != null) { 19102 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 19103 pw.print(","); 19104 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19105 UserHandle.USER_SYSTEM)); 19106 } 19107 } 19108 19109 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 19110 packageName == null) { 19111 if (mIntentFilterVerifierComponent != null) { 19112 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 19113 if (!checkin) { 19114 if (dumpState.onTitlePrinted()) 19115 pw.println(); 19116 pw.println("Intent Filter Verifier:"); 19117 pw.print(" Using: "); 19118 pw.print(verifierPackageName); 19119 pw.print(" (uid="); 19120 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19121 UserHandle.USER_SYSTEM)); 19122 pw.println(")"); 19123 } else if (verifierPackageName != null) { 19124 pw.print("ifv,"); pw.print(verifierPackageName); 19125 pw.print(","); 19126 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19127 UserHandle.USER_SYSTEM)); 19128 } 19129 } else { 19130 pw.println(); 19131 pw.println("No Intent Filter Verifier available!"); 19132 } 19133 } 19134 19135 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 19136 boolean printedHeader = false; 19137 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 19138 while (it.hasNext()) { 19139 String name = it.next(); 19140 SharedLibraryEntry ent = mSharedLibraries.get(name); 19141 if (!checkin) { 19142 if (!printedHeader) { 19143 if (dumpState.onTitlePrinted()) 19144 pw.println(); 19145 pw.println("Libraries:"); 19146 printedHeader = true; 19147 } 19148 pw.print(" "); 19149 } else { 19150 pw.print("lib,"); 19151 } 19152 pw.print(name); 19153 if (!checkin) { 19154 pw.print(" -> "); 19155 } 19156 if (ent.path != null) { 19157 if (!checkin) { 19158 pw.print("(jar) "); 19159 pw.print(ent.path); 19160 } else { 19161 pw.print(",jar,"); 19162 pw.print(ent.path); 19163 } 19164 } else { 19165 if (!checkin) { 19166 pw.print("(apk) "); 19167 pw.print(ent.apk); 19168 } else { 19169 pw.print(",apk,"); 19170 pw.print(ent.apk); 19171 } 19172 } 19173 pw.println(); 19174 } 19175 } 19176 19177 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19178 if (dumpState.onTitlePrinted()) 19179 pw.println(); 19180 if (!checkin) { 19181 pw.println("Features:"); 19182 } 19183 19184 for (FeatureInfo feat : mAvailableFeatures.values()) { 19185 if (checkin) { 19186 pw.print("feat,"); 19187 pw.print(feat.name); 19188 pw.print(","); 19189 pw.println(feat.version); 19190 } else { 19191 pw.print(" "); 19192 pw.print(feat.name); 19193 if (feat.version > 0) { 19194 pw.print(" version="); 19195 pw.print(feat.version); 19196 } 19197 pw.println(); 19198 } 19199 } 19200 } 19201 19202 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19203 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19204 : "Activity Resolver Table:", " ", packageName, 19205 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19206 dumpState.setTitlePrinted(true); 19207 } 19208 } 19209 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19210 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19211 : "Receiver Resolver Table:", " ", packageName, 19212 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19213 dumpState.setTitlePrinted(true); 19214 } 19215 } 19216 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19217 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19218 : "Service Resolver Table:", " ", packageName, 19219 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19220 dumpState.setTitlePrinted(true); 19221 } 19222 } 19223 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19224 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19225 : "Provider Resolver Table:", " ", packageName, 19226 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19227 dumpState.setTitlePrinted(true); 19228 } 19229 } 19230 19231 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19232 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19233 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19234 int user = mSettings.mPreferredActivities.keyAt(i); 19235 if (pir.dump(pw, 19236 dumpState.getTitlePrinted() 19237 ? "\nPreferred Activities User " + user + ":" 19238 : "Preferred Activities User " + user + ":", " ", 19239 packageName, true, false)) { 19240 dumpState.setTitlePrinted(true); 19241 } 19242 } 19243 } 19244 19245 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19246 pw.flush(); 19247 FileOutputStream fout = new FileOutputStream(fd); 19248 BufferedOutputStream str = new BufferedOutputStream(fout); 19249 XmlSerializer serializer = new FastXmlSerializer(); 19250 try { 19251 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19252 serializer.startDocument(null, true); 19253 serializer.setFeature( 19254 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19255 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19256 serializer.endDocument(); 19257 serializer.flush(); 19258 } catch (IllegalArgumentException e) { 19259 pw.println("Failed writing: " + e); 19260 } catch (IllegalStateException e) { 19261 pw.println("Failed writing: " + e); 19262 } catch (IOException e) { 19263 pw.println("Failed writing: " + e); 19264 } 19265 } 19266 19267 if (!checkin 19268 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19269 && packageName == null) { 19270 pw.println(); 19271 int count = mSettings.mPackages.size(); 19272 if (count == 0) { 19273 pw.println("No applications!"); 19274 pw.println(); 19275 } else { 19276 final String prefix = " "; 19277 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19278 if (allPackageSettings.size() == 0) { 19279 pw.println("No domain preferred apps!"); 19280 pw.println(); 19281 } else { 19282 pw.println("App verification status:"); 19283 pw.println(); 19284 count = 0; 19285 for (PackageSetting ps : allPackageSettings) { 19286 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19287 if (ivi == null || ivi.getPackageName() == null) continue; 19288 pw.println(prefix + "Package: " + ivi.getPackageName()); 19289 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19290 pw.println(prefix + "Status: " + ivi.getStatusString()); 19291 pw.println(); 19292 count++; 19293 } 19294 if (count == 0) { 19295 pw.println(prefix + "No app verification established."); 19296 pw.println(); 19297 } 19298 for (int userId : sUserManager.getUserIds()) { 19299 pw.println("App linkages for user " + userId + ":"); 19300 pw.println(); 19301 count = 0; 19302 for (PackageSetting ps : allPackageSettings) { 19303 final long status = ps.getDomainVerificationStatusForUser(userId); 19304 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19305 continue; 19306 } 19307 pw.println(prefix + "Package: " + ps.name); 19308 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19309 String statusStr = IntentFilterVerificationInfo. 19310 getStatusStringFromValue(status); 19311 pw.println(prefix + "Status: " + statusStr); 19312 pw.println(); 19313 count++; 19314 } 19315 if (count == 0) { 19316 pw.println(prefix + "No configured app linkages."); 19317 pw.println(); 19318 } 19319 } 19320 } 19321 } 19322 } 19323 19324 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19325 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19326 if (packageName == null && permissionNames == null) { 19327 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19328 if (iperm == 0) { 19329 if (dumpState.onTitlePrinted()) 19330 pw.println(); 19331 pw.println("AppOp Permissions:"); 19332 } 19333 pw.print(" AppOp Permission "); 19334 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19335 pw.println(":"); 19336 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19337 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19338 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19339 } 19340 } 19341 } 19342 } 19343 19344 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19345 boolean printedSomething = false; 19346 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19347 if (packageName != null && !packageName.equals(p.info.packageName)) { 19348 continue; 19349 } 19350 if (!printedSomething) { 19351 if (dumpState.onTitlePrinted()) 19352 pw.println(); 19353 pw.println("Registered ContentProviders:"); 19354 printedSomething = true; 19355 } 19356 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19357 pw.print(" "); pw.println(p.toString()); 19358 } 19359 printedSomething = false; 19360 for (Map.Entry<String, PackageParser.Provider> entry : 19361 mProvidersByAuthority.entrySet()) { 19362 PackageParser.Provider p = entry.getValue(); 19363 if (packageName != null && !packageName.equals(p.info.packageName)) { 19364 continue; 19365 } 19366 if (!printedSomething) { 19367 if (dumpState.onTitlePrinted()) 19368 pw.println(); 19369 pw.println("ContentProvider Authorities:"); 19370 printedSomething = true; 19371 } 19372 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19373 pw.print(" "); pw.println(p.toString()); 19374 if (p.info != null && p.info.applicationInfo != null) { 19375 final String appInfo = p.info.applicationInfo.toString(); 19376 pw.print(" applicationInfo="); pw.println(appInfo); 19377 } 19378 } 19379 } 19380 19381 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19382 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19383 } 19384 19385 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19386 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19387 } 19388 19389 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19390 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19391 } 19392 19393 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19394 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19395 } 19396 19397 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19398 // XXX should handle packageName != null by dumping only install data that 19399 // the given package is involved with. 19400 if (dumpState.onTitlePrinted()) pw.println(); 19401 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19402 } 19403 19404 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19405 // XXX should handle packageName != null by dumping only install data that 19406 // the given package is involved with. 19407 if (dumpState.onTitlePrinted()) pw.println(); 19408 19409 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19410 ipw.println(); 19411 ipw.println("Frozen packages:"); 19412 ipw.increaseIndent(); 19413 if (mFrozenPackages.size() == 0) { 19414 ipw.println("(none)"); 19415 } else { 19416 for (int i = 0; i < mFrozenPackages.size(); i++) { 19417 ipw.println(mFrozenPackages.valueAt(i)); 19418 } 19419 } 19420 ipw.decreaseIndent(); 19421 } 19422 19423 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19424 if (dumpState.onTitlePrinted()) pw.println(); 19425 dumpDexoptStateLPr(pw, packageName); 19426 } 19427 19428 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19429 if (dumpState.onTitlePrinted()) pw.println(); 19430 dumpCompilerStatsLPr(pw, packageName); 19431 } 19432 19433 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19434 if (dumpState.onTitlePrinted()) pw.println(); 19435 mSettings.dumpReadMessagesLPr(pw, dumpState); 19436 19437 pw.println(); 19438 pw.println("Package warning messages:"); 19439 BufferedReader in = null; 19440 String line = null; 19441 try { 19442 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19443 while ((line = in.readLine()) != null) { 19444 if (line.contains("ignored: updated version")) continue; 19445 pw.println(line); 19446 } 19447 } catch (IOException ignored) { 19448 } finally { 19449 IoUtils.closeQuietly(in); 19450 } 19451 } 19452 19453 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19454 BufferedReader in = null; 19455 String line = null; 19456 try { 19457 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19458 while ((line = in.readLine()) != null) { 19459 if (line.contains("ignored: updated version")) continue; 19460 pw.print("msg,"); 19461 pw.println(line); 19462 } 19463 } catch (IOException ignored) { 19464 } finally { 19465 IoUtils.closeQuietly(in); 19466 } 19467 } 19468 } 19469 } 19470 19471 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19472 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19473 ipw.println(); 19474 ipw.println("Dexopt state:"); 19475 ipw.increaseIndent(); 19476 Collection<PackageParser.Package> packages = null; 19477 if (packageName != null) { 19478 PackageParser.Package targetPackage = mPackages.get(packageName); 19479 if (targetPackage != null) { 19480 packages = Collections.singletonList(targetPackage); 19481 } else { 19482 ipw.println("Unable to find package: " + packageName); 19483 return; 19484 } 19485 } else { 19486 packages = mPackages.values(); 19487 } 19488 19489 for (PackageParser.Package pkg : packages) { 19490 ipw.println("[" + pkg.packageName + "]"); 19491 ipw.increaseIndent(); 19492 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19493 ipw.decreaseIndent(); 19494 } 19495 } 19496 19497 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19498 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19499 ipw.println(); 19500 ipw.println("Compiler stats:"); 19501 ipw.increaseIndent(); 19502 Collection<PackageParser.Package> packages = null; 19503 if (packageName != null) { 19504 PackageParser.Package targetPackage = mPackages.get(packageName); 19505 if (targetPackage != null) { 19506 packages = Collections.singletonList(targetPackage); 19507 } else { 19508 ipw.println("Unable to find package: " + packageName); 19509 return; 19510 } 19511 } else { 19512 packages = mPackages.values(); 19513 } 19514 19515 for (PackageParser.Package pkg : packages) { 19516 ipw.println("[" + pkg.packageName + "]"); 19517 ipw.increaseIndent(); 19518 19519 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19520 if (stats == null) { 19521 ipw.println("(No recorded stats)"); 19522 } else { 19523 stats.dump(ipw); 19524 } 19525 ipw.decreaseIndent(); 19526 } 19527 } 19528 19529 private String dumpDomainString(String packageName) { 19530 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19531 .getList(); 19532 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19533 19534 ArraySet<String> result = new ArraySet<>(); 19535 if (iviList.size() > 0) { 19536 for (IntentFilterVerificationInfo ivi : iviList) { 19537 for (String host : ivi.getDomains()) { 19538 result.add(host); 19539 } 19540 } 19541 } 19542 if (filters != null && filters.size() > 0) { 19543 for (IntentFilter filter : filters) { 19544 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19545 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19546 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19547 result.addAll(filter.getHostsList()); 19548 } 19549 } 19550 } 19551 19552 StringBuilder sb = new StringBuilder(result.size() * 16); 19553 for (String domain : result) { 19554 if (sb.length() > 0) sb.append(" "); 19555 sb.append(domain); 19556 } 19557 return sb.toString(); 19558 } 19559 19560 // ------- apps on sdcard specific code ------- 19561 static final boolean DEBUG_SD_INSTALL = false; 19562 19563 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19564 19565 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19566 19567 private boolean mMediaMounted = false; 19568 19569 static String getEncryptKey() { 19570 try { 19571 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19572 SD_ENCRYPTION_KEYSTORE_NAME); 19573 if (sdEncKey == null) { 19574 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19575 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19576 if (sdEncKey == null) { 19577 Slog.e(TAG, "Failed to create encryption keys"); 19578 return null; 19579 } 19580 } 19581 return sdEncKey; 19582 } catch (NoSuchAlgorithmException nsae) { 19583 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19584 return null; 19585 } catch (IOException ioe) { 19586 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19587 return null; 19588 } 19589 } 19590 19591 /* 19592 * Update media status on PackageManager. 19593 */ 19594 @Override 19595 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19596 int callingUid = Binder.getCallingUid(); 19597 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19598 throw new SecurityException("Media status can only be updated by the system"); 19599 } 19600 // reader; this apparently protects mMediaMounted, but should probably 19601 // be a different lock in that case. 19602 synchronized (mPackages) { 19603 Log.i(TAG, "Updating external media status from " 19604 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19605 + (mediaStatus ? "mounted" : "unmounted")); 19606 if (DEBUG_SD_INSTALL) 19607 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19608 + ", mMediaMounted=" + mMediaMounted); 19609 if (mediaStatus == mMediaMounted) { 19610 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19611 : 0, -1); 19612 mHandler.sendMessage(msg); 19613 return; 19614 } 19615 mMediaMounted = mediaStatus; 19616 } 19617 // Queue up an async operation since the package installation may take a 19618 // little while. 19619 mHandler.post(new Runnable() { 19620 public void run() { 19621 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19622 } 19623 }); 19624 } 19625 19626 /** 19627 * Called by StorageManagerService when the initial ASECs to scan are available. 19628 * Should block until all the ASEC containers are finished being scanned. 19629 */ 19630 public void scanAvailableAsecs() { 19631 updateExternalMediaStatusInner(true, false, false); 19632 } 19633 19634 /* 19635 * Collect information of applications on external media, map them against 19636 * existing containers and update information based on current mount status. 19637 * Please note that we always have to report status if reportStatus has been 19638 * set to true especially when unloading packages. 19639 */ 19640 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19641 boolean externalStorage) { 19642 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19643 int[] uidArr = EmptyArray.INT; 19644 19645 final String[] list = PackageHelper.getSecureContainerList(); 19646 if (ArrayUtils.isEmpty(list)) { 19647 Log.i(TAG, "No secure containers found"); 19648 } else { 19649 // Process list of secure containers and categorize them 19650 // as active or stale based on their package internal state. 19651 19652 // reader 19653 synchronized (mPackages) { 19654 for (String cid : list) { 19655 // Leave stages untouched for now; installer service owns them 19656 if (PackageInstallerService.isStageName(cid)) continue; 19657 19658 if (DEBUG_SD_INSTALL) 19659 Log.i(TAG, "Processing container " + cid); 19660 String pkgName = getAsecPackageName(cid); 19661 if (pkgName == null) { 19662 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19663 continue; 19664 } 19665 if (DEBUG_SD_INSTALL) 19666 Log.i(TAG, "Looking for pkg : " + pkgName); 19667 19668 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19669 if (ps == null) { 19670 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19671 continue; 19672 } 19673 19674 /* 19675 * Skip packages that are not external if we're unmounting 19676 * external storage. 19677 */ 19678 if (externalStorage && !isMounted && !isExternal(ps)) { 19679 continue; 19680 } 19681 19682 final AsecInstallArgs args = new AsecInstallArgs(cid, 19683 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19684 // The package status is changed only if the code path 19685 // matches between settings and the container id. 19686 if (ps.codePathString != null 19687 && ps.codePathString.startsWith(args.getCodePath())) { 19688 if (DEBUG_SD_INSTALL) { 19689 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19690 + " at code path: " + ps.codePathString); 19691 } 19692 19693 // We do have a valid package installed on sdcard 19694 processCids.put(args, ps.codePathString); 19695 final int uid = ps.appId; 19696 if (uid != -1) { 19697 uidArr = ArrayUtils.appendInt(uidArr, uid); 19698 } 19699 } else { 19700 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19701 + ps.codePathString); 19702 } 19703 } 19704 } 19705 19706 Arrays.sort(uidArr); 19707 } 19708 19709 // Process packages with valid entries. 19710 if (isMounted) { 19711 if (DEBUG_SD_INSTALL) 19712 Log.i(TAG, "Loading packages"); 19713 loadMediaPackages(processCids, uidArr, externalStorage); 19714 startCleaningPackages(); 19715 mInstallerService.onSecureContainersAvailable(); 19716 } else { 19717 if (DEBUG_SD_INSTALL) 19718 Log.i(TAG, "Unloading packages"); 19719 unloadMediaPackages(processCids, uidArr, reportStatus); 19720 } 19721 } 19722 19723 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19724 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19725 final int size = infos.size(); 19726 final String[] packageNames = new String[size]; 19727 final int[] packageUids = new int[size]; 19728 for (int i = 0; i < size; i++) { 19729 final ApplicationInfo info = infos.get(i); 19730 packageNames[i] = info.packageName; 19731 packageUids[i] = info.uid; 19732 } 19733 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19734 finishedReceiver); 19735 } 19736 19737 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19738 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19739 sendResourcesChangedBroadcast(mediaStatus, replacing, 19740 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19741 } 19742 19743 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19744 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19745 int size = pkgList.length; 19746 if (size > 0) { 19747 // Send broadcasts here 19748 Bundle extras = new Bundle(); 19749 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19750 if (uidArr != null) { 19751 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19752 } 19753 if (replacing) { 19754 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19755 } 19756 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19757 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19758 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19759 } 19760 } 19761 19762 /* 19763 * Look at potentially valid container ids from processCids If package 19764 * information doesn't match the one on record or package scanning fails, 19765 * the cid is added to list of removeCids. We currently don't delete stale 19766 * containers. 19767 */ 19768 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19769 boolean externalStorage) { 19770 ArrayList<String> pkgList = new ArrayList<String>(); 19771 Set<AsecInstallArgs> keys = processCids.keySet(); 19772 19773 for (AsecInstallArgs args : keys) { 19774 String codePath = processCids.get(args); 19775 if (DEBUG_SD_INSTALL) 19776 Log.i(TAG, "Loading container : " + args.cid); 19777 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19778 try { 19779 // Make sure there are no container errors first. 19780 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19781 Slog.e(TAG, "Failed to mount cid : " + args.cid 19782 + " when installing from sdcard"); 19783 continue; 19784 } 19785 // Check code path here. 19786 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19787 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19788 + " does not match one in settings " + codePath); 19789 continue; 19790 } 19791 // Parse package 19792 int parseFlags = mDefParseFlags; 19793 if (args.isExternalAsec()) { 19794 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19795 } 19796 if (args.isFwdLocked()) { 19797 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19798 } 19799 19800 synchronized (mInstallLock) { 19801 PackageParser.Package pkg = null; 19802 try { 19803 // Sadly we don't know the package name yet to freeze it 19804 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19805 SCAN_IGNORE_FROZEN, 0, null); 19806 } catch (PackageManagerException e) { 19807 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19808 } 19809 // Scan the package 19810 if (pkg != null) { 19811 /* 19812 * TODO why is the lock being held? doPostInstall is 19813 * called in other places without the lock. This needs 19814 * to be straightened out. 19815 */ 19816 // writer 19817 synchronized (mPackages) { 19818 retCode = PackageManager.INSTALL_SUCCEEDED; 19819 pkgList.add(pkg.packageName); 19820 // Post process args 19821 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19822 pkg.applicationInfo.uid); 19823 } 19824 } else { 19825 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19826 } 19827 } 19828 19829 } finally { 19830 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19831 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19832 } 19833 } 19834 } 19835 // writer 19836 synchronized (mPackages) { 19837 // If the platform SDK has changed since the last time we booted, 19838 // we need to re-grant app permission to catch any new ones that 19839 // appear. This is really a hack, and means that apps can in some 19840 // cases get permissions that the user didn't initially explicitly 19841 // allow... it would be nice to have some better way to handle 19842 // this situation. 19843 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19844 : mSettings.getInternalVersion(); 19845 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19846 : StorageManager.UUID_PRIVATE_INTERNAL; 19847 19848 int updateFlags = UPDATE_PERMISSIONS_ALL; 19849 if (ver.sdkVersion != mSdkVersion) { 19850 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19851 + mSdkVersion + "; regranting permissions for external"); 19852 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19853 } 19854 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19855 19856 // Yay, everything is now upgraded 19857 ver.forceCurrent(); 19858 19859 // can downgrade to reader 19860 // Persist settings 19861 mSettings.writeLPr(); 19862 } 19863 // Send a broadcast to let everyone know we are done processing 19864 if (pkgList.size() > 0) { 19865 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19866 } 19867 } 19868 19869 /* 19870 * Utility method to unload a list of specified containers 19871 */ 19872 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19873 // Just unmount all valid containers. 19874 for (AsecInstallArgs arg : cidArgs) { 19875 synchronized (mInstallLock) { 19876 arg.doPostDeleteLI(false); 19877 } 19878 } 19879 } 19880 19881 /* 19882 * Unload packages mounted on external media. This involves deleting package 19883 * data from internal structures, sending broadcasts about disabled packages, 19884 * gc'ing to free up references, unmounting all secure containers 19885 * corresponding to packages on external media, and posting a 19886 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19887 * that we always have to post this message if status has been requested no 19888 * matter what. 19889 */ 19890 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19891 final boolean reportStatus) { 19892 if (DEBUG_SD_INSTALL) 19893 Log.i(TAG, "unloading media packages"); 19894 ArrayList<String> pkgList = new ArrayList<String>(); 19895 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19896 final Set<AsecInstallArgs> keys = processCids.keySet(); 19897 for (AsecInstallArgs args : keys) { 19898 String pkgName = args.getPackageName(); 19899 if (DEBUG_SD_INSTALL) 19900 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19901 // Delete package internally 19902 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19903 synchronized (mInstallLock) { 19904 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19905 final boolean res; 19906 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19907 "unloadMediaPackages")) { 19908 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19909 null); 19910 } 19911 if (res) { 19912 pkgList.add(pkgName); 19913 } else { 19914 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19915 failedList.add(args); 19916 } 19917 } 19918 } 19919 19920 // reader 19921 synchronized (mPackages) { 19922 // We didn't update the settings after removing each package; 19923 // write them now for all packages. 19924 mSettings.writeLPr(); 19925 } 19926 19927 // We have to absolutely send UPDATED_MEDIA_STATUS only 19928 // after confirming that all the receivers processed the ordered 19929 // broadcast when packages get disabled, force a gc to clean things up. 19930 // and unload all the containers. 19931 if (pkgList.size() > 0) { 19932 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19933 new IIntentReceiver.Stub() { 19934 public void performReceive(Intent intent, int resultCode, String data, 19935 Bundle extras, boolean ordered, boolean sticky, 19936 int sendingUser) throws RemoteException { 19937 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19938 reportStatus ? 1 : 0, 1, keys); 19939 mHandler.sendMessage(msg); 19940 } 19941 }); 19942 } else { 19943 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19944 keys); 19945 mHandler.sendMessage(msg); 19946 } 19947 } 19948 19949 private void loadPrivatePackages(final VolumeInfo vol) { 19950 mHandler.post(new Runnable() { 19951 @Override 19952 public void run() { 19953 loadPrivatePackagesInner(vol); 19954 } 19955 }); 19956 } 19957 19958 private void loadPrivatePackagesInner(VolumeInfo vol) { 19959 final String volumeUuid = vol.fsUuid; 19960 if (TextUtils.isEmpty(volumeUuid)) { 19961 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19962 return; 19963 } 19964 19965 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19966 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19967 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19968 19969 final VersionInfo ver; 19970 final List<PackageSetting> packages; 19971 synchronized (mPackages) { 19972 ver = mSettings.findOrCreateVersion(volumeUuid); 19973 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19974 } 19975 19976 for (PackageSetting ps : packages) { 19977 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19978 synchronized (mInstallLock) { 19979 final PackageParser.Package pkg; 19980 try { 19981 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19982 loaded.add(pkg.applicationInfo); 19983 19984 } catch (PackageManagerException e) { 19985 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19986 } 19987 19988 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19989 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19990 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19991 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19992 } 19993 } 19994 } 19995 19996 // Reconcile app data for all started/unlocked users 19997 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19998 final UserManager um = mContext.getSystemService(UserManager.class); 19999 UserManagerInternal umInternal = getUserManagerInternal(); 20000 for (UserInfo user : um.getUsers()) { 20001 final int flags; 20002 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20003 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20004 } else if (umInternal.isUserRunning(user.id)) { 20005 flags = StorageManager.FLAG_STORAGE_DE; 20006 } else { 20007 continue; 20008 } 20009 20010 try { 20011 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 20012 synchronized (mInstallLock) { 20013 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 20014 } 20015 } catch (IllegalStateException e) { 20016 // Device was probably ejected, and we'll process that event momentarily 20017 Slog.w(TAG, "Failed to prepare storage: " + e); 20018 } 20019 } 20020 20021 synchronized (mPackages) { 20022 int updateFlags = UPDATE_PERMISSIONS_ALL; 20023 if (ver.sdkVersion != mSdkVersion) { 20024 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20025 + mSdkVersion + "; regranting permissions for " + volumeUuid); 20026 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20027 } 20028 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20029 20030 // Yay, everything is now upgraded 20031 ver.forceCurrent(); 20032 20033 mSettings.writeLPr(); 20034 } 20035 20036 for (PackageFreezer freezer : freezers) { 20037 freezer.close(); 20038 } 20039 20040 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 20041 sendResourcesChangedBroadcast(true, false, loaded, null); 20042 } 20043 20044 private void unloadPrivatePackages(final VolumeInfo vol) { 20045 mHandler.post(new Runnable() { 20046 @Override 20047 public void run() { 20048 unloadPrivatePackagesInner(vol); 20049 } 20050 }); 20051 } 20052 20053 private void unloadPrivatePackagesInner(VolumeInfo vol) { 20054 final String volumeUuid = vol.fsUuid; 20055 if (TextUtils.isEmpty(volumeUuid)) { 20056 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 20057 return; 20058 } 20059 20060 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 20061 synchronized (mInstallLock) { 20062 synchronized (mPackages) { 20063 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 20064 for (PackageSetting ps : packages) { 20065 if (ps.pkg == null) continue; 20066 20067 final ApplicationInfo info = ps.pkg.applicationInfo; 20068 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20069 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20070 20071 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 20072 "unloadPrivatePackagesInner")) { 20073 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 20074 false, null)) { 20075 unloaded.add(info); 20076 } else { 20077 Slog.w(TAG, "Failed to unload " + ps.codePath); 20078 } 20079 } 20080 20081 // Try very hard to release any references to this package 20082 // so we don't risk the system server being killed due to 20083 // open FDs 20084 AttributeCache.instance().removePackage(ps.name); 20085 } 20086 20087 mSettings.writeLPr(); 20088 } 20089 } 20090 20091 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 20092 sendResourcesChangedBroadcast(false, false, unloaded, null); 20093 20094 // Try very hard to release any references to this path so we don't risk 20095 // the system server being killed due to open FDs 20096 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 20097 20098 for (int i = 0; i < 3; i++) { 20099 System.gc(); 20100 System.runFinalization(); 20101 } 20102 } 20103 20104 /** 20105 * Prepare storage areas for given user on all mounted devices. 20106 */ 20107 void prepareUserData(int userId, int userSerial, int flags) { 20108 synchronized (mInstallLock) { 20109 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20110 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20111 final String volumeUuid = vol.getFsUuid(); 20112 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 20113 } 20114 } 20115 } 20116 20117 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 20118 boolean allowRecover) { 20119 // Prepare storage and verify that serial numbers are consistent; if 20120 // there's a mismatch we need to destroy to avoid leaking data 20121 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20122 try { 20123 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 20124 20125 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 20126 UserManagerService.enforceSerialNumber( 20127 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 20128 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20129 UserManagerService.enforceSerialNumber( 20130 Environment.getDataSystemDeDirectory(userId), userSerial); 20131 } 20132 } 20133 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 20134 UserManagerService.enforceSerialNumber( 20135 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 20136 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20137 UserManagerService.enforceSerialNumber( 20138 Environment.getDataSystemCeDirectory(userId), userSerial); 20139 } 20140 } 20141 20142 synchronized (mInstallLock) { 20143 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20144 } 20145 } catch (Exception e) { 20146 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20147 + " because we failed to prepare: " + e); 20148 destroyUserDataLI(volumeUuid, userId, 20149 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20150 20151 if (allowRecover) { 20152 // Try one last time; if we fail again we're really in trouble 20153 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20154 } 20155 } 20156 } 20157 20158 /** 20159 * Destroy storage areas for given user on all mounted devices. 20160 */ 20161 void destroyUserData(int userId, int flags) { 20162 synchronized (mInstallLock) { 20163 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20164 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20165 final String volumeUuid = vol.getFsUuid(); 20166 destroyUserDataLI(volumeUuid, userId, flags); 20167 } 20168 } 20169 } 20170 20171 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20172 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20173 try { 20174 // Clean up app data, profile data, and media data 20175 mInstaller.destroyUserData(volumeUuid, userId, flags); 20176 20177 // Clean up system data 20178 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20179 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20180 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20181 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20182 } 20183 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20184 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20185 } 20186 } 20187 20188 // Data with special labels is now gone, so finish the job 20189 storage.destroyUserStorage(volumeUuid, userId, flags); 20190 20191 } catch (Exception e) { 20192 logCriticalInfo(Log.WARN, 20193 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20194 } 20195 } 20196 20197 /** 20198 * Examine all users present on given mounted volume, and destroy data 20199 * belonging to users that are no longer valid, or whose user ID has been 20200 * recycled. 20201 */ 20202 private void reconcileUsers(String volumeUuid) { 20203 final List<File> files = new ArrayList<>(); 20204 Collections.addAll(files, FileUtils 20205 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20206 Collections.addAll(files, FileUtils 20207 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20208 Collections.addAll(files, FileUtils 20209 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20210 Collections.addAll(files, FileUtils 20211 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20212 for (File file : files) { 20213 if (!file.isDirectory()) continue; 20214 20215 final int userId; 20216 final UserInfo info; 20217 try { 20218 userId = Integer.parseInt(file.getName()); 20219 info = sUserManager.getUserInfo(userId); 20220 } catch (NumberFormatException e) { 20221 Slog.w(TAG, "Invalid user directory " + file); 20222 continue; 20223 } 20224 20225 boolean destroyUser = false; 20226 if (info == null) { 20227 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20228 + " because no matching user was found"); 20229 destroyUser = true; 20230 } else if (!mOnlyCore) { 20231 try { 20232 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20233 } catch (IOException e) { 20234 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20235 + " because we failed to enforce serial number: " + e); 20236 destroyUser = true; 20237 } 20238 } 20239 20240 if (destroyUser) { 20241 synchronized (mInstallLock) { 20242 destroyUserDataLI(volumeUuid, userId, 20243 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20244 } 20245 } 20246 } 20247 } 20248 20249 private void assertPackageKnown(String volumeUuid, String packageName) 20250 throws PackageManagerException { 20251 synchronized (mPackages) { 20252 // Normalize package name to handle renamed packages 20253 packageName = normalizePackageNameLPr(packageName); 20254 20255 final PackageSetting ps = mSettings.mPackages.get(packageName); 20256 if (ps == null) { 20257 throw new PackageManagerException("Package " + packageName + " is unknown"); 20258 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20259 throw new PackageManagerException( 20260 "Package " + packageName + " found on unknown volume " + volumeUuid 20261 + "; expected volume " + ps.volumeUuid); 20262 } 20263 } 20264 } 20265 20266 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20267 throws PackageManagerException { 20268 synchronized (mPackages) { 20269 // Normalize package name to handle renamed packages 20270 packageName = normalizePackageNameLPr(packageName); 20271 20272 final PackageSetting ps = mSettings.mPackages.get(packageName); 20273 if (ps == null) { 20274 throw new PackageManagerException("Package " + packageName + " is unknown"); 20275 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20276 throw new PackageManagerException( 20277 "Package " + packageName + " found on unknown volume " + volumeUuid 20278 + "; expected volume " + ps.volumeUuid); 20279 } else if (!ps.getInstalled(userId)) { 20280 throw new PackageManagerException( 20281 "Package " + packageName + " not installed for user " + userId); 20282 } 20283 } 20284 } 20285 20286 /** 20287 * Examine all apps present on given mounted volume, and destroy apps that 20288 * aren't expected, either due to uninstallation or reinstallation on 20289 * another volume. 20290 */ 20291 private void reconcileApps(String volumeUuid) { 20292 final File[] files = FileUtils 20293 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20294 for (File file : files) { 20295 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20296 && !PackageInstallerService.isStageName(file.getName()); 20297 if (!isPackage) { 20298 // Ignore entries which are not packages 20299 continue; 20300 } 20301 20302 try { 20303 final PackageLite pkg = PackageParser.parsePackageLite(file, 20304 PackageParser.PARSE_MUST_BE_APK); 20305 assertPackageKnown(volumeUuid, pkg.packageName); 20306 20307 } catch (PackageParserException | PackageManagerException e) { 20308 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20309 synchronized (mInstallLock) { 20310 removeCodePathLI(file); 20311 } 20312 } 20313 } 20314 } 20315 20316 /** 20317 * Reconcile all app data for the given user. 20318 * <p> 20319 * Verifies that directories exist and that ownership and labeling is 20320 * correct for all installed apps on all mounted volumes. 20321 */ 20322 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20323 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20324 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20325 final String volumeUuid = vol.getFsUuid(); 20326 synchronized (mInstallLock) { 20327 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20328 } 20329 } 20330 } 20331 20332 /** 20333 * Reconcile all app data on given mounted volume. 20334 * <p> 20335 * Destroys app data that isn't expected, either due to uninstallation or 20336 * reinstallation on another volume. 20337 * <p> 20338 * Verifies that directories exist and that ownership and labeling is 20339 * correct for all installed apps. 20340 */ 20341 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20342 boolean migrateAppData) { 20343 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20344 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20345 20346 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20347 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20348 20349 // First look for stale data that doesn't belong, and check if things 20350 // have changed since we did our last restorecon 20351 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20352 if (StorageManager.isFileEncryptedNativeOrEmulated() 20353 && !StorageManager.isUserKeyUnlocked(userId)) { 20354 throw new RuntimeException( 20355 "Yikes, someone asked us to reconcile CE storage while " + userId 20356 + " was still locked; this would have caused massive data loss!"); 20357 } 20358 20359 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20360 for (File file : files) { 20361 final String packageName = file.getName(); 20362 try { 20363 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20364 } catch (PackageManagerException e) { 20365 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20366 try { 20367 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20368 StorageManager.FLAG_STORAGE_CE, 0); 20369 } catch (InstallerException e2) { 20370 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20371 } 20372 } 20373 } 20374 } 20375 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20376 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20377 for (File file : files) { 20378 final String packageName = file.getName(); 20379 try { 20380 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20381 } catch (PackageManagerException e) { 20382 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20383 try { 20384 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20385 StorageManager.FLAG_STORAGE_DE, 0); 20386 } catch (InstallerException e2) { 20387 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20388 } 20389 } 20390 } 20391 } 20392 20393 // Ensure that data directories are ready to roll for all packages 20394 // installed for this volume and user 20395 final List<PackageSetting> packages; 20396 synchronized (mPackages) { 20397 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20398 } 20399 int preparedCount = 0; 20400 for (PackageSetting ps : packages) { 20401 final String packageName = ps.name; 20402 if (ps.pkg == null) { 20403 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20404 // TODO: might be due to legacy ASEC apps; we should circle back 20405 // and reconcile again once they're scanned 20406 continue; 20407 } 20408 20409 if (ps.getInstalled(userId)) { 20410 prepareAppDataLIF(ps.pkg, userId, flags); 20411 20412 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20413 // We may have just shuffled around app data directories, so 20414 // prepare them one more time 20415 prepareAppDataLIF(ps.pkg, userId, flags); 20416 } 20417 20418 preparedCount++; 20419 } 20420 } 20421 20422 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20423 } 20424 20425 /** 20426 * Prepare app data for the given app just after it was installed or 20427 * upgraded. This method carefully only touches users that it's installed 20428 * for, and it forces a restorecon to handle any seinfo changes. 20429 * <p> 20430 * Verifies that directories exist and that ownership and labeling is 20431 * correct for all installed apps. If there is an ownership mismatch, it 20432 * will try recovering system apps by wiping data; third-party app data is 20433 * left intact. 20434 * <p> 20435 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20436 */ 20437 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20438 final PackageSetting ps; 20439 synchronized (mPackages) { 20440 ps = mSettings.mPackages.get(pkg.packageName); 20441 mSettings.writeKernelMappingLPr(ps); 20442 } 20443 20444 final UserManager um = mContext.getSystemService(UserManager.class); 20445 UserManagerInternal umInternal = getUserManagerInternal(); 20446 for (UserInfo user : um.getUsers()) { 20447 final int flags; 20448 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20449 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20450 } else if (umInternal.isUserRunning(user.id)) { 20451 flags = StorageManager.FLAG_STORAGE_DE; 20452 } else { 20453 continue; 20454 } 20455 20456 if (ps.getInstalled(user.id)) { 20457 // TODO: when user data is locked, mark that we're still dirty 20458 prepareAppDataLIF(pkg, user.id, flags); 20459 } 20460 } 20461 } 20462 20463 /** 20464 * Prepare app data for the given app. 20465 * <p> 20466 * Verifies that directories exist and that ownership and labeling is 20467 * correct for all installed apps. If there is an ownership mismatch, this 20468 * will try recovering system apps by wiping data; third-party app data is 20469 * left intact. 20470 */ 20471 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20472 if (pkg == null) { 20473 Slog.wtf(TAG, "Package was null!", new Throwable()); 20474 return; 20475 } 20476 prepareAppDataLeafLIF(pkg, userId, flags); 20477 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20478 for (int i = 0; i < childCount; i++) { 20479 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20480 } 20481 } 20482 20483 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20484 if (DEBUG_APP_DATA) { 20485 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20486 + Integer.toHexString(flags)); 20487 } 20488 20489 final String volumeUuid = pkg.volumeUuid; 20490 final String packageName = pkg.packageName; 20491 final ApplicationInfo app = pkg.applicationInfo; 20492 final int appId = UserHandle.getAppId(app.uid); 20493 20494 Preconditions.checkNotNull(app.seinfo); 20495 20496 long ceDataInode = -1; 20497 try { 20498 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20499 appId, app.seinfo, app.targetSdkVersion); 20500 } catch (InstallerException e) { 20501 if (app.isSystemApp()) { 20502 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20503 + ", but trying to recover: " + e); 20504 destroyAppDataLeafLIF(pkg, userId, flags); 20505 try { 20506 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20507 appId, app.seinfo, app.targetSdkVersion); 20508 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20509 } catch (InstallerException e2) { 20510 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20511 } 20512 } else { 20513 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20514 } 20515 } 20516 20517 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20518 // TODO: mark this structure as dirty so we persist it! 20519 synchronized (mPackages) { 20520 final PackageSetting ps = mSettings.mPackages.get(packageName); 20521 if (ps != null) { 20522 ps.setCeDataInode(ceDataInode, userId); 20523 } 20524 } 20525 } 20526 20527 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20528 } 20529 20530 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20531 if (pkg == null) { 20532 Slog.wtf(TAG, "Package was null!", new Throwable()); 20533 return; 20534 } 20535 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20536 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20537 for (int i = 0; i < childCount; i++) { 20538 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20539 } 20540 } 20541 20542 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20543 final String volumeUuid = pkg.volumeUuid; 20544 final String packageName = pkg.packageName; 20545 final ApplicationInfo app = pkg.applicationInfo; 20546 20547 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20548 // Create a native library symlink only if we have native libraries 20549 // and if the native libraries are 32 bit libraries. We do not provide 20550 // this symlink for 64 bit libraries. 20551 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20552 final String nativeLibPath = app.nativeLibraryDir; 20553 try { 20554 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20555 nativeLibPath, userId); 20556 } catch (InstallerException e) { 20557 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20558 } 20559 } 20560 } 20561 } 20562 20563 /** 20564 * For system apps on non-FBE devices, this method migrates any existing 20565 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20566 * requested by the app. 20567 */ 20568 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20569 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20570 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20571 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20572 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20573 try { 20574 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20575 storageTarget); 20576 } catch (InstallerException e) { 20577 logCriticalInfo(Log.WARN, 20578 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20579 } 20580 return true; 20581 } else { 20582 return false; 20583 } 20584 } 20585 20586 public PackageFreezer freezePackage(String packageName, String killReason) { 20587 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20588 } 20589 20590 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20591 return new PackageFreezer(packageName, userId, killReason); 20592 } 20593 20594 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20595 String killReason) { 20596 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20597 } 20598 20599 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20600 String killReason) { 20601 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20602 return new PackageFreezer(); 20603 } else { 20604 return freezePackage(packageName, userId, killReason); 20605 } 20606 } 20607 20608 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20609 String killReason) { 20610 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20611 } 20612 20613 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20614 String killReason) { 20615 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20616 return new PackageFreezer(); 20617 } else { 20618 return freezePackage(packageName, userId, killReason); 20619 } 20620 } 20621 20622 /** 20623 * Class that freezes and kills the given package upon creation, and 20624 * unfreezes it upon closing. This is typically used when doing surgery on 20625 * app code/data to prevent the app from running while you're working. 20626 */ 20627 private class PackageFreezer implements AutoCloseable { 20628 private final String mPackageName; 20629 private final PackageFreezer[] mChildren; 20630 20631 private final boolean mWeFroze; 20632 20633 private final AtomicBoolean mClosed = new AtomicBoolean(); 20634 private final CloseGuard mCloseGuard = CloseGuard.get(); 20635 20636 /** 20637 * Create and return a stub freezer that doesn't actually do anything, 20638 * typically used when someone requested 20639 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20640 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20641 */ 20642 public PackageFreezer() { 20643 mPackageName = null; 20644 mChildren = null; 20645 mWeFroze = false; 20646 mCloseGuard.open("close"); 20647 } 20648 20649 public PackageFreezer(String packageName, int userId, String killReason) { 20650 synchronized (mPackages) { 20651 mPackageName = packageName; 20652 mWeFroze = mFrozenPackages.add(mPackageName); 20653 20654 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20655 if (ps != null) { 20656 killApplication(ps.name, ps.appId, userId, killReason); 20657 } 20658 20659 final PackageParser.Package p = mPackages.get(packageName); 20660 if (p != null && p.childPackages != null) { 20661 final int N = p.childPackages.size(); 20662 mChildren = new PackageFreezer[N]; 20663 for (int i = 0; i < N; i++) { 20664 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20665 userId, killReason); 20666 } 20667 } else { 20668 mChildren = null; 20669 } 20670 } 20671 mCloseGuard.open("close"); 20672 } 20673 20674 @Override 20675 protected void finalize() throws Throwable { 20676 try { 20677 mCloseGuard.warnIfOpen(); 20678 close(); 20679 } finally { 20680 super.finalize(); 20681 } 20682 } 20683 20684 @Override 20685 public void close() { 20686 mCloseGuard.close(); 20687 if (mClosed.compareAndSet(false, true)) { 20688 synchronized (mPackages) { 20689 if (mWeFroze) { 20690 mFrozenPackages.remove(mPackageName); 20691 } 20692 20693 if (mChildren != null) { 20694 for (PackageFreezer freezer : mChildren) { 20695 freezer.close(); 20696 } 20697 } 20698 } 20699 } 20700 } 20701 } 20702 20703 /** 20704 * Verify that given package is currently frozen. 20705 */ 20706 private void checkPackageFrozen(String packageName) { 20707 synchronized (mPackages) { 20708 if (!mFrozenPackages.contains(packageName)) { 20709 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20710 } 20711 } 20712 } 20713 20714 @Override 20715 public int movePackage(final String packageName, final String volumeUuid) { 20716 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20717 20718 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20719 final int moveId = mNextMoveId.getAndIncrement(); 20720 mHandler.post(new Runnable() { 20721 @Override 20722 public void run() { 20723 try { 20724 movePackageInternal(packageName, volumeUuid, moveId, user); 20725 } catch (PackageManagerException e) { 20726 Slog.w(TAG, "Failed to move " + packageName, e); 20727 mMoveCallbacks.notifyStatusChanged(moveId, 20728 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20729 } 20730 } 20731 }); 20732 return moveId; 20733 } 20734 20735 private void movePackageInternal(final String packageName, final String volumeUuid, 20736 final int moveId, UserHandle user) throws PackageManagerException { 20737 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20738 final PackageManager pm = mContext.getPackageManager(); 20739 20740 final boolean currentAsec; 20741 final String currentVolumeUuid; 20742 final File codeFile; 20743 final String installerPackageName; 20744 final String packageAbiOverride; 20745 final int appId; 20746 final String seinfo; 20747 final String label; 20748 final int targetSdkVersion; 20749 final PackageFreezer freezer; 20750 final int[] installedUserIds; 20751 20752 // reader 20753 synchronized (mPackages) { 20754 final PackageParser.Package pkg = mPackages.get(packageName); 20755 final PackageSetting ps = mSettings.mPackages.get(packageName); 20756 if (pkg == null || ps == null) { 20757 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20758 } 20759 20760 if (pkg.applicationInfo.isSystemApp()) { 20761 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20762 "Cannot move system application"); 20763 } 20764 20765 if (pkg.applicationInfo.isExternalAsec()) { 20766 currentAsec = true; 20767 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20768 } else if (pkg.applicationInfo.isForwardLocked()) { 20769 currentAsec = true; 20770 currentVolumeUuid = "forward_locked"; 20771 } else { 20772 currentAsec = false; 20773 currentVolumeUuid = ps.volumeUuid; 20774 20775 final File probe = new File(pkg.codePath); 20776 final File probeOat = new File(probe, "oat"); 20777 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20778 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20779 "Move only supported for modern cluster style installs"); 20780 } 20781 } 20782 20783 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20784 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20785 "Package already moved to " + volumeUuid); 20786 } 20787 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20788 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20789 "Device admin cannot be moved"); 20790 } 20791 20792 if (mFrozenPackages.contains(packageName)) { 20793 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20794 "Failed to move already frozen package"); 20795 } 20796 20797 codeFile = new File(pkg.codePath); 20798 installerPackageName = ps.installerPackageName; 20799 packageAbiOverride = ps.cpuAbiOverrideString; 20800 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20801 seinfo = pkg.applicationInfo.seinfo; 20802 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20803 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20804 freezer = freezePackage(packageName, "movePackageInternal"); 20805 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20806 } 20807 20808 final Bundle extras = new Bundle(); 20809 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20810 extras.putString(Intent.EXTRA_TITLE, label); 20811 mMoveCallbacks.notifyCreated(moveId, extras); 20812 20813 int installFlags; 20814 final boolean moveCompleteApp; 20815 final File measurePath; 20816 20817 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20818 installFlags = INSTALL_INTERNAL; 20819 moveCompleteApp = !currentAsec; 20820 measurePath = Environment.getDataAppDirectory(volumeUuid); 20821 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20822 installFlags = INSTALL_EXTERNAL; 20823 moveCompleteApp = false; 20824 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20825 } else { 20826 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20827 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20828 || !volume.isMountedWritable()) { 20829 freezer.close(); 20830 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20831 "Move location not mounted private volume"); 20832 } 20833 20834 Preconditions.checkState(!currentAsec); 20835 20836 installFlags = INSTALL_INTERNAL; 20837 moveCompleteApp = true; 20838 measurePath = Environment.getDataAppDirectory(volumeUuid); 20839 } 20840 20841 final PackageStats stats = new PackageStats(null, -1); 20842 synchronized (mInstaller) { 20843 for (int userId : installedUserIds) { 20844 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20845 freezer.close(); 20846 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20847 "Failed to measure package size"); 20848 } 20849 } 20850 } 20851 20852 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20853 + stats.dataSize); 20854 20855 final long startFreeBytes = measurePath.getFreeSpace(); 20856 final long sizeBytes; 20857 if (moveCompleteApp) { 20858 sizeBytes = stats.codeSize + stats.dataSize; 20859 } else { 20860 sizeBytes = stats.codeSize; 20861 } 20862 20863 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20864 freezer.close(); 20865 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20866 "Not enough free space to move"); 20867 } 20868 20869 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20870 20871 final CountDownLatch installedLatch = new CountDownLatch(1); 20872 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20873 @Override 20874 public void onUserActionRequired(Intent intent) throws RemoteException { 20875 throw new IllegalStateException(); 20876 } 20877 20878 @Override 20879 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20880 Bundle extras) throws RemoteException { 20881 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20882 + PackageManager.installStatusToString(returnCode, msg)); 20883 20884 installedLatch.countDown(); 20885 freezer.close(); 20886 20887 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20888 switch (status) { 20889 case PackageInstaller.STATUS_SUCCESS: 20890 mMoveCallbacks.notifyStatusChanged(moveId, 20891 PackageManager.MOVE_SUCCEEDED); 20892 break; 20893 case PackageInstaller.STATUS_FAILURE_STORAGE: 20894 mMoveCallbacks.notifyStatusChanged(moveId, 20895 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20896 break; 20897 default: 20898 mMoveCallbacks.notifyStatusChanged(moveId, 20899 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20900 break; 20901 } 20902 } 20903 }; 20904 20905 final MoveInfo move; 20906 if (moveCompleteApp) { 20907 // Kick off a thread to report progress estimates 20908 new Thread() { 20909 @Override 20910 public void run() { 20911 while (true) { 20912 try { 20913 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20914 break; 20915 } 20916 } catch (InterruptedException ignored) { 20917 } 20918 20919 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20920 final int progress = 10 + (int) MathUtils.constrain( 20921 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20922 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20923 } 20924 } 20925 }.start(); 20926 20927 final String dataAppName = codeFile.getName(); 20928 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20929 dataAppName, appId, seinfo, targetSdkVersion); 20930 } else { 20931 move = null; 20932 } 20933 20934 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20935 20936 final Message msg = mHandler.obtainMessage(INIT_COPY); 20937 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20938 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20939 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20940 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20941 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20942 msg.obj = params; 20943 20944 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20945 System.identityHashCode(msg.obj)); 20946 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20947 System.identityHashCode(msg.obj)); 20948 20949 mHandler.sendMessage(msg); 20950 } 20951 20952 @Override 20953 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20954 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20955 20956 final int realMoveId = mNextMoveId.getAndIncrement(); 20957 final Bundle extras = new Bundle(); 20958 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20959 mMoveCallbacks.notifyCreated(realMoveId, extras); 20960 20961 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20962 @Override 20963 public void onCreated(int moveId, Bundle extras) { 20964 // Ignored 20965 } 20966 20967 @Override 20968 public void onStatusChanged(int moveId, int status, long estMillis) { 20969 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20970 } 20971 }; 20972 20973 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20974 storage.setPrimaryStorageUuid(volumeUuid, callback); 20975 return realMoveId; 20976 } 20977 20978 @Override 20979 public int getMoveStatus(int moveId) { 20980 mContext.enforceCallingOrSelfPermission( 20981 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20982 return mMoveCallbacks.mLastStatus.get(moveId); 20983 } 20984 20985 @Override 20986 public void registerMoveCallback(IPackageMoveObserver callback) { 20987 mContext.enforceCallingOrSelfPermission( 20988 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20989 mMoveCallbacks.register(callback); 20990 } 20991 20992 @Override 20993 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20994 mContext.enforceCallingOrSelfPermission( 20995 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20996 mMoveCallbacks.unregister(callback); 20997 } 20998 20999 @Override 21000 public boolean setInstallLocation(int loc) { 21001 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 21002 null); 21003 if (getInstallLocation() == loc) { 21004 return true; 21005 } 21006 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 21007 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 21008 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 21009 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 21010 return true; 21011 } 21012 return false; 21013 } 21014 21015 @Override 21016 public int getInstallLocation() { 21017 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 21018 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 21019 PackageHelper.APP_INSTALL_AUTO); 21020 } 21021 21022 /** Called by UserManagerService */ 21023 void cleanUpUser(UserManagerService userManager, int userHandle) { 21024 synchronized (mPackages) { 21025 mDirtyUsers.remove(userHandle); 21026 mUserNeedsBadging.delete(userHandle); 21027 mSettings.removeUserLPw(userHandle); 21028 mPendingBroadcasts.remove(userHandle); 21029 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 21030 removeUnusedPackagesLPw(userManager, userHandle); 21031 } 21032 } 21033 21034 /** 21035 * We're removing userHandle and would like to remove any downloaded packages 21036 * that are no longer in use by any other user. 21037 * @param userHandle the user being removed 21038 */ 21039 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 21040 final boolean DEBUG_CLEAN_APKS = false; 21041 int [] users = userManager.getUserIds(); 21042 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 21043 while (psit.hasNext()) { 21044 PackageSetting ps = psit.next(); 21045 if (ps.pkg == null) { 21046 continue; 21047 } 21048 final String packageName = ps.pkg.packageName; 21049 // Skip over if system app 21050 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 21051 continue; 21052 } 21053 if (DEBUG_CLEAN_APKS) { 21054 Slog.i(TAG, "Checking package " + packageName); 21055 } 21056 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 21057 if (keep) { 21058 if (DEBUG_CLEAN_APKS) { 21059 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 21060 } 21061 } else { 21062 for (int i = 0; i < users.length; i++) { 21063 if (users[i] != userHandle && ps.getInstalled(users[i])) { 21064 keep = true; 21065 if (DEBUG_CLEAN_APKS) { 21066 Slog.i(TAG, " Keeping package " + packageName + " for user " 21067 + users[i]); 21068 } 21069 break; 21070 } 21071 } 21072 } 21073 if (!keep) { 21074 if (DEBUG_CLEAN_APKS) { 21075 Slog.i(TAG, " Removing package " + packageName); 21076 } 21077 mHandler.post(new Runnable() { 21078 public void run() { 21079 deletePackageX(packageName, userHandle, 0); 21080 } //end run 21081 }); 21082 } 21083 } 21084 } 21085 21086 /** Called by UserManagerService */ 21087 void createNewUser(int userId, String[] disallowedPackages) { 21088 synchronized (mInstallLock) { 21089 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 21090 } 21091 synchronized (mPackages) { 21092 scheduleWritePackageRestrictionsLocked(userId); 21093 scheduleWritePackageListLocked(userId); 21094 applyFactoryDefaultBrowserLPw(userId); 21095 primeDomainVerificationsLPw(userId); 21096 } 21097 } 21098 21099 void onNewUserCreated(final int userId) { 21100 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21101 // If permission review for legacy apps is required, we represent 21102 // dagerous permissions for such apps as always granted runtime 21103 // permissions to keep per user flag state whether review is needed. 21104 // Hence, if a new user is added we have to propagate dangerous 21105 // permission grants for these legacy apps. 21106 if (mPermissionReviewRequired) { 21107 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 21108 | UPDATE_PERMISSIONS_REPLACE_ALL); 21109 } 21110 } 21111 21112 @Override 21113 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 21114 mContext.enforceCallingOrSelfPermission( 21115 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 21116 "Only package verification agents can read the verifier device identity"); 21117 21118 synchronized (mPackages) { 21119 return mSettings.getVerifierDeviceIdentityLPw(); 21120 } 21121 } 21122 21123 @Override 21124 public void setPermissionEnforced(String permission, boolean enforced) { 21125 // TODO: Now that we no longer change GID for storage, this should to away. 21126 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 21127 "setPermissionEnforced"); 21128 if (READ_EXTERNAL_STORAGE.equals(permission)) { 21129 synchronized (mPackages) { 21130 if (mSettings.mReadExternalStorageEnforced == null 21131 || mSettings.mReadExternalStorageEnforced != enforced) { 21132 mSettings.mReadExternalStorageEnforced = enforced; 21133 mSettings.writeLPr(); 21134 } 21135 } 21136 // kill any non-foreground processes so we restart them and 21137 // grant/revoke the GID. 21138 final IActivityManager am = ActivityManager.getService(); 21139 if (am != null) { 21140 final long token = Binder.clearCallingIdentity(); 21141 try { 21142 am.killProcessesBelowForeground("setPermissionEnforcement"); 21143 } catch (RemoteException e) { 21144 } finally { 21145 Binder.restoreCallingIdentity(token); 21146 } 21147 } 21148 } else { 21149 throw new IllegalArgumentException("No selective enforcement for " + permission); 21150 } 21151 } 21152 21153 @Override 21154 @Deprecated 21155 public boolean isPermissionEnforced(String permission) { 21156 return true; 21157 } 21158 21159 @Override 21160 public boolean isStorageLow() { 21161 final long token = Binder.clearCallingIdentity(); 21162 try { 21163 final DeviceStorageMonitorInternal 21164 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21165 if (dsm != null) { 21166 return dsm.isMemoryLow(); 21167 } else { 21168 return false; 21169 } 21170 } finally { 21171 Binder.restoreCallingIdentity(token); 21172 } 21173 } 21174 21175 @Override 21176 public IPackageInstaller getPackageInstaller() { 21177 return mInstallerService; 21178 } 21179 21180 private boolean userNeedsBadging(int userId) { 21181 int index = mUserNeedsBadging.indexOfKey(userId); 21182 if (index < 0) { 21183 final UserInfo userInfo; 21184 final long token = Binder.clearCallingIdentity(); 21185 try { 21186 userInfo = sUserManager.getUserInfo(userId); 21187 } finally { 21188 Binder.restoreCallingIdentity(token); 21189 } 21190 final boolean b; 21191 if (userInfo != null && userInfo.isManagedProfile()) { 21192 b = true; 21193 } else { 21194 b = false; 21195 } 21196 mUserNeedsBadging.put(userId, b); 21197 return b; 21198 } 21199 return mUserNeedsBadging.valueAt(index); 21200 } 21201 21202 @Override 21203 public KeySet getKeySetByAlias(String packageName, String alias) { 21204 if (packageName == null || alias == null) { 21205 return null; 21206 } 21207 synchronized(mPackages) { 21208 final PackageParser.Package pkg = mPackages.get(packageName); 21209 if (pkg == null) { 21210 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21211 throw new IllegalArgumentException("Unknown package: " + packageName); 21212 } 21213 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21214 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21215 } 21216 } 21217 21218 @Override 21219 public KeySet getSigningKeySet(String packageName) { 21220 if (packageName == null) { 21221 return null; 21222 } 21223 synchronized(mPackages) { 21224 final PackageParser.Package pkg = mPackages.get(packageName); 21225 if (pkg == null) { 21226 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21227 throw new IllegalArgumentException("Unknown package: " + packageName); 21228 } 21229 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21230 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21231 throw new SecurityException("May not access signing KeySet of other apps."); 21232 } 21233 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21234 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21235 } 21236 } 21237 21238 @Override 21239 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21240 if (packageName == null || ks == null) { 21241 return false; 21242 } 21243 synchronized(mPackages) { 21244 final PackageParser.Package pkg = mPackages.get(packageName); 21245 if (pkg == null) { 21246 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21247 throw new IllegalArgumentException("Unknown package: " + packageName); 21248 } 21249 IBinder ksh = ks.getToken(); 21250 if (ksh instanceof KeySetHandle) { 21251 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21252 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21253 } 21254 return false; 21255 } 21256 } 21257 21258 @Override 21259 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21260 if (packageName == null || ks == null) { 21261 return false; 21262 } 21263 synchronized(mPackages) { 21264 final PackageParser.Package pkg = mPackages.get(packageName); 21265 if (pkg == null) { 21266 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21267 throw new IllegalArgumentException("Unknown package: " + packageName); 21268 } 21269 IBinder ksh = ks.getToken(); 21270 if (ksh instanceof KeySetHandle) { 21271 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21272 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21273 } 21274 return false; 21275 } 21276 } 21277 21278 private void deletePackageIfUnusedLPr(final String packageName) { 21279 PackageSetting ps = mSettings.mPackages.get(packageName); 21280 if (ps == null) { 21281 return; 21282 } 21283 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21284 // TODO Implement atomic delete if package is unused 21285 // It is currently possible that the package will be deleted even if it is installed 21286 // after this method returns. 21287 mHandler.post(new Runnable() { 21288 public void run() { 21289 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21290 } 21291 }); 21292 } 21293 } 21294 21295 /** 21296 * Check and throw if the given before/after packages would be considered a 21297 * downgrade. 21298 */ 21299 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21300 throws PackageManagerException { 21301 if (after.versionCode < before.mVersionCode) { 21302 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21303 "Update version code " + after.versionCode + " is older than current " 21304 + before.mVersionCode); 21305 } else if (after.versionCode == before.mVersionCode) { 21306 if (after.baseRevisionCode < before.baseRevisionCode) { 21307 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21308 "Update base revision code " + after.baseRevisionCode 21309 + " is older than current " + before.baseRevisionCode); 21310 } 21311 21312 if (!ArrayUtils.isEmpty(after.splitNames)) { 21313 for (int i = 0; i < after.splitNames.length; i++) { 21314 final String splitName = after.splitNames[i]; 21315 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21316 if (j != -1) { 21317 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21318 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21319 "Update split " + splitName + " revision code " 21320 + after.splitRevisionCodes[i] + " is older than current " 21321 + before.splitRevisionCodes[j]); 21322 } 21323 } 21324 } 21325 } 21326 } 21327 } 21328 21329 private static class MoveCallbacks extends Handler { 21330 private static final int MSG_CREATED = 1; 21331 private static final int MSG_STATUS_CHANGED = 2; 21332 21333 private final RemoteCallbackList<IPackageMoveObserver> 21334 mCallbacks = new RemoteCallbackList<>(); 21335 21336 private final SparseIntArray mLastStatus = new SparseIntArray(); 21337 21338 public MoveCallbacks(Looper looper) { 21339 super(looper); 21340 } 21341 21342 public void register(IPackageMoveObserver callback) { 21343 mCallbacks.register(callback); 21344 } 21345 21346 public void unregister(IPackageMoveObserver callback) { 21347 mCallbacks.unregister(callback); 21348 } 21349 21350 @Override 21351 public void handleMessage(Message msg) { 21352 final SomeArgs args = (SomeArgs) msg.obj; 21353 final int n = mCallbacks.beginBroadcast(); 21354 for (int i = 0; i < n; i++) { 21355 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21356 try { 21357 invokeCallback(callback, msg.what, args); 21358 } catch (RemoteException ignored) { 21359 } 21360 } 21361 mCallbacks.finishBroadcast(); 21362 args.recycle(); 21363 } 21364 21365 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21366 throws RemoteException { 21367 switch (what) { 21368 case MSG_CREATED: { 21369 callback.onCreated(args.argi1, (Bundle) args.arg2); 21370 break; 21371 } 21372 case MSG_STATUS_CHANGED: { 21373 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21374 break; 21375 } 21376 } 21377 } 21378 21379 private void notifyCreated(int moveId, Bundle extras) { 21380 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21381 21382 final SomeArgs args = SomeArgs.obtain(); 21383 args.argi1 = moveId; 21384 args.arg2 = extras; 21385 obtainMessage(MSG_CREATED, args).sendToTarget(); 21386 } 21387 21388 private void notifyStatusChanged(int moveId, int status) { 21389 notifyStatusChanged(moveId, status, -1); 21390 } 21391 21392 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21393 Slog.v(TAG, "Move " + moveId + " status " + status); 21394 21395 final SomeArgs args = SomeArgs.obtain(); 21396 args.argi1 = moveId; 21397 args.argi2 = status; 21398 args.arg3 = estMillis; 21399 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21400 21401 synchronized (mLastStatus) { 21402 mLastStatus.put(moveId, status); 21403 } 21404 } 21405 } 21406 21407 private final static class OnPermissionChangeListeners extends Handler { 21408 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21409 21410 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21411 new RemoteCallbackList<>(); 21412 21413 public OnPermissionChangeListeners(Looper looper) { 21414 super(looper); 21415 } 21416 21417 @Override 21418 public void handleMessage(Message msg) { 21419 switch (msg.what) { 21420 case MSG_ON_PERMISSIONS_CHANGED: { 21421 final int uid = msg.arg1; 21422 handleOnPermissionsChanged(uid); 21423 } break; 21424 } 21425 } 21426 21427 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21428 mPermissionListeners.register(listener); 21429 21430 } 21431 21432 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21433 mPermissionListeners.unregister(listener); 21434 } 21435 21436 public void onPermissionsChanged(int uid) { 21437 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21438 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21439 } 21440 } 21441 21442 private void handleOnPermissionsChanged(int uid) { 21443 final int count = mPermissionListeners.beginBroadcast(); 21444 try { 21445 for (int i = 0; i < count; i++) { 21446 IOnPermissionsChangeListener callback = mPermissionListeners 21447 .getBroadcastItem(i); 21448 try { 21449 callback.onPermissionsChanged(uid); 21450 } catch (RemoteException e) { 21451 Log.e(TAG, "Permission listener is dead", e); 21452 } 21453 } 21454 } finally { 21455 mPermissionListeners.finishBroadcast(); 21456 } 21457 } 21458 } 21459 21460 private class PackageManagerInternalImpl extends PackageManagerInternal { 21461 @Override 21462 public void setLocationPackagesProvider(PackagesProvider provider) { 21463 synchronized (mPackages) { 21464 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21465 } 21466 } 21467 21468 @Override 21469 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21470 synchronized (mPackages) { 21471 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21472 } 21473 } 21474 21475 @Override 21476 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21477 synchronized (mPackages) { 21478 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21479 } 21480 } 21481 21482 @Override 21483 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21484 synchronized (mPackages) { 21485 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21486 } 21487 } 21488 21489 @Override 21490 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21491 synchronized (mPackages) { 21492 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21493 } 21494 } 21495 21496 @Override 21497 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21498 synchronized (mPackages) { 21499 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21500 } 21501 } 21502 21503 @Override 21504 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21505 synchronized (mPackages) { 21506 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21507 packageName, userId); 21508 } 21509 } 21510 21511 @Override 21512 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21513 synchronized (mPackages) { 21514 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21515 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21516 packageName, userId); 21517 } 21518 } 21519 21520 @Override 21521 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21522 synchronized (mPackages) { 21523 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21524 packageName, userId); 21525 } 21526 } 21527 21528 @Override 21529 public void setKeepUninstalledPackages(final List<String> packageList) { 21530 Preconditions.checkNotNull(packageList); 21531 List<String> removedFromList = null; 21532 synchronized (mPackages) { 21533 if (mKeepUninstalledPackages != null) { 21534 final int packagesCount = mKeepUninstalledPackages.size(); 21535 for (int i = 0; i < packagesCount; i++) { 21536 String oldPackage = mKeepUninstalledPackages.get(i); 21537 if (packageList != null && packageList.contains(oldPackage)) { 21538 continue; 21539 } 21540 if (removedFromList == null) { 21541 removedFromList = new ArrayList<>(); 21542 } 21543 removedFromList.add(oldPackage); 21544 } 21545 } 21546 mKeepUninstalledPackages = new ArrayList<>(packageList); 21547 if (removedFromList != null) { 21548 final int removedCount = removedFromList.size(); 21549 for (int i = 0; i < removedCount; i++) { 21550 deletePackageIfUnusedLPr(removedFromList.get(i)); 21551 } 21552 } 21553 } 21554 } 21555 21556 @Override 21557 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21558 synchronized (mPackages) { 21559 // If we do not support permission review, done. 21560 if (!mPermissionReviewRequired) { 21561 return false; 21562 } 21563 21564 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21565 if (packageSetting == null) { 21566 return false; 21567 } 21568 21569 // Permission review applies only to apps not supporting the new permission model. 21570 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21571 return false; 21572 } 21573 21574 // Legacy apps have the permission and get user consent on launch. 21575 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21576 return permissionsState.isPermissionReviewRequired(userId); 21577 } 21578 } 21579 21580 @Override 21581 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21582 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21583 } 21584 21585 @Override 21586 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21587 int userId) { 21588 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21589 } 21590 21591 @Override 21592 public void setDeviceAndProfileOwnerPackages( 21593 int deviceOwnerUserId, String deviceOwnerPackage, 21594 SparseArray<String> profileOwnerPackages) { 21595 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21596 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21597 } 21598 21599 @Override 21600 public boolean isPackageDataProtected(int userId, String packageName) { 21601 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21602 } 21603 21604 @Override 21605 public boolean isPackageEphemeral(int userId, String packageName) { 21606 synchronized (mPackages) { 21607 PackageParser.Package p = mPackages.get(packageName); 21608 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21609 } 21610 } 21611 21612 @Override 21613 public boolean wasPackageEverLaunched(String packageName, int userId) { 21614 synchronized (mPackages) { 21615 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21616 } 21617 } 21618 21619 @Override 21620 public void grantRuntimePermission(String packageName, String name, int userId, 21621 boolean overridePolicy) { 21622 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21623 overridePolicy); 21624 } 21625 21626 @Override 21627 public void revokeRuntimePermission(String packageName, String name, int userId, 21628 boolean overridePolicy) { 21629 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21630 overridePolicy); 21631 } 21632 21633 @Override 21634 public String getNameForUid(int uid) { 21635 return PackageManagerService.this.getNameForUid(uid); 21636 } 21637 21638 @Override 21639 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21640 Intent origIntent, String resolvedType, Intent launchIntent, 21641 String callingPackage, int userId) { 21642 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21643 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21644 } 21645 21646 public String getSetupWizardPackageName() { 21647 return mSetupWizardPackage; 21648 } 21649 } 21650 21651 @Override 21652 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21653 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21654 synchronized (mPackages) { 21655 final long identity = Binder.clearCallingIdentity(); 21656 try { 21657 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21658 packageNames, userId); 21659 } finally { 21660 Binder.restoreCallingIdentity(identity); 21661 } 21662 } 21663 } 21664 21665 private static void enforceSystemOrPhoneCaller(String tag) { 21666 int callingUid = Binder.getCallingUid(); 21667 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21668 throw new SecurityException( 21669 "Cannot call " + tag + " from UID " + callingUid); 21670 } 21671 } 21672 21673 boolean isHistoricalPackageUsageAvailable() { 21674 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21675 } 21676 21677 /** 21678 * Return a <b>copy</b> of the collection of packages known to the package manager. 21679 * @return A copy of the values of mPackages. 21680 */ 21681 Collection<PackageParser.Package> getPackages() { 21682 synchronized (mPackages) { 21683 return new ArrayList<>(mPackages.values()); 21684 } 21685 } 21686 21687 /** 21688 * Logs process start information (including base APK hash) to the security log. 21689 * @hide 21690 */ 21691 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21692 String apkFile, int pid) { 21693 if (!SecurityLog.isLoggingEnabled()) { 21694 return; 21695 } 21696 Bundle data = new Bundle(); 21697 data.putLong("startTimestamp", System.currentTimeMillis()); 21698 data.putString("processName", processName); 21699 data.putInt("uid", uid); 21700 data.putString("seinfo", seinfo); 21701 data.putString("apkFile", apkFile); 21702 data.putInt("pid", pid); 21703 Message msg = mProcessLoggingHandler.obtainMessage( 21704 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21705 msg.setData(data); 21706 mProcessLoggingHandler.sendMessage(msg); 21707 } 21708 21709 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21710 return mCompilerStats.getPackageStats(pkgName); 21711 } 21712 21713 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21714 return getOrCreateCompilerPackageStats(pkg.packageName); 21715 } 21716 21717 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21718 return mCompilerStats.getOrCreatePackageStats(pkgName); 21719 } 21720 21721 public void deleteCompilerPackageStats(String pkgName) { 21722 mCompilerStats.deletePackageStats(pkgName); 21723 } 21724} 21725