PackageManagerService.java revision d5f7e30505c351f3db58f791382240d6dece4dec
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.storage.DeviceStorageMonitorInternal; 264 265import dalvik.system.CloseGuard; 266import dalvik.system.DexFile; 267import dalvik.system.VMRuntime; 268 269import libcore.io.IoUtils; 270import libcore.util.EmptyArray; 271 272import org.xmlpull.v1.XmlPullParser; 273import org.xmlpull.v1.XmlPullParserException; 274import org.xmlpull.v1.XmlSerializer; 275 276import java.io.BufferedOutputStream; 277import java.io.BufferedReader; 278import java.io.ByteArrayInputStream; 279import java.io.ByteArrayOutputStream; 280import java.io.File; 281import java.io.FileDescriptor; 282import java.io.FileInputStream; 283import java.io.FileNotFoundException; 284import java.io.FileOutputStream; 285import java.io.FileReader; 286import java.io.FilenameFilter; 287import java.io.IOException; 288import java.io.PrintWriter; 289import java.nio.charset.StandardCharsets; 290import java.security.DigestInputStream; 291import java.security.MessageDigest; 292import java.security.NoSuchAlgorithmException; 293import java.security.PublicKey; 294import java.security.SecureRandom; 295import java.security.cert.Certificate; 296import java.security.cert.CertificateEncodingException; 297import java.security.cert.CertificateException; 298import java.text.SimpleDateFormat; 299import java.util.ArrayList; 300import java.util.Arrays; 301import java.util.Collection; 302import java.util.Collections; 303import java.util.Comparator; 304import java.util.Date; 305import java.util.HashSet; 306import java.util.Iterator; 307import java.util.List; 308import java.util.Map; 309import java.util.Objects; 310import java.util.Set; 311import java.util.concurrent.CountDownLatch; 312import java.util.concurrent.TimeUnit; 313import java.util.concurrent.atomic.AtomicBoolean; 314import java.util.concurrent.atomic.AtomicInteger; 315 316/** 317 * Keep track of all those APKs everywhere. 318 * <p> 319 * Internally there are two important locks: 320 * <ul> 321 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 322 * and other related state. It is a fine-grained lock that should only be held 323 * momentarily, as it's one of the most contended locks in the system. 324 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 325 * operations typically involve heavy lifting of application data on disk. Since 326 * {@code installd} is single-threaded, and it's operations can often be slow, 327 * this lock should never be acquired while already holding {@link #mPackages}. 328 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 329 * holding {@link #mInstallLock}. 330 * </ul> 331 * Many internal methods rely on the caller to hold the appropriate locks, and 332 * this contract is expressed through method name suffixes: 333 * <ul> 334 * <li>fooLI(): the caller must hold {@link #mInstallLock} 335 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 336 * being modified must be frozen 337 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 338 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 339 * </ul> 340 * <p> 341 * Because this class is very central to the platform's security; please run all 342 * CTS and unit tests whenever making modifications: 343 * 344 * <pre> 345 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 346 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 347 * </pre> 348 */ 349public class PackageManagerService extends IPackageManager.Stub { 350 static final String TAG = "PackageManager"; 351 static final boolean DEBUG_SETTINGS = false; 352 static final boolean DEBUG_PREFERRED = false; 353 static final boolean DEBUG_UPGRADE = false; 354 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 355 private static final boolean DEBUG_BACKUP = false; 356 private static final boolean DEBUG_INSTALL = false; 357 private static final boolean DEBUG_REMOVE = false; 358 private static final boolean DEBUG_BROADCASTS = false; 359 private static final boolean DEBUG_SHOW_INFO = false; 360 private static final boolean DEBUG_PACKAGE_INFO = false; 361 private static final boolean DEBUG_INTENT_MATCHING = false; 362 private static final boolean DEBUG_PACKAGE_SCANNING = false; 363 private static final boolean DEBUG_VERIFY = false; 364 private static final boolean DEBUG_FILTERS = false; 365 366 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 367 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 368 // user, but by default initialize to this. 369 static final boolean DEBUG_DEXOPT = false; 370 371 private static final boolean DEBUG_ABI_SELECTION = false; 372 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 373 private static final boolean DEBUG_TRIAGED_MISSING = false; 374 private static final boolean DEBUG_APP_DATA = false; 375 376 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 377 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 378 379 private static final boolean DISABLE_EPHEMERAL_APPS = false; 380 private static final boolean HIDE_EPHEMERAL_APIS = true; 381 382 private static final int RADIO_UID = Process.PHONE_UID; 383 private static final int LOG_UID = Process.LOG_UID; 384 private static final int NFC_UID = Process.NFC_UID; 385 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 386 private static final int SHELL_UID = Process.SHELL_UID; 387 388 // Cap the size of permission trees that 3rd party apps can define 389 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 390 391 // Suffix used during package installation when copying/moving 392 // package apks to install directory. 393 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 394 395 static final int SCAN_NO_DEX = 1<<1; 396 static final int SCAN_FORCE_DEX = 1<<2; 397 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 398 static final int SCAN_NEW_INSTALL = 1<<4; 399 static final int SCAN_UPDATE_TIME = 1<<5; 400 static final int SCAN_BOOTING = 1<<6; 401 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 402 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 403 static final int SCAN_REPLACING = 1<<9; 404 static final int SCAN_REQUIRE_KNOWN = 1<<10; 405 static final int SCAN_MOVE = 1<<11; 406 static final int SCAN_INITIAL = 1<<12; 407 static final int SCAN_CHECK_ONLY = 1<<13; 408 static final int SCAN_DONT_KILL_APP = 1<<14; 409 static final int SCAN_IGNORE_FROZEN = 1<<15; 410 static final int REMOVE_CHATTY = 1<<16; 411 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 412 413 private static final int[] EMPTY_INT_ARRAY = new int[0]; 414 415 /** 416 * Timeout (in milliseconds) after which the watchdog should declare that 417 * our handler thread is wedged. The usual default for such things is one 418 * minute but we sometimes do very lengthy I/O operations on this thread, 419 * such as installing multi-gigabyte applications, so ours needs to be longer. 420 */ 421 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 422 423 /** 424 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 425 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 426 * settings entry if available, otherwise we use the hardcoded default. If it's been 427 * more than this long since the last fstrim, we force one during the boot sequence. 428 * 429 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 430 * one gets run at the next available charging+idle time. This final mandatory 431 * no-fstrim check kicks in only of the other scheduling criteria is never met. 432 */ 433 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 434 435 /** 436 * Whether verification is enabled by default. 437 */ 438 private static final boolean DEFAULT_VERIFY_ENABLE = true; 439 440 /** 441 * The default maximum time to wait for the verification agent to return in 442 * milliseconds. 443 */ 444 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 445 446 /** 447 * The default response for package verification timeout. 448 * 449 * This can be either PackageManager.VERIFICATION_ALLOW or 450 * PackageManager.VERIFICATION_REJECT. 451 */ 452 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 453 454 static final String PLATFORM_PACKAGE_NAME = "android"; 455 456 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 457 458 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 459 DEFAULT_CONTAINER_PACKAGE, 460 "com.android.defcontainer.DefaultContainerService"); 461 462 private static final String KILL_APP_REASON_GIDS_CHANGED = 463 "permission grant or revoke changed gids"; 464 465 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 466 "permissions revoked"; 467 468 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 469 470 private static final String PACKAGE_SCHEME = "package"; 471 472 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 473 /** 474 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 475 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 476 * VENDOR_OVERLAY_DIR. 477 */ 478 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 479 /** 480 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 481 * is in VENDOR_OVERLAY_THEME_PROPERTY. 482 */ 483 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 484 = "persist.vendor.overlay.theme"; 485 486 /** Permission grant: not grant the permission. */ 487 private static final int GRANT_DENIED = 1; 488 489 /** Permission grant: grant the permission as an install permission. */ 490 private static final int GRANT_INSTALL = 2; 491 492 /** Permission grant: grant the permission as a runtime one. */ 493 private static final int GRANT_RUNTIME = 3; 494 495 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 496 private static final int GRANT_UPGRADE = 4; 497 498 /** Canonical intent used to identify what counts as a "web browser" app */ 499 private static final Intent sBrowserIntent; 500 static { 501 sBrowserIntent = new Intent(); 502 sBrowserIntent.setAction(Intent.ACTION_VIEW); 503 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 504 sBrowserIntent.setData(Uri.parse("http:")); 505 } 506 507 /** 508 * The set of all protected actions [i.e. those actions for which a high priority 509 * intent filter is disallowed]. 510 */ 511 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 512 static { 513 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 514 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 515 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 516 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 517 } 518 519 // Compilation reasons. 520 public static final int REASON_FIRST_BOOT = 0; 521 public static final int REASON_BOOT = 1; 522 public static final int REASON_INSTALL = 2; 523 public static final int REASON_BACKGROUND_DEXOPT = 3; 524 public static final int REASON_AB_OTA = 4; 525 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 526 public static final int REASON_SHARED_APK = 6; 527 public static final int REASON_FORCED_DEXOPT = 7; 528 public static final int REASON_CORE_APP = 8; 529 530 public static final int REASON_LAST = REASON_CORE_APP; 531 532 /** Special library name that skips shared libraries check during compilation. */ 533 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 534 535 /** All dangerous permission names in the same order as the events in MetricsEvent */ 536 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 537 Manifest.permission.READ_CALENDAR, 538 Manifest.permission.WRITE_CALENDAR, 539 Manifest.permission.CAMERA, 540 Manifest.permission.READ_CONTACTS, 541 Manifest.permission.WRITE_CONTACTS, 542 Manifest.permission.GET_ACCOUNTS, 543 Manifest.permission.ACCESS_FINE_LOCATION, 544 Manifest.permission.ACCESS_COARSE_LOCATION, 545 Manifest.permission.RECORD_AUDIO, 546 Manifest.permission.READ_PHONE_STATE, 547 Manifest.permission.CALL_PHONE, 548 Manifest.permission.READ_CALL_LOG, 549 Manifest.permission.WRITE_CALL_LOG, 550 Manifest.permission.ADD_VOICEMAIL, 551 Manifest.permission.USE_SIP, 552 Manifest.permission.PROCESS_OUTGOING_CALLS, 553 Manifest.permission.READ_CELL_BROADCASTS, 554 Manifest.permission.BODY_SENSORS, 555 Manifest.permission.SEND_SMS, 556 Manifest.permission.RECEIVE_SMS, 557 Manifest.permission.READ_SMS, 558 Manifest.permission.RECEIVE_WAP_PUSH, 559 Manifest.permission.RECEIVE_MMS, 560 Manifest.permission.READ_EXTERNAL_STORAGE, 561 Manifest.permission.WRITE_EXTERNAL_STORAGE, 562 Manifest.permission.READ_PHONE_NUMBER); 563 564 final ServiceThread mHandlerThread; 565 566 final PackageHandler mHandler; 567 568 private final ProcessLoggingHandler mProcessLoggingHandler; 569 570 /** 571 * Messages for {@link #mHandler} that need to wait for system ready before 572 * being dispatched. 573 */ 574 private ArrayList<Message> mPostSystemReadyMessages; 575 576 final int mSdkVersion = Build.VERSION.SDK_INT; 577 578 final Context mContext; 579 final boolean mFactoryTest; 580 final boolean mOnlyCore; 581 final DisplayMetrics mMetrics; 582 final int mDefParseFlags; 583 final String[] mSeparateProcesses; 584 final boolean mIsUpgrade; 585 final boolean mIsPreNUpgrade; 586 final boolean mIsPreNMR1Upgrade; 587 588 @GuardedBy("mPackages") 589 private boolean mDexOptDialogShown; 590 591 /** The location for ASEC container files on internal storage. */ 592 final String mAsecInternalPath; 593 594 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 595 // LOCK HELD. Can be called with mInstallLock held. 596 @GuardedBy("mInstallLock") 597 final Installer mInstaller; 598 599 /** Directory where installed third-party apps stored */ 600 final File mAppInstallDir; 601 final File mEphemeralInstallDir; 602 603 /** 604 * Directory to which applications installed internally have their 605 * 32 bit native libraries copied. 606 */ 607 private File mAppLib32InstallDir; 608 609 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 610 // apps. 611 final File mDrmAppPrivateInstallDir; 612 613 // ---------------------------------------------------------------- 614 615 // Lock for state used when installing and doing other long running 616 // operations. Methods that must be called with this lock held have 617 // the suffix "LI". 618 final Object mInstallLock = new Object(); 619 620 // ---------------------------------------------------------------- 621 622 // Keys are String (package name), values are Package. This also serves 623 // as the lock for the global state. Methods that must be called with 624 // this lock held have the prefix "LP". 625 @GuardedBy("mPackages") 626 final ArrayMap<String, PackageParser.Package> mPackages = 627 new ArrayMap<String, PackageParser.Package>(); 628 629 final ArrayMap<String, Set<String>> mKnownCodebase = 630 new ArrayMap<String, Set<String>>(); 631 632 // Tracks available target package names -> overlay package paths. 633 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 634 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 635 636 /** 637 * Tracks new system packages [received in an OTA] that we expect to 638 * find updated user-installed versions. Keys are package name, values 639 * are package location. 640 */ 641 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 642 /** 643 * Tracks high priority intent filters for protected actions. During boot, certain 644 * filter actions are protected and should never be allowed to have a high priority 645 * intent filter for them. However, there is one, and only one exception -- the 646 * setup wizard. It must be able to define a high priority intent filter for these 647 * actions to ensure there are no escapes from the wizard. We need to delay processing 648 * of these during boot as we need to look at all of the system packages in order 649 * to know which component is the setup wizard. 650 */ 651 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 652 /** 653 * Whether or not processing protected filters should be deferred. 654 */ 655 private boolean mDeferProtectedFilters = true; 656 657 /** 658 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 659 */ 660 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 661 /** 662 * Whether or not system app permissions should be promoted from install to runtime. 663 */ 664 boolean mPromoteSystemApps; 665 666 @GuardedBy("mPackages") 667 final Settings mSettings; 668 669 /** 670 * Set of package names that are currently "frozen", which means active 671 * surgery is being done on the code/data for that package. The platform 672 * will refuse to launch frozen packages to avoid race conditions. 673 * 674 * @see PackageFreezer 675 */ 676 @GuardedBy("mPackages") 677 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 678 679 final ProtectedPackages mProtectedPackages; 680 681 boolean mFirstBoot; 682 683 // System configuration read by SystemConfig. 684 final int[] mGlobalGids; 685 final SparseArray<ArraySet<String>> mSystemPermissions; 686 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 687 688 // If mac_permissions.xml was found for seinfo labeling. 689 boolean mFoundPolicyFile; 690 691 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 692 693 public static final class SharedLibraryEntry { 694 public final String path; 695 public final String apk; 696 697 SharedLibraryEntry(String _path, String _apk) { 698 path = _path; 699 apk = _apk; 700 } 701 } 702 703 // Currently known shared libraries. 704 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 705 new ArrayMap<String, SharedLibraryEntry>(); 706 707 // All available activities, for your resolving pleasure. 708 final ActivityIntentResolver mActivities = 709 new ActivityIntentResolver(); 710 711 // All available receivers, for your resolving pleasure. 712 final ActivityIntentResolver mReceivers = 713 new ActivityIntentResolver(); 714 715 // All available services, for your resolving pleasure. 716 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 717 718 // All available providers, for your resolving pleasure. 719 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 720 721 // Mapping from provider base names (first directory in content URI codePath) 722 // to the provider information. 723 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 724 new ArrayMap<String, PackageParser.Provider>(); 725 726 // Mapping from instrumentation class names to info about them. 727 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 728 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 729 730 // Mapping from permission names to info about them. 731 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 732 new ArrayMap<String, PackageParser.PermissionGroup>(); 733 734 // Packages whose data we have transfered into another package, thus 735 // should no longer exist. 736 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 737 738 // Broadcast actions that are only available to the system. 739 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 740 741 /** List of packages waiting for verification. */ 742 final SparseArray<PackageVerificationState> mPendingVerification 743 = new SparseArray<PackageVerificationState>(); 744 745 /** Set of packages associated with each app op permission. */ 746 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 747 748 final PackageInstallerService mInstallerService; 749 750 private final PackageDexOptimizer mPackageDexOptimizer; 751 752 private AtomicInteger mNextMoveId = new AtomicInteger(); 753 private final MoveCallbacks mMoveCallbacks; 754 755 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 756 757 // Cache of users who need badging. 758 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 759 760 /** Token for keys in mPendingVerification. */ 761 private int mPendingVerificationToken = 0; 762 763 volatile boolean mSystemReady; 764 volatile boolean mSafeMode; 765 volatile boolean mHasSystemUidErrors; 766 767 ApplicationInfo mAndroidApplication; 768 final ActivityInfo mResolveActivity = new ActivityInfo(); 769 final ResolveInfo mResolveInfo = new ResolveInfo(); 770 ComponentName mResolveComponentName; 771 PackageParser.Package mPlatformPackage; 772 ComponentName mCustomResolverComponentName; 773 774 boolean mResolverReplaced = false; 775 776 private final @Nullable ComponentName mIntentFilterVerifierComponent; 777 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 778 779 private int mIntentFilterVerificationToken = 0; 780 781 /** The service connection to the ephemeral resolver */ 782 final EphemeralResolverConnection mEphemeralResolverConnection; 783 784 /** Component used to install ephemeral applications */ 785 ComponentName mEphemeralInstallerComponent; 786 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 787 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 788 789 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 790 = new SparseArray<IntentFilterVerificationState>(); 791 792 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 793 794 // List of packages names to keep cached, even if they are uninstalled for all users 795 private List<String> mKeepUninstalledPackages; 796 797 private UserManagerInternal mUserManagerInternal; 798 799 private static class IFVerificationParams { 800 PackageParser.Package pkg; 801 boolean replacing; 802 int userId; 803 int verifierUid; 804 805 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 806 int _userId, int _verifierUid) { 807 pkg = _pkg; 808 replacing = _replacing; 809 userId = _userId; 810 replacing = _replacing; 811 verifierUid = _verifierUid; 812 } 813 } 814 815 private interface IntentFilterVerifier<T extends IntentFilter> { 816 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 817 T filter, String packageName); 818 void startVerifications(int userId); 819 void receiveVerificationResponse(int verificationId); 820 } 821 822 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 823 private Context mContext; 824 private ComponentName mIntentFilterVerifierComponent; 825 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 826 827 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 828 mContext = context; 829 mIntentFilterVerifierComponent = verifierComponent; 830 } 831 832 private String getDefaultScheme() { 833 return IntentFilter.SCHEME_HTTPS; 834 } 835 836 @Override 837 public void startVerifications(int userId) { 838 // Launch verifications requests 839 int count = mCurrentIntentFilterVerifications.size(); 840 for (int n=0; n<count; n++) { 841 int verificationId = mCurrentIntentFilterVerifications.get(n); 842 final IntentFilterVerificationState ivs = 843 mIntentFilterVerificationStates.get(verificationId); 844 845 String packageName = ivs.getPackageName(); 846 847 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 848 final int filterCount = filters.size(); 849 ArraySet<String> domainsSet = new ArraySet<>(); 850 for (int m=0; m<filterCount; m++) { 851 PackageParser.ActivityIntentInfo filter = filters.get(m); 852 domainsSet.addAll(filter.getHostsList()); 853 } 854 synchronized (mPackages) { 855 if (mSettings.createIntentFilterVerificationIfNeededLPw( 856 packageName, domainsSet) != null) { 857 scheduleWriteSettingsLocked(); 858 } 859 } 860 sendVerificationRequest(userId, verificationId, ivs); 861 } 862 mCurrentIntentFilterVerifications.clear(); 863 } 864 865 private void sendVerificationRequest(int userId, int verificationId, 866 IntentFilterVerificationState ivs) { 867 868 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 869 verificationIntent.putExtra( 870 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 871 verificationId); 872 verificationIntent.putExtra( 873 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 874 getDefaultScheme()); 875 verificationIntent.putExtra( 876 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 877 ivs.getHostsString()); 878 verificationIntent.putExtra( 879 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 880 ivs.getPackageName()); 881 verificationIntent.setComponent(mIntentFilterVerifierComponent); 882 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 883 884 UserHandle user = new UserHandle(userId); 885 mContext.sendBroadcastAsUser(verificationIntent, user); 886 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 887 "Sending IntentFilter verification broadcast"); 888 } 889 890 public void receiveVerificationResponse(int verificationId) { 891 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 892 893 final boolean verified = ivs.isVerified(); 894 895 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 896 final int count = filters.size(); 897 if (DEBUG_DOMAIN_VERIFICATION) { 898 Slog.i(TAG, "Received verification response " + verificationId 899 + " for " + count + " filters, verified=" + verified); 900 } 901 for (int n=0; n<count; n++) { 902 PackageParser.ActivityIntentInfo filter = filters.get(n); 903 filter.setVerified(verified); 904 905 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 906 + " verified with result:" + verified + " and hosts:" 907 + ivs.getHostsString()); 908 } 909 910 mIntentFilterVerificationStates.remove(verificationId); 911 912 final String packageName = ivs.getPackageName(); 913 IntentFilterVerificationInfo ivi = null; 914 915 synchronized (mPackages) { 916 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 917 } 918 if (ivi == null) { 919 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 920 + verificationId + " packageName:" + packageName); 921 return; 922 } 923 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 924 "Updating IntentFilterVerificationInfo for package " + packageName 925 +" verificationId:" + verificationId); 926 927 synchronized (mPackages) { 928 if (verified) { 929 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 930 } else { 931 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 932 } 933 scheduleWriteSettingsLocked(); 934 935 final int userId = ivs.getUserId(); 936 if (userId != UserHandle.USER_ALL) { 937 final int userStatus = 938 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 939 940 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 941 boolean needUpdate = false; 942 943 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 944 // already been set by the User thru the Disambiguation dialog 945 switch (userStatus) { 946 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 947 if (verified) { 948 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 949 } else { 950 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 951 } 952 needUpdate = true; 953 break; 954 955 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 956 if (verified) { 957 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 958 needUpdate = true; 959 } 960 break; 961 962 default: 963 // Nothing to do 964 } 965 966 if (needUpdate) { 967 mSettings.updateIntentFilterVerificationStatusLPw( 968 packageName, updatedStatus, userId); 969 scheduleWritePackageRestrictionsLocked(userId); 970 } 971 } 972 } 973 } 974 975 @Override 976 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 977 ActivityIntentInfo filter, String packageName) { 978 if (!hasValidDomains(filter)) { 979 return false; 980 } 981 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 982 if (ivs == null) { 983 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 984 packageName); 985 } 986 if (DEBUG_DOMAIN_VERIFICATION) { 987 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 988 } 989 ivs.addFilter(filter); 990 return true; 991 } 992 993 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 994 int userId, int verificationId, String packageName) { 995 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 996 verifierUid, userId, packageName); 997 ivs.setPendingState(); 998 synchronized (mPackages) { 999 mIntentFilterVerificationStates.append(verificationId, ivs); 1000 mCurrentIntentFilterVerifications.add(verificationId); 1001 } 1002 return ivs; 1003 } 1004 } 1005 1006 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1007 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1008 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1009 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1010 } 1011 1012 // Set of pending broadcasts for aggregating enable/disable of components. 1013 static class PendingPackageBroadcasts { 1014 // for each user id, a map of <package name -> components within that package> 1015 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1016 1017 public PendingPackageBroadcasts() { 1018 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1019 } 1020 1021 public ArrayList<String> get(int userId, String packageName) { 1022 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1023 return packages.get(packageName); 1024 } 1025 1026 public void put(int userId, String packageName, ArrayList<String> components) { 1027 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1028 packages.put(packageName, components); 1029 } 1030 1031 public void remove(int userId, String packageName) { 1032 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1033 if (packages != null) { 1034 packages.remove(packageName); 1035 } 1036 } 1037 1038 public void remove(int userId) { 1039 mUidMap.remove(userId); 1040 } 1041 1042 public int userIdCount() { 1043 return mUidMap.size(); 1044 } 1045 1046 public int userIdAt(int n) { 1047 return mUidMap.keyAt(n); 1048 } 1049 1050 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1051 return mUidMap.get(userId); 1052 } 1053 1054 public int size() { 1055 // total number of pending broadcast entries across all userIds 1056 int num = 0; 1057 for (int i = 0; i< mUidMap.size(); i++) { 1058 num += mUidMap.valueAt(i).size(); 1059 } 1060 return num; 1061 } 1062 1063 public void clear() { 1064 mUidMap.clear(); 1065 } 1066 1067 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1068 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1069 if (map == null) { 1070 map = new ArrayMap<String, ArrayList<String>>(); 1071 mUidMap.put(userId, map); 1072 } 1073 return map; 1074 } 1075 } 1076 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1077 1078 // Service Connection to remote media container service to copy 1079 // package uri's from external media onto secure containers 1080 // or internal storage. 1081 private IMediaContainerService mContainerService = null; 1082 1083 static final int SEND_PENDING_BROADCAST = 1; 1084 static final int MCS_BOUND = 3; 1085 static final int END_COPY = 4; 1086 static final int INIT_COPY = 5; 1087 static final int MCS_UNBIND = 6; 1088 static final int START_CLEANING_PACKAGE = 7; 1089 static final int FIND_INSTALL_LOC = 8; 1090 static final int POST_INSTALL = 9; 1091 static final int MCS_RECONNECT = 10; 1092 static final int MCS_GIVE_UP = 11; 1093 static final int UPDATED_MEDIA_STATUS = 12; 1094 static final int WRITE_SETTINGS = 13; 1095 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1096 static final int PACKAGE_VERIFIED = 15; 1097 static final int CHECK_PENDING_VERIFICATION = 16; 1098 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1099 static final int INTENT_FILTER_VERIFIED = 18; 1100 static final int WRITE_PACKAGE_LIST = 19; 1101 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1102 1103 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1104 1105 // Delay time in millisecs 1106 static final int BROADCAST_DELAY = 10 * 1000; 1107 1108 static UserManagerService sUserManager; 1109 1110 // Stores a list of users whose package restrictions file needs to be updated 1111 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1112 1113 final private DefaultContainerConnection mDefContainerConn = 1114 new DefaultContainerConnection(); 1115 class DefaultContainerConnection implements ServiceConnection { 1116 public void onServiceConnected(ComponentName name, IBinder service) { 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1118 final IMediaContainerService imcs = IMediaContainerService.Stub 1119 .asInterface(Binder.allowBlocking(service)); 1120 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1121 } 1122 1123 public void onServiceDisconnected(ComponentName name) { 1124 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1125 } 1126 } 1127 1128 // Recordkeeping of restore-after-install operations that are currently in flight 1129 // between the Package Manager and the Backup Manager 1130 static class PostInstallData { 1131 public InstallArgs args; 1132 public PackageInstalledInfo res; 1133 1134 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1135 args = _a; 1136 res = _r; 1137 } 1138 } 1139 1140 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1141 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1142 1143 // XML tags for backup/restore of various bits of state 1144 private static final String TAG_PREFERRED_BACKUP = "pa"; 1145 private static final String TAG_DEFAULT_APPS = "da"; 1146 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1147 1148 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1149 private static final String TAG_ALL_GRANTS = "rt-grants"; 1150 private static final String TAG_GRANT = "grant"; 1151 private static final String ATTR_PACKAGE_NAME = "pkg"; 1152 1153 private static final String TAG_PERMISSION = "perm"; 1154 private static final String ATTR_PERMISSION_NAME = "name"; 1155 private static final String ATTR_IS_GRANTED = "g"; 1156 private static final String ATTR_USER_SET = "set"; 1157 private static final String ATTR_USER_FIXED = "fixed"; 1158 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1159 1160 // System/policy permission grants are not backed up 1161 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1162 FLAG_PERMISSION_POLICY_FIXED 1163 | FLAG_PERMISSION_SYSTEM_FIXED 1164 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1165 1166 // And we back up these user-adjusted states 1167 private static final int USER_RUNTIME_GRANT_MASK = 1168 FLAG_PERMISSION_USER_SET 1169 | FLAG_PERMISSION_USER_FIXED 1170 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1171 1172 final @Nullable String mRequiredVerifierPackage; 1173 final @NonNull String mRequiredInstallerPackage; 1174 final @NonNull String mRequiredUninstallerPackage; 1175 final @Nullable String mSetupWizardPackage; 1176 final @Nullable String mStorageManagerPackage; 1177 final @NonNull String mServicesSystemSharedLibraryPackageName; 1178 final @NonNull String mSharedSystemSharedLibraryPackageName; 1179 1180 final boolean mPermissionReviewRequired; 1181 1182 private final PackageUsage mPackageUsage = new PackageUsage(); 1183 private final CompilerStats mCompilerStats = new CompilerStats(); 1184 1185 class PackageHandler extends Handler { 1186 private boolean mBound = false; 1187 final ArrayList<HandlerParams> mPendingInstalls = 1188 new ArrayList<HandlerParams>(); 1189 1190 private boolean connectToService() { 1191 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1192 " DefaultContainerService"); 1193 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1194 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1195 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1196 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1197 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1198 mBound = true; 1199 return true; 1200 } 1201 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1202 return false; 1203 } 1204 1205 private void disconnectService() { 1206 mContainerService = null; 1207 mBound = false; 1208 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1209 mContext.unbindService(mDefContainerConn); 1210 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1211 } 1212 1213 PackageHandler(Looper looper) { 1214 super(looper); 1215 } 1216 1217 public void handleMessage(Message msg) { 1218 try { 1219 doHandleMessage(msg); 1220 } finally { 1221 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1222 } 1223 } 1224 1225 void doHandleMessage(Message msg) { 1226 switch (msg.what) { 1227 case INIT_COPY: { 1228 HandlerParams params = (HandlerParams) msg.obj; 1229 int idx = mPendingInstalls.size(); 1230 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1231 // If a bind was already initiated we dont really 1232 // need to do anything. The pending install 1233 // will be processed later on. 1234 if (!mBound) { 1235 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1236 System.identityHashCode(mHandler)); 1237 // If this is the only one pending we might 1238 // have to bind to the service again. 1239 if (!connectToService()) { 1240 Slog.e(TAG, "Failed to bind to media container service"); 1241 params.serviceError(); 1242 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1243 System.identityHashCode(mHandler)); 1244 if (params.traceMethod != null) { 1245 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1246 params.traceCookie); 1247 } 1248 return; 1249 } else { 1250 // Once we bind to the service, the first 1251 // pending request will be processed. 1252 mPendingInstalls.add(idx, params); 1253 } 1254 } else { 1255 mPendingInstalls.add(idx, params); 1256 // Already bound to the service. Just make 1257 // sure we trigger off processing the first request. 1258 if (idx == 0) { 1259 mHandler.sendEmptyMessage(MCS_BOUND); 1260 } 1261 } 1262 break; 1263 } 1264 case MCS_BOUND: { 1265 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1266 if (msg.obj != null) { 1267 mContainerService = (IMediaContainerService) msg.obj; 1268 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1269 System.identityHashCode(mHandler)); 1270 } 1271 if (mContainerService == null) { 1272 if (!mBound) { 1273 // Something seriously wrong since we are not bound and we are not 1274 // waiting for connection. Bail out. 1275 Slog.e(TAG, "Cannot bind to media container service"); 1276 for (HandlerParams params : mPendingInstalls) { 1277 // Indicate service bind error 1278 params.serviceError(); 1279 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1280 System.identityHashCode(params)); 1281 if (params.traceMethod != null) { 1282 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1283 params.traceMethod, params.traceCookie); 1284 } 1285 return; 1286 } 1287 mPendingInstalls.clear(); 1288 } else { 1289 Slog.w(TAG, "Waiting to connect to media container service"); 1290 } 1291 } else if (mPendingInstalls.size() > 0) { 1292 HandlerParams params = mPendingInstalls.get(0); 1293 if (params != null) { 1294 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1295 System.identityHashCode(params)); 1296 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1297 if (params.startCopy()) { 1298 // We are done... look for more work or to 1299 // go idle. 1300 if (DEBUG_SD_INSTALL) Log.i(TAG, 1301 "Checking for more work or unbind..."); 1302 // Delete pending install 1303 if (mPendingInstalls.size() > 0) { 1304 mPendingInstalls.remove(0); 1305 } 1306 if (mPendingInstalls.size() == 0) { 1307 if (mBound) { 1308 if (DEBUG_SD_INSTALL) Log.i(TAG, 1309 "Posting delayed MCS_UNBIND"); 1310 removeMessages(MCS_UNBIND); 1311 Message ubmsg = obtainMessage(MCS_UNBIND); 1312 // Unbind after a little delay, to avoid 1313 // continual thrashing. 1314 sendMessageDelayed(ubmsg, 10000); 1315 } 1316 } else { 1317 // There are more pending requests in queue. 1318 // Just post MCS_BOUND message to trigger processing 1319 // of next pending install. 1320 if (DEBUG_SD_INSTALL) Log.i(TAG, 1321 "Posting MCS_BOUND for next work"); 1322 mHandler.sendEmptyMessage(MCS_BOUND); 1323 } 1324 } 1325 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1326 } 1327 } else { 1328 // Should never happen ideally. 1329 Slog.w(TAG, "Empty queue"); 1330 } 1331 break; 1332 } 1333 case MCS_RECONNECT: { 1334 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1335 if (mPendingInstalls.size() > 0) { 1336 if (mBound) { 1337 disconnectService(); 1338 } 1339 if (!connectToService()) { 1340 Slog.e(TAG, "Failed to bind to media container service"); 1341 for (HandlerParams params : mPendingInstalls) { 1342 // Indicate service bind error 1343 params.serviceError(); 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1345 System.identityHashCode(params)); 1346 } 1347 mPendingInstalls.clear(); 1348 } 1349 } 1350 break; 1351 } 1352 case MCS_UNBIND: { 1353 // If there is no actual work left, then time to unbind. 1354 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1355 1356 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1357 if (mBound) { 1358 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1359 1360 disconnectService(); 1361 } 1362 } else if (mPendingInstalls.size() > 0) { 1363 // There are more pending requests in queue. 1364 // Just post MCS_BOUND message to trigger processing 1365 // of next pending install. 1366 mHandler.sendEmptyMessage(MCS_BOUND); 1367 } 1368 1369 break; 1370 } 1371 case MCS_GIVE_UP: { 1372 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1373 HandlerParams params = mPendingInstalls.remove(0); 1374 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1375 System.identityHashCode(params)); 1376 break; 1377 } 1378 case SEND_PENDING_BROADCAST: { 1379 String packages[]; 1380 ArrayList<String> components[]; 1381 int size = 0; 1382 int uids[]; 1383 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1384 synchronized (mPackages) { 1385 if (mPendingBroadcasts == null) { 1386 return; 1387 } 1388 size = mPendingBroadcasts.size(); 1389 if (size <= 0) { 1390 // Nothing to be done. Just return 1391 return; 1392 } 1393 packages = new String[size]; 1394 components = new ArrayList[size]; 1395 uids = new int[size]; 1396 int i = 0; // filling out the above arrays 1397 1398 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1399 int packageUserId = mPendingBroadcasts.userIdAt(n); 1400 Iterator<Map.Entry<String, ArrayList<String>>> it 1401 = mPendingBroadcasts.packagesForUserId(packageUserId) 1402 .entrySet().iterator(); 1403 while (it.hasNext() && i < size) { 1404 Map.Entry<String, ArrayList<String>> ent = it.next(); 1405 packages[i] = ent.getKey(); 1406 components[i] = ent.getValue(); 1407 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1408 uids[i] = (ps != null) 1409 ? UserHandle.getUid(packageUserId, ps.appId) 1410 : -1; 1411 i++; 1412 } 1413 } 1414 size = i; 1415 mPendingBroadcasts.clear(); 1416 } 1417 // Send broadcasts 1418 for (int i = 0; i < size; i++) { 1419 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1420 } 1421 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1422 break; 1423 } 1424 case START_CLEANING_PACKAGE: { 1425 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1426 final String packageName = (String)msg.obj; 1427 final int userId = msg.arg1; 1428 final boolean andCode = msg.arg2 != 0; 1429 synchronized (mPackages) { 1430 if (userId == UserHandle.USER_ALL) { 1431 int[] users = sUserManager.getUserIds(); 1432 for (int user : users) { 1433 mSettings.addPackageToCleanLPw( 1434 new PackageCleanItem(user, packageName, andCode)); 1435 } 1436 } else { 1437 mSettings.addPackageToCleanLPw( 1438 new PackageCleanItem(userId, packageName, andCode)); 1439 } 1440 } 1441 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1442 startCleaningPackages(); 1443 } break; 1444 case POST_INSTALL: { 1445 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1446 1447 PostInstallData data = mRunningInstalls.get(msg.arg1); 1448 final boolean didRestore = (msg.arg2 != 0); 1449 mRunningInstalls.delete(msg.arg1); 1450 1451 if (data != null) { 1452 InstallArgs args = data.args; 1453 PackageInstalledInfo parentRes = data.res; 1454 1455 final boolean grantPermissions = (args.installFlags 1456 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1457 final boolean killApp = (args.installFlags 1458 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1459 final String[] grantedPermissions = args.installGrantPermissions; 1460 1461 // Handle the parent package 1462 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1463 grantedPermissions, didRestore, args.installerPackageName, 1464 args.observer); 1465 1466 // Handle the child packages 1467 final int childCount = (parentRes.addedChildPackages != null) 1468 ? parentRes.addedChildPackages.size() : 0; 1469 for (int i = 0; i < childCount; i++) { 1470 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1471 handlePackagePostInstall(childRes, grantPermissions, killApp, 1472 grantedPermissions, false, args.installerPackageName, 1473 args.observer); 1474 } 1475 1476 // Log tracing if needed 1477 if (args.traceMethod != null) { 1478 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1479 args.traceCookie); 1480 } 1481 } else { 1482 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1483 } 1484 1485 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1486 } break; 1487 case UPDATED_MEDIA_STATUS: { 1488 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1489 boolean reportStatus = msg.arg1 == 1; 1490 boolean doGc = msg.arg2 == 1; 1491 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1492 if (doGc) { 1493 // Force a gc to clear up stale containers. 1494 Runtime.getRuntime().gc(); 1495 } 1496 if (msg.obj != null) { 1497 @SuppressWarnings("unchecked") 1498 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1499 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1500 // Unload containers 1501 unloadAllContainers(args); 1502 } 1503 if (reportStatus) { 1504 try { 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, 1506 "Invoking StorageManagerService call back"); 1507 PackageHelper.getStorageManager().finishMediaUpdate(); 1508 } catch (RemoteException e) { 1509 Log.e(TAG, "StorageManagerService not running?"); 1510 } 1511 } 1512 } break; 1513 case WRITE_SETTINGS: { 1514 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1515 synchronized (mPackages) { 1516 removeMessages(WRITE_SETTINGS); 1517 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1518 mSettings.writeLPr(); 1519 mDirtyUsers.clear(); 1520 } 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1522 } break; 1523 case WRITE_PACKAGE_RESTRICTIONS: { 1524 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1525 synchronized (mPackages) { 1526 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1527 for (int userId : mDirtyUsers) { 1528 mSettings.writePackageRestrictionsLPr(userId); 1529 } 1530 mDirtyUsers.clear(); 1531 } 1532 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1533 } break; 1534 case WRITE_PACKAGE_LIST: { 1535 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1536 synchronized (mPackages) { 1537 removeMessages(WRITE_PACKAGE_LIST); 1538 mSettings.writePackageListLPr(msg.arg1); 1539 } 1540 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1541 } break; 1542 case CHECK_PENDING_VERIFICATION: { 1543 final int verificationId = msg.arg1; 1544 final PackageVerificationState state = mPendingVerification.get(verificationId); 1545 1546 if ((state != null) && !state.timeoutExtended()) { 1547 final InstallArgs args = state.getInstallArgs(); 1548 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1549 1550 Slog.i(TAG, "Verification timed out for " + originUri); 1551 mPendingVerification.remove(verificationId); 1552 1553 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1554 1555 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1556 Slog.i(TAG, "Continuing with installation of " + originUri); 1557 state.setVerifierResponse(Binder.getCallingUid(), 1558 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1559 broadcastPackageVerified(verificationId, originUri, 1560 PackageManager.VERIFICATION_ALLOW, 1561 state.getInstallArgs().getUser()); 1562 try { 1563 ret = args.copyApk(mContainerService, true); 1564 } catch (RemoteException e) { 1565 Slog.e(TAG, "Could not contact the ContainerService"); 1566 } 1567 } else { 1568 broadcastPackageVerified(verificationId, originUri, 1569 PackageManager.VERIFICATION_REJECT, 1570 state.getInstallArgs().getUser()); 1571 } 1572 1573 Trace.asyncTraceEnd( 1574 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1575 1576 processPendingInstall(args, ret); 1577 mHandler.sendEmptyMessage(MCS_UNBIND); 1578 } 1579 break; 1580 } 1581 case PACKAGE_VERIFIED: { 1582 final int verificationId = msg.arg1; 1583 1584 final PackageVerificationState state = mPendingVerification.get(verificationId); 1585 if (state == null) { 1586 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1587 break; 1588 } 1589 1590 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1591 1592 state.setVerifierResponse(response.callerUid, response.code); 1593 1594 if (state.isVerificationComplete()) { 1595 mPendingVerification.remove(verificationId); 1596 1597 final InstallArgs args = state.getInstallArgs(); 1598 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1599 1600 int ret; 1601 if (state.isInstallAllowed()) { 1602 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1603 broadcastPackageVerified(verificationId, originUri, 1604 response.code, state.getInstallArgs().getUser()); 1605 try { 1606 ret = args.copyApk(mContainerService, true); 1607 } catch (RemoteException e) { 1608 Slog.e(TAG, "Could not contact the ContainerService"); 1609 } 1610 } else { 1611 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1612 } 1613 1614 Trace.asyncTraceEnd( 1615 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1616 1617 processPendingInstall(args, ret); 1618 mHandler.sendEmptyMessage(MCS_UNBIND); 1619 } 1620 1621 break; 1622 } 1623 case START_INTENT_FILTER_VERIFICATIONS: { 1624 IFVerificationParams params = (IFVerificationParams) msg.obj; 1625 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1626 params.replacing, params.pkg); 1627 break; 1628 } 1629 case INTENT_FILTER_VERIFIED: { 1630 final int verificationId = msg.arg1; 1631 1632 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1633 verificationId); 1634 if (state == null) { 1635 Slog.w(TAG, "Invalid IntentFilter verification token " 1636 + verificationId + " received"); 1637 break; 1638 } 1639 1640 final int userId = state.getUserId(); 1641 1642 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1643 "Processing IntentFilter verification with token:" 1644 + verificationId + " and userId:" + userId); 1645 1646 final IntentFilterVerificationResponse response = 1647 (IntentFilterVerificationResponse) msg.obj; 1648 1649 state.setVerifierResponse(response.callerUid, response.code); 1650 1651 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1652 "IntentFilter verification with token:" + verificationId 1653 + " and userId:" + userId 1654 + " is settings verifier response with response code:" 1655 + response.code); 1656 1657 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1658 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1659 + response.getFailedDomainsString()); 1660 } 1661 1662 if (state.isVerificationComplete()) { 1663 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1664 } else { 1665 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1666 "IntentFilter verification with token:" + verificationId 1667 + " was not said to be complete"); 1668 } 1669 1670 break; 1671 } 1672 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1673 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1674 mEphemeralResolverConnection, 1675 (EphemeralRequest) msg.obj, 1676 mEphemeralInstallerActivity, 1677 mHandler); 1678 } 1679 } 1680 } 1681 } 1682 1683 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1684 boolean killApp, String[] grantedPermissions, 1685 boolean launchedForRestore, String installerPackage, 1686 IPackageInstallObserver2 installObserver) { 1687 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1688 // Send the removed broadcasts 1689 if (res.removedInfo != null) { 1690 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1691 } 1692 1693 // Now that we successfully installed the package, grant runtime 1694 // permissions if requested before broadcasting the install. 1695 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1696 >= Build.VERSION_CODES.M) { 1697 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1698 } 1699 1700 final boolean update = res.removedInfo != null 1701 && res.removedInfo.removedPackage != null; 1702 1703 // If this is the first time we have child packages for a disabled privileged 1704 // app that had no children, we grant requested runtime permissions to the new 1705 // children if the parent on the system image had them already granted. 1706 if (res.pkg.parentPackage != null) { 1707 synchronized (mPackages) { 1708 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1709 } 1710 } 1711 1712 synchronized (mPackages) { 1713 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1714 } 1715 1716 final String packageName = res.pkg.applicationInfo.packageName; 1717 1718 // Determine the set of users who are adding this package for 1719 // the first time vs. those who are seeing an update. 1720 int[] firstUsers = EMPTY_INT_ARRAY; 1721 int[] updateUsers = EMPTY_INT_ARRAY; 1722 if (res.origUsers == null || res.origUsers.length == 0) { 1723 firstUsers = res.newUsers; 1724 } else { 1725 for (int newUser : res.newUsers) { 1726 boolean isNew = true; 1727 for (int origUser : res.origUsers) { 1728 if (origUser == newUser) { 1729 isNew = false; 1730 break; 1731 } 1732 } 1733 if (isNew) { 1734 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1735 } else { 1736 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1737 } 1738 } 1739 } 1740 1741 // Send installed broadcasts if the install/update is not ephemeral 1742 if (!isEphemeral(res.pkg)) { 1743 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1744 1745 // Send added for users that see the package for the first time 1746 // sendPackageAddedForNewUsers also deals with system apps 1747 int appId = UserHandle.getAppId(res.uid); 1748 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1749 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1750 1751 // Send added for users that don't see the package for the first time 1752 Bundle extras = new Bundle(1); 1753 extras.putInt(Intent.EXTRA_UID, res.uid); 1754 if (update) { 1755 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1756 } 1757 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1758 extras, 0 /*flags*/, null /*targetPackage*/, 1759 null /*finishedReceiver*/, updateUsers); 1760 1761 // Send replaced for users that don't see the package for the first time 1762 if (update) { 1763 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1764 packageName, extras, 0 /*flags*/, 1765 null /*targetPackage*/, null /*finishedReceiver*/, 1766 updateUsers); 1767 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1768 null /*package*/, null /*extras*/, 0 /*flags*/, 1769 packageName /*targetPackage*/, 1770 null /*finishedReceiver*/, updateUsers); 1771 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1772 // First-install and we did a restore, so we're responsible for the 1773 // first-launch broadcast. 1774 if (DEBUG_BACKUP) { 1775 Slog.i(TAG, "Post-restore of " + packageName 1776 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1777 } 1778 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1779 } 1780 1781 // Send broadcast package appeared if forward locked/external for all users 1782 // treat asec-hosted packages like removable media on upgrade 1783 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1784 if (DEBUG_INSTALL) { 1785 Slog.i(TAG, "upgrading pkg " + res.pkg 1786 + " is ASEC-hosted -> AVAILABLE"); 1787 } 1788 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1789 ArrayList<String> pkgList = new ArrayList<>(1); 1790 pkgList.add(packageName); 1791 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1792 } 1793 } 1794 1795 // Work that needs to happen on first install within each user 1796 if (firstUsers != null && firstUsers.length > 0) { 1797 synchronized (mPackages) { 1798 for (int userId : firstUsers) { 1799 // If this app is a browser and it's newly-installed for some 1800 // users, clear any default-browser state in those users. The 1801 // app's nature doesn't depend on the user, so we can just check 1802 // its browser nature in any user and generalize. 1803 if (packageIsBrowser(packageName, userId)) { 1804 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1805 } 1806 1807 // We may also need to apply pending (restored) runtime 1808 // permission grants within these users. 1809 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1810 } 1811 } 1812 } 1813 1814 // Log current value of "unknown sources" setting 1815 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1816 getUnknownSourcesSettings()); 1817 1818 // Force a gc to clear up things 1819 Runtime.getRuntime().gc(); 1820 1821 // Remove the replaced package's older resources safely now 1822 // We delete after a gc for applications on sdcard. 1823 if (res.removedInfo != null && res.removedInfo.args != null) { 1824 synchronized (mInstallLock) { 1825 res.removedInfo.args.doPostDeleteLI(true); 1826 } 1827 } 1828 } 1829 1830 // If someone is watching installs - notify them 1831 if (installObserver != null) { 1832 try { 1833 Bundle extras = extrasForInstallResult(res); 1834 installObserver.onPackageInstalled(res.name, res.returnCode, 1835 res.returnMsg, extras); 1836 } catch (RemoteException e) { 1837 Slog.i(TAG, "Observer no longer exists."); 1838 } 1839 } 1840 } 1841 1842 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1843 PackageParser.Package pkg) { 1844 if (pkg.parentPackage == null) { 1845 return; 1846 } 1847 if (pkg.requestedPermissions == null) { 1848 return; 1849 } 1850 final PackageSetting disabledSysParentPs = mSettings 1851 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1852 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1853 || !disabledSysParentPs.isPrivileged() 1854 || (disabledSysParentPs.childPackageNames != null 1855 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1856 return; 1857 } 1858 final int[] allUserIds = sUserManager.getUserIds(); 1859 final int permCount = pkg.requestedPermissions.size(); 1860 for (int i = 0; i < permCount; i++) { 1861 String permission = pkg.requestedPermissions.get(i); 1862 BasePermission bp = mSettings.mPermissions.get(permission); 1863 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1864 continue; 1865 } 1866 for (int userId : allUserIds) { 1867 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1868 permission, userId)) { 1869 grantRuntimePermission(pkg.packageName, permission, userId); 1870 } 1871 } 1872 } 1873 } 1874 1875 private StorageEventListener mStorageListener = new StorageEventListener() { 1876 @Override 1877 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1878 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1879 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1880 final String volumeUuid = vol.getFsUuid(); 1881 1882 // Clean up any users or apps that were removed or recreated 1883 // while this volume was missing 1884 reconcileUsers(volumeUuid); 1885 reconcileApps(volumeUuid); 1886 1887 // Clean up any install sessions that expired or were 1888 // cancelled while this volume was missing 1889 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1890 1891 loadPrivatePackages(vol); 1892 1893 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1894 unloadPrivatePackages(vol); 1895 } 1896 } 1897 1898 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1899 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1900 updateExternalMediaStatus(true, false); 1901 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1902 updateExternalMediaStatus(false, false); 1903 } 1904 } 1905 } 1906 1907 @Override 1908 public void onVolumeForgotten(String fsUuid) { 1909 if (TextUtils.isEmpty(fsUuid)) { 1910 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1911 return; 1912 } 1913 1914 // Remove any apps installed on the forgotten volume 1915 synchronized (mPackages) { 1916 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1917 for (PackageSetting ps : packages) { 1918 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1919 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1920 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1921 1922 // Try very hard to release any references to this package 1923 // so we don't risk the system server being killed due to 1924 // open FDs 1925 AttributeCache.instance().removePackage(ps.name); 1926 } 1927 1928 mSettings.onVolumeForgotten(fsUuid); 1929 mSettings.writeLPr(); 1930 } 1931 } 1932 }; 1933 1934 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1935 String[] grantedPermissions) { 1936 for (int userId : userIds) { 1937 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1938 } 1939 1940 // We could have touched GID membership, so flush out packages.list 1941 synchronized (mPackages) { 1942 mSettings.writePackageListLPr(); 1943 } 1944 } 1945 1946 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1947 String[] grantedPermissions) { 1948 SettingBase sb = (SettingBase) pkg.mExtras; 1949 if (sb == null) { 1950 return; 1951 } 1952 1953 PermissionsState permissionsState = sb.getPermissionsState(); 1954 1955 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1956 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1957 1958 for (String permission : pkg.requestedPermissions) { 1959 final BasePermission bp; 1960 synchronized (mPackages) { 1961 bp = mSettings.mPermissions.get(permission); 1962 } 1963 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1964 && (grantedPermissions == null 1965 || ArrayUtils.contains(grantedPermissions, permission))) { 1966 final int flags = permissionsState.getPermissionFlags(permission, userId); 1967 // Installer cannot change immutable permissions. 1968 if ((flags & immutableFlags) == 0) { 1969 grantRuntimePermission(pkg.packageName, permission, userId); 1970 } 1971 } 1972 } 1973 } 1974 1975 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1976 Bundle extras = null; 1977 switch (res.returnCode) { 1978 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1979 extras = new Bundle(); 1980 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1981 res.origPermission); 1982 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1983 res.origPackage); 1984 break; 1985 } 1986 case PackageManager.INSTALL_SUCCEEDED: { 1987 extras = new Bundle(); 1988 extras.putBoolean(Intent.EXTRA_REPLACING, 1989 res.removedInfo != null && res.removedInfo.removedPackage != null); 1990 break; 1991 } 1992 } 1993 return extras; 1994 } 1995 1996 void scheduleWriteSettingsLocked() { 1997 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1998 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1999 } 2000 } 2001 2002 void scheduleWritePackageListLocked(int userId) { 2003 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2004 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2005 msg.arg1 = userId; 2006 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2007 } 2008 } 2009 2010 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2011 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2012 scheduleWritePackageRestrictionsLocked(userId); 2013 } 2014 2015 void scheduleWritePackageRestrictionsLocked(int userId) { 2016 final int[] userIds = (userId == UserHandle.USER_ALL) 2017 ? sUserManager.getUserIds() : new int[]{userId}; 2018 for (int nextUserId : userIds) { 2019 if (!sUserManager.exists(nextUserId)) return; 2020 mDirtyUsers.add(nextUserId); 2021 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2022 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2023 } 2024 } 2025 } 2026 2027 public static PackageManagerService main(Context context, Installer installer, 2028 boolean factoryTest, boolean onlyCore) { 2029 // Self-check for initial settings. 2030 PackageManagerServiceCompilerMapping.checkProperties(); 2031 2032 PackageManagerService m = new PackageManagerService(context, installer, 2033 factoryTest, onlyCore); 2034 m.enableSystemUserPackages(); 2035 ServiceManager.addService("package", m); 2036 return m; 2037 } 2038 2039 private void enableSystemUserPackages() { 2040 if (!UserManager.isSplitSystemUser()) { 2041 return; 2042 } 2043 // For system user, enable apps based on the following conditions: 2044 // - app is whitelisted or belong to one of these groups: 2045 // -- system app which has no launcher icons 2046 // -- system app which has INTERACT_ACROSS_USERS permission 2047 // -- system IME app 2048 // - app is not in the blacklist 2049 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2050 Set<String> enableApps = new ArraySet<>(); 2051 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2052 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2053 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2054 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2055 enableApps.addAll(wlApps); 2056 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2057 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2058 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2059 enableApps.removeAll(blApps); 2060 Log.i(TAG, "Applications installed for system user: " + enableApps); 2061 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2062 UserHandle.SYSTEM); 2063 final int allAppsSize = allAps.size(); 2064 synchronized (mPackages) { 2065 for (int i = 0; i < allAppsSize; i++) { 2066 String pName = allAps.get(i); 2067 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2068 // Should not happen, but we shouldn't be failing if it does 2069 if (pkgSetting == null) { 2070 continue; 2071 } 2072 boolean install = enableApps.contains(pName); 2073 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2074 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2075 + " for system user"); 2076 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2077 } 2078 } 2079 } 2080 } 2081 2082 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2083 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2084 Context.DISPLAY_SERVICE); 2085 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2086 } 2087 2088 /** 2089 * Requests that files preopted on a secondary system partition be copied to the data partition 2090 * if possible. Note that the actual copying of the files is accomplished by init for security 2091 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2092 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2093 */ 2094 private static void requestCopyPreoptedFiles() { 2095 final int WAIT_TIME_MS = 100; 2096 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2097 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2098 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2099 // We will wait for up to 100 seconds. 2100 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2101 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2102 try { 2103 Thread.sleep(WAIT_TIME_MS); 2104 } catch (InterruptedException e) { 2105 // Do nothing 2106 } 2107 if (SystemClock.uptimeMillis() > timeEnd) { 2108 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2109 Slog.wtf(TAG, "cppreopt did not finish!"); 2110 break; 2111 } 2112 } 2113 } 2114 } 2115 2116 public PackageManagerService(Context context, Installer installer, 2117 boolean factoryTest, boolean onlyCore) { 2118 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2119 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2120 SystemClock.uptimeMillis()); 2121 2122 if (mSdkVersion <= 0) { 2123 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2124 } 2125 2126 mContext = context; 2127 2128 mPermissionReviewRequired = context.getResources().getBoolean( 2129 R.bool.config_permissionReviewRequired); 2130 2131 mFactoryTest = factoryTest; 2132 mOnlyCore = onlyCore; 2133 mMetrics = new DisplayMetrics(); 2134 mSettings = new Settings(mPackages); 2135 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2136 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2137 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2138 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2139 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2140 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2141 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2142 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2143 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2144 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2145 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2146 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2147 2148 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2149 if (separateProcesses != null && separateProcesses.length() > 0) { 2150 if ("*".equals(separateProcesses)) { 2151 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2152 mSeparateProcesses = null; 2153 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2154 } else { 2155 mDefParseFlags = 0; 2156 mSeparateProcesses = separateProcesses.split(","); 2157 Slog.w(TAG, "Running with debug.separate_processes: " 2158 + separateProcesses); 2159 } 2160 } else { 2161 mDefParseFlags = 0; 2162 mSeparateProcesses = null; 2163 } 2164 2165 mInstaller = installer; 2166 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2167 "*dexopt*"); 2168 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2169 2170 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2171 FgThread.get().getLooper()); 2172 2173 getDefaultDisplayMetrics(context, mMetrics); 2174 2175 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2176 SystemConfig systemConfig = SystemConfig.getInstance(); 2177 mGlobalGids = systemConfig.getGlobalGids(); 2178 mSystemPermissions = systemConfig.getSystemPermissions(); 2179 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2181 2182 mProtectedPackages = new ProtectedPackages(mContext); 2183 2184 synchronized (mInstallLock) { 2185 // writer 2186 synchronized (mPackages) { 2187 mHandlerThread = new ServiceThread(TAG, 2188 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2189 mHandlerThread.start(); 2190 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2191 mProcessLoggingHandler = new ProcessLoggingHandler(); 2192 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2193 2194 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2195 2196 File dataDir = Environment.getDataDirectory(); 2197 mAppInstallDir = new File(dataDir, "app"); 2198 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2199 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2200 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2201 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2202 2203 sUserManager = new UserManagerService(context, this, mPackages); 2204 2205 // Propagate permission configuration in to package manager. 2206 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2207 = systemConfig.getPermissions(); 2208 for (int i=0; i<permConfig.size(); i++) { 2209 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2210 BasePermission bp = mSettings.mPermissions.get(perm.name); 2211 if (bp == null) { 2212 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2213 mSettings.mPermissions.put(perm.name, bp); 2214 } 2215 if (perm.gids != null) { 2216 bp.setGids(perm.gids, perm.perUser); 2217 } 2218 } 2219 2220 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2221 for (int i=0; i<libConfig.size(); i++) { 2222 mSharedLibraries.put(libConfig.keyAt(i), 2223 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2224 } 2225 2226 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2227 2228 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2229 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2230 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2231 2232 // Clean up orphaned packages for which the code path doesn't exist 2233 // and they are an update to a system app - caused by bug/32321269 2234 final int packageSettingCount = mSettings.mPackages.size(); 2235 for (int i = packageSettingCount - 1; i >= 0; i--) { 2236 PackageSetting ps = mSettings.mPackages.valueAt(i); 2237 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2238 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2239 mSettings.mPackages.removeAt(i); 2240 mSettings.enableSystemPackageLPw(ps.name); 2241 } 2242 } 2243 2244 if (mFirstBoot) { 2245 requestCopyPreoptedFiles(); 2246 } 2247 2248 String customResolverActivity = Resources.getSystem().getString( 2249 R.string.config_customResolverActivity); 2250 if (TextUtils.isEmpty(customResolverActivity)) { 2251 customResolverActivity = null; 2252 } else { 2253 mCustomResolverComponentName = ComponentName.unflattenFromString( 2254 customResolverActivity); 2255 } 2256 2257 long startTime = SystemClock.uptimeMillis(); 2258 2259 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2260 startTime); 2261 2262 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2263 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2264 2265 if (bootClassPath == null) { 2266 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2267 } 2268 2269 if (systemServerClassPath == null) { 2270 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2271 } 2272 2273 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2274 final String[] dexCodeInstructionSets = 2275 getDexCodeInstructionSets( 2276 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2277 2278 /** 2279 * Ensure all external libraries have had dexopt run on them. 2280 */ 2281 if (mSharedLibraries.size() > 0) { 2282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2283 // NOTE: For now, we're compiling these system "shared libraries" 2284 // (and framework jars) into all available architectures. It's possible 2285 // to compile them only when we come across an app that uses them (there's 2286 // already logic for that in scanPackageLI) but that adds some complexity. 2287 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2288 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2289 final String lib = libEntry.path; 2290 if (lib == null) { 2291 continue; 2292 } 2293 2294 try { 2295 // Shared libraries do not have profiles so we perform a full 2296 // AOT compilation (if needed). 2297 int dexoptNeeded = DexFile.getDexOptNeeded( 2298 lib, dexCodeInstructionSet, 2299 getCompilerFilterForReason(REASON_SHARED_APK), 2300 false /* newProfile */); 2301 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2302 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2303 dexCodeInstructionSet, dexoptNeeded, null, 2304 DEXOPT_PUBLIC, 2305 getCompilerFilterForReason(REASON_SHARED_APK), 2306 StorageManager.UUID_PRIVATE_INTERNAL, 2307 SKIP_SHARED_LIBRARY_CHECK); 2308 } 2309 } catch (FileNotFoundException e) { 2310 Slog.w(TAG, "Library not found: " + lib); 2311 } catch (IOException | InstallerException e) { 2312 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2313 + e.getMessage()); 2314 } 2315 } 2316 } 2317 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2318 } 2319 2320 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2321 2322 final VersionInfo ver = mSettings.getInternalVersion(); 2323 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2324 2325 // when upgrading from pre-M, promote system app permissions from install to runtime 2326 mPromoteSystemApps = 2327 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2328 2329 // When upgrading from pre-N, we need to handle package extraction like first boot, 2330 // as there is no profiling data available. 2331 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2332 2333 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2334 2335 // save off the names of pre-existing system packages prior to scanning; we don't 2336 // want to automatically grant runtime permissions for new system apps 2337 if (mPromoteSystemApps) { 2338 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2339 while (pkgSettingIter.hasNext()) { 2340 PackageSetting ps = pkgSettingIter.next(); 2341 if (isSystemApp(ps)) { 2342 mExistingSystemPackages.add(ps.name); 2343 } 2344 } 2345 } 2346 2347 // Set flag to monitor and not change apk file paths when 2348 // scanning install directories. 2349 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2350 2351 if (mIsUpgrade || mFirstBoot) { 2352 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2353 } 2354 2355 // Collect vendor overlay packages. (Do this before scanning any apps.) 2356 // For security and version matching reason, only consider 2357 // overlay packages if they reside in the right directory. 2358 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2359 if (overlayThemeDir.isEmpty()) { 2360 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2361 } 2362 if (!overlayThemeDir.isEmpty()) { 2363 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2364 | PackageParser.PARSE_IS_SYSTEM 2365 | PackageParser.PARSE_IS_SYSTEM_DIR 2366 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2367 } 2368 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2369 | PackageParser.PARSE_IS_SYSTEM 2370 | PackageParser.PARSE_IS_SYSTEM_DIR 2371 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2372 2373 // Find base frameworks (resource packages without code). 2374 scanDirTracedLI(frameworkDir, mDefParseFlags 2375 | PackageParser.PARSE_IS_SYSTEM 2376 | PackageParser.PARSE_IS_SYSTEM_DIR 2377 | PackageParser.PARSE_IS_PRIVILEGED, 2378 scanFlags | SCAN_NO_DEX, 0); 2379 2380 // Collected privileged system packages. 2381 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2382 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2383 | PackageParser.PARSE_IS_SYSTEM 2384 | PackageParser.PARSE_IS_SYSTEM_DIR 2385 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2386 2387 // Collect ordinary system packages. 2388 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2389 scanDirTracedLI(systemAppDir, mDefParseFlags 2390 | PackageParser.PARSE_IS_SYSTEM 2391 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2392 2393 // Collect all vendor packages. 2394 File vendorAppDir = new File("/vendor/app"); 2395 try { 2396 vendorAppDir = vendorAppDir.getCanonicalFile(); 2397 } catch (IOException e) { 2398 // failed to look up canonical path, continue with original one 2399 } 2400 scanDirTracedLI(vendorAppDir, mDefParseFlags 2401 | PackageParser.PARSE_IS_SYSTEM 2402 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2403 2404 // Collect all OEM packages. 2405 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2406 scanDirTracedLI(oemAppDir, mDefParseFlags 2407 | PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2409 2410 // Prune any system packages that no longer exist. 2411 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2412 if (!mOnlyCore) { 2413 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2414 while (psit.hasNext()) { 2415 PackageSetting ps = psit.next(); 2416 2417 /* 2418 * If this is not a system app, it can't be a 2419 * disable system app. 2420 */ 2421 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2422 continue; 2423 } 2424 2425 /* 2426 * If the package is scanned, it's not erased. 2427 */ 2428 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2429 if (scannedPkg != null) { 2430 /* 2431 * If the system app is both scanned and in the 2432 * disabled packages list, then it must have been 2433 * added via OTA. Remove it from the currently 2434 * scanned package so the previously user-installed 2435 * application can be scanned. 2436 */ 2437 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2438 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2439 + ps.name + "; removing system app. Last known codePath=" 2440 + ps.codePathString + ", installStatus=" + ps.installStatus 2441 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2442 + scannedPkg.mVersionCode); 2443 removePackageLI(scannedPkg, true); 2444 mExpectingBetter.put(ps.name, ps.codePath); 2445 } 2446 2447 continue; 2448 } 2449 2450 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2451 psit.remove(); 2452 logCriticalInfo(Log.WARN, "System package " + ps.name 2453 + " no longer exists; it's data will be wiped"); 2454 // Actual deletion of code and data will be handled by later 2455 // reconciliation step 2456 } else { 2457 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2458 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2459 possiblyDeletedUpdatedSystemApps.add(ps.name); 2460 } 2461 } 2462 } 2463 } 2464 2465 //look for any incomplete package installations 2466 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2467 for (int i = 0; i < deletePkgsList.size(); i++) { 2468 // Actual deletion of code and data will be handled by later 2469 // reconciliation step 2470 final String packageName = deletePkgsList.get(i).name; 2471 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2472 synchronized (mPackages) { 2473 mSettings.removePackageLPw(packageName); 2474 } 2475 } 2476 2477 //delete tmp files 2478 deleteTempPackageFiles(); 2479 2480 // Remove any shared userIDs that have no associated packages 2481 mSettings.pruneSharedUsersLPw(); 2482 2483 if (!mOnlyCore) { 2484 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2485 SystemClock.uptimeMillis()); 2486 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2487 2488 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2489 | PackageParser.PARSE_FORWARD_LOCK, 2490 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2491 2492 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2493 | PackageParser.PARSE_IS_EPHEMERAL, 2494 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2495 2496 /** 2497 * Remove disable package settings for any updated system 2498 * apps that were removed via an OTA. If they're not a 2499 * previously-updated app, remove them completely. 2500 * Otherwise, just revoke their system-level permissions. 2501 */ 2502 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2503 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2504 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2505 2506 String msg; 2507 if (deletedPkg == null) { 2508 msg = "Updated system package " + deletedAppName 2509 + " no longer exists; it's data will be wiped"; 2510 // Actual deletion of code and data will be handled by later 2511 // reconciliation step 2512 } else { 2513 msg = "Updated system app + " + deletedAppName 2514 + " no longer present; removing system privileges for " 2515 + deletedAppName; 2516 2517 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2518 2519 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2520 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2521 } 2522 logCriticalInfo(Log.WARN, msg); 2523 } 2524 2525 /** 2526 * Make sure all system apps that we expected to appear on 2527 * the userdata partition actually showed up. If they never 2528 * appeared, crawl back and revive the system version. 2529 */ 2530 for (int i = 0; i < mExpectingBetter.size(); i++) { 2531 final String packageName = mExpectingBetter.keyAt(i); 2532 if (!mPackages.containsKey(packageName)) { 2533 final File scanFile = mExpectingBetter.valueAt(i); 2534 2535 logCriticalInfo(Log.WARN, "Expected better " + packageName 2536 + " but never showed up; reverting to system"); 2537 2538 int reparseFlags = mDefParseFlags; 2539 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2540 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2541 | PackageParser.PARSE_IS_SYSTEM_DIR 2542 | PackageParser.PARSE_IS_PRIVILEGED; 2543 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2544 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2545 | PackageParser.PARSE_IS_SYSTEM_DIR; 2546 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2547 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2548 | PackageParser.PARSE_IS_SYSTEM_DIR; 2549 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2550 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2551 | PackageParser.PARSE_IS_SYSTEM_DIR; 2552 } else { 2553 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2554 continue; 2555 } 2556 2557 mSettings.enableSystemPackageLPw(packageName); 2558 2559 try { 2560 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2561 } catch (PackageManagerException e) { 2562 Slog.e(TAG, "Failed to parse original system package: " 2563 + e.getMessage()); 2564 } 2565 } 2566 } 2567 } 2568 mExpectingBetter.clear(); 2569 2570 // Resolve the storage manager. 2571 mStorageManagerPackage = getStorageManagerPackageName(); 2572 2573 // Resolve protected action filters. Only the setup wizard is allowed to 2574 // have a high priority filter for these actions. 2575 mSetupWizardPackage = getSetupWizardPackageName(); 2576 if (mProtectedFilters.size() > 0) { 2577 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2578 Slog.i(TAG, "No setup wizard;" 2579 + " All protected intents capped to priority 0"); 2580 } 2581 for (ActivityIntentInfo filter : mProtectedFilters) { 2582 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2583 if (DEBUG_FILTERS) { 2584 Slog.i(TAG, "Found setup wizard;" 2585 + " allow priority " + filter.getPriority() + ";" 2586 + " package: " + filter.activity.info.packageName 2587 + " activity: " + filter.activity.className 2588 + " priority: " + filter.getPriority()); 2589 } 2590 // skip setup wizard; allow it to keep the high priority filter 2591 continue; 2592 } 2593 Slog.w(TAG, "Protected action; cap priority to 0;" 2594 + " package: " + filter.activity.info.packageName 2595 + " activity: " + filter.activity.className 2596 + " origPrio: " + filter.getPriority()); 2597 filter.setPriority(0); 2598 } 2599 } 2600 mDeferProtectedFilters = false; 2601 mProtectedFilters.clear(); 2602 2603 // Now that we know all of the shared libraries, update all clients to have 2604 // the correct library paths. 2605 updateAllSharedLibrariesLPw(); 2606 2607 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2608 // NOTE: We ignore potential failures here during a system scan (like 2609 // the rest of the commands above) because there's precious little we 2610 // can do about it. A settings error is reported, though. 2611 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2612 } 2613 2614 // Now that we know all the packages we are keeping, 2615 // read and update their last usage times. 2616 mPackageUsage.read(mPackages); 2617 mCompilerStats.read(); 2618 2619 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2620 SystemClock.uptimeMillis()); 2621 Slog.i(TAG, "Time to scan packages: " 2622 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2623 + " seconds"); 2624 2625 // If the platform SDK has changed since the last time we booted, 2626 // we need to re-grant app permission to catch any new ones that 2627 // appear. This is really a hack, and means that apps can in some 2628 // cases get permissions that the user didn't initially explicitly 2629 // allow... it would be nice to have some better way to handle 2630 // this situation. 2631 int updateFlags = UPDATE_PERMISSIONS_ALL; 2632 if (ver.sdkVersion != mSdkVersion) { 2633 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2634 + mSdkVersion + "; regranting permissions for internal storage"); 2635 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2636 } 2637 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2638 ver.sdkVersion = mSdkVersion; 2639 2640 // If this is the first boot or an update from pre-M, and it is a normal 2641 // boot, then we need to initialize the default preferred apps across 2642 // all defined users. 2643 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2644 for (UserInfo user : sUserManager.getUsers(true)) { 2645 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2646 applyFactoryDefaultBrowserLPw(user.id); 2647 primeDomainVerificationsLPw(user.id); 2648 } 2649 } 2650 2651 // Prepare storage for system user really early during boot, 2652 // since core system apps like SettingsProvider and SystemUI 2653 // can't wait for user to start 2654 final int storageFlags; 2655 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2656 storageFlags = StorageManager.FLAG_STORAGE_DE; 2657 } else { 2658 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2659 } 2660 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2661 storageFlags, true /* migrateAppData */); 2662 2663 // If this is first boot after an OTA, and a normal boot, then 2664 // we need to clear code cache directories. 2665 // Note that we do *not* clear the application profiles. These remain valid 2666 // across OTAs and are used to drive profile verification (post OTA) and 2667 // profile compilation (without waiting to collect a fresh set of profiles). 2668 if (mIsUpgrade && !onlyCore) { 2669 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2670 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2671 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2672 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2673 // No apps are running this early, so no need to freeze 2674 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2675 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2676 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2677 } 2678 } 2679 ver.fingerprint = Build.FINGERPRINT; 2680 } 2681 2682 checkDefaultBrowser(); 2683 2684 // clear only after permissions and other defaults have been updated 2685 mExistingSystemPackages.clear(); 2686 mPromoteSystemApps = false; 2687 2688 // All the changes are done during package scanning. 2689 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2690 2691 // can downgrade to reader 2692 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2693 mSettings.writeLPr(); 2694 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2695 2696 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2697 // early on (before the package manager declares itself as early) because other 2698 // components in the system server might ask for package contexts for these apps. 2699 // 2700 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2701 // (i.e, that the data partition is unavailable). 2702 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2703 long start = System.nanoTime(); 2704 List<PackageParser.Package> coreApps = new ArrayList<>(); 2705 for (PackageParser.Package pkg : mPackages.values()) { 2706 if (pkg.coreApp) { 2707 coreApps.add(pkg); 2708 } 2709 } 2710 2711 int[] stats = performDexOptUpgrade(coreApps, false, 2712 getCompilerFilterForReason(REASON_CORE_APP)); 2713 2714 final int elapsedTimeSeconds = 2715 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2716 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2717 2718 if (DEBUG_DEXOPT) { 2719 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2720 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2721 } 2722 2723 2724 // TODO: Should we log these stats to tron too ? 2725 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2726 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2727 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2728 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2729 } 2730 2731 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2732 SystemClock.uptimeMillis()); 2733 2734 if (!mOnlyCore) { 2735 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2736 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2737 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2738 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2739 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2740 mIntentFilterVerifierComponent); 2741 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2742 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2743 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2744 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2745 } else { 2746 mRequiredVerifierPackage = null; 2747 mRequiredInstallerPackage = null; 2748 mRequiredUninstallerPackage = null; 2749 mIntentFilterVerifierComponent = null; 2750 mIntentFilterVerifier = null; 2751 mServicesSystemSharedLibraryPackageName = null; 2752 mSharedSystemSharedLibraryPackageName = null; 2753 } 2754 2755 mInstallerService = new PackageInstallerService(context, this); 2756 2757 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2758 if (ephemeralResolverComponent != null) { 2759 if (DEBUG_EPHEMERAL) { 2760 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2761 } 2762 mEphemeralResolverConnection = 2763 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2764 } else { 2765 mEphemeralResolverConnection = null; 2766 } 2767 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2768 if (mEphemeralInstallerComponent != null) { 2769 if (DEBUG_EPHEMERAL) { 2770 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2771 } 2772 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2773 } 2774 2775 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2776 } // synchronized (mPackages) 2777 } // synchronized (mInstallLock) 2778 2779 // Now after opening every single application zip, make sure they 2780 // are all flushed. Not really needed, but keeps things nice and 2781 // tidy. 2782 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2783 Runtime.getRuntime().gc(); 2784 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2785 2786 // The initial scanning above does many calls into installd while 2787 // holding the mPackages lock, but we're mostly interested in yelling 2788 // once we have a booted system. 2789 mInstaller.setWarnIfHeld(mPackages); 2790 2791 // Expose private service for system components to use. 2792 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2793 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2794 } 2795 2796 @Override 2797 public boolean isFirstBoot() { 2798 return mFirstBoot; 2799 } 2800 2801 @Override 2802 public boolean isOnlyCoreApps() { 2803 return mOnlyCore; 2804 } 2805 2806 @Override 2807 public boolean isUpgrade() { 2808 return mIsUpgrade; 2809 } 2810 2811 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2812 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2813 2814 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2815 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2816 UserHandle.USER_SYSTEM); 2817 if (matches.size() == 1) { 2818 return matches.get(0).getComponentInfo().packageName; 2819 } else if (matches.size() == 0) { 2820 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2821 return null; 2822 } 2823 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2824 } 2825 2826 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2827 synchronized (mPackages) { 2828 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2829 if (libraryEntry == null) { 2830 throw new IllegalStateException("Missing required shared library:" + libraryName); 2831 } 2832 return libraryEntry.apk; 2833 } 2834 } 2835 2836 private @NonNull String getRequiredInstallerLPr() { 2837 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2838 intent.addCategory(Intent.CATEGORY_DEFAULT); 2839 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2840 2841 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2842 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2843 UserHandle.USER_SYSTEM); 2844 if (matches.size() == 1) { 2845 ResolveInfo resolveInfo = matches.get(0); 2846 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2847 throw new RuntimeException("The installer must be a privileged app"); 2848 } 2849 return matches.get(0).getComponentInfo().packageName; 2850 } else { 2851 throw new RuntimeException("There must be exactly one installer; found " + matches); 2852 } 2853 } 2854 2855 private @NonNull String getRequiredUninstallerLPr() { 2856 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2857 intent.addCategory(Intent.CATEGORY_DEFAULT); 2858 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2859 2860 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2861 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2862 UserHandle.USER_SYSTEM); 2863 if (resolveInfo == null || 2864 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2865 throw new RuntimeException("There must be exactly one uninstaller; found " 2866 + resolveInfo); 2867 } 2868 return resolveInfo.getComponentInfo().packageName; 2869 } 2870 2871 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2872 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2873 2874 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2875 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2876 UserHandle.USER_SYSTEM); 2877 ResolveInfo best = null; 2878 final int N = matches.size(); 2879 for (int i = 0; i < N; i++) { 2880 final ResolveInfo cur = matches.get(i); 2881 final String packageName = cur.getComponentInfo().packageName; 2882 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2883 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2884 continue; 2885 } 2886 2887 if (best == null || cur.priority > best.priority) { 2888 best = cur; 2889 } 2890 } 2891 2892 if (best != null) { 2893 return best.getComponentInfo().getComponentName(); 2894 } else { 2895 throw new RuntimeException("There must be at least one intent filter verifier"); 2896 } 2897 } 2898 2899 private @Nullable ComponentName getEphemeralResolverLPr() { 2900 final String[] packageArray = 2901 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2902 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2903 if (DEBUG_EPHEMERAL) { 2904 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2905 } 2906 return null; 2907 } 2908 2909 final int resolveFlags = 2910 MATCH_DIRECT_BOOT_AWARE 2911 | MATCH_DIRECT_BOOT_UNAWARE 2912 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2913 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2914 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2915 resolveFlags, UserHandle.USER_SYSTEM); 2916 2917 final int N = resolvers.size(); 2918 if (N == 0) { 2919 if (DEBUG_EPHEMERAL) { 2920 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2921 } 2922 return null; 2923 } 2924 2925 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2926 for (int i = 0; i < N; i++) { 2927 final ResolveInfo info = resolvers.get(i); 2928 2929 if (info.serviceInfo == null) { 2930 continue; 2931 } 2932 2933 final String packageName = info.serviceInfo.packageName; 2934 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2935 if (DEBUG_EPHEMERAL) { 2936 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2937 + " pkg: " + packageName + ", info:" + info); 2938 } 2939 continue; 2940 } 2941 2942 if (DEBUG_EPHEMERAL) { 2943 Slog.v(TAG, "Ephemeral resolver found;" 2944 + " pkg: " + packageName + ", info:" + info); 2945 } 2946 return new ComponentName(packageName, info.serviceInfo.name); 2947 } 2948 if (DEBUG_EPHEMERAL) { 2949 Slog.v(TAG, "Ephemeral resolver NOT found"); 2950 } 2951 return null; 2952 } 2953 2954 private @Nullable ComponentName getEphemeralInstallerLPr() { 2955 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2956 intent.addCategory(Intent.CATEGORY_DEFAULT); 2957 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2958 2959 final int resolveFlags = 2960 MATCH_DIRECT_BOOT_AWARE 2961 | MATCH_DIRECT_BOOT_UNAWARE 2962 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2963 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2964 resolveFlags, UserHandle.USER_SYSTEM); 2965 Iterator<ResolveInfo> iter = matches.iterator(); 2966 while (iter.hasNext()) { 2967 final ResolveInfo rInfo = iter.next(); 2968 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 2969 if (ps != null) { 2970 final PermissionsState permissionsState = ps.getPermissionsState(); 2971 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 2972 continue; 2973 } 2974 } 2975 iter.remove(); 2976 } 2977 if (matches.size() == 0) { 2978 return null; 2979 } else if (matches.size() == 1) { 2980 return matches.get(0).getComponentInfo().getComponentName(); 2981 } else { 2982 throw new RuntimeException( 2983 "There must be at most one ephemeral installer; found " + matches); 2984 } 2985 } 2986 2987 private void primeDomainVerificationsLPw(int userId) { 2988 if (DEBUG_DOMAIN_VERIFICATION) { 2989 Slog.d(TAG, "Priming domain verifications in user " + userId); 2990 } 2991 2992 SystemConfig systemConfig = SystemConfig.getInstance(); 2993 ArraySet<String> packages = systemConfig.getLinkedApps(); 2994 2995 for (String packageName : packages) { 2996 PackageParser.Package pkg = mPackages.get(packageName); 2997 if (pkg != null) { 2998 if (!pkg.isSystemApp()) { 2999 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3000 continue; 3001 } 3002 3003 ArraySet<String> domains = null; 3004 for (PackageParser.Activity a : pkg.activities) { 3005 for (ActivityIntentInfo filter : a.intents) { 3006 if (hasValidDomains(filter)) { 3007 if (domains == null) { 3008 domains = new ArraySet<String>(); 3009 } 3010 domains.addAll(filter.getHostsList()); 3011 } 3012 } 3013 } 3014 3015 if (domains != null && domains.size() > 0) { 3016 if (DEBUG_DOMAIN_VERIFICATION) { 3017 Slog.v(TAG, " + " + packageName); 3018 } 3019 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3020 // state w.r.t. the formal app-linkage "no verification attempted" state; 3021 // and then 'always' in the per-user state actually used for intent resolution. 3022 final IntentFilterVerificationInfo ivi; 3023 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3024 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3025 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3026 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3027 } else { 3028 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3029 + "' does not handle web links"); 3030 } 3031 } else { 3032 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3033 } 3034 } 3035 3036 scheduleWritePackageRestrictionsLocked(userId); 3037 scheduleWriteSettingsLocked(); 3038 } 3039 3040 private void applyFactoryDefaultBrowserLPw(int userId) { 3041 // The default browser app's package name is stored in a string resource, 3042 // with a product-specific overlay used for vendor customization. 3043 String browserPkg = mContext.getResources().getString( 3044 com.android.internal.R.string.default_browser); 3045 if (!TextUtils.isEmpty(browserPkg)) { 3046 // non-empty string => required to be a known package 3047 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3048 if (ps == null) { 3049 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3050 browserPkg = null; 3051 } else { 3052 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3053 } 3054 } 3055 3056 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3057 // default. If there's more than one, just leave everything alone. 3058 if (browserPkg == null) { 3059 calculateDefaultBrowserLPw(userId); 3060 } 3061 } 3062 3063 private void calculateDefaultBrowserLPw(int userId) { 3064 List<String> allBrowsers = resolveAllBrowserApps(userId); 3065 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3066 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3067 } 3068 3069 private List<String> resolveAllBrowserApps(int userId) { 3070 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3071 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3072 PackageManager.MATCH_ALL, userId); 3073 3074 final int count = list.size(); 3075 List<String> result = new ArrayList<String>(count); 3076 for (int i=0; i<count; i++) { 3077 ResolveInfo info = list.get(i); 3078 if (info.activityInfo == null 3079 || !info.handleAllWebDataURI 3080 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3081 || result.contains(info.activityInfo.packageName)) { 3082 continue; 3083 } 3084 result.add(info.activityInfo.packageName); 3085 } 3086 3087 return result; 3088 } 3089 3090 private boolean packageIsBrowser(String packageName, int userId) { 3091 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3092 PackageManager.MATCH_ALL, userId); 3093 final int N = list.size(); 3094 for (int i = 0; i < N; i++) { 3095 ResolveInfo info = list.get(i); 3096 if (packageName.equals(info.activityInfo.packageName)) { 3097 return true; 3098 } 3099 } 3100 return false; 3101 } 3102 3103 private void checkDefaultBrowser() { 3104 final int myUserId = UserHandle.myUserId(); 3105 final String packageName = getDefaultBrowserPackageName(myUserId); 3106 if (packageName != null) { 3107 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3108 if (info == null) { 3109 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3110 synchronized (mPackages) { 3111 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3112 } 3113 } 3114 } 3115 } 3116 3117 @Override 3118 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3119 throws RemoteException { 3120 try { 3121 return super.onTransact(code, data, reply, flags); 3122 } catch (RuntimeException e) { 3123 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3124 Slog.wtf(TAG, "Package Manager Crash", e); 3125 } 3126 throw e; 3127 } 3128 } 3129 3130 static int[] appendInts(int[] cur, int[] add) { 3131 if (add == null) return cur; 3132 if (cur == null) return add; 3133 final int N = add.length; 3134 for (int i=0; i<N; i++) { 3135 cur = appendInt(cur, add[i]); 3136 } 3137 return cur; 3138 } 3139 3140 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3141 if (!sUserManager.exists(userId)) return null; 3142 if (ps == null) { 3143 return null; 3144 } 3145 final PackageParser.Package p = ps.pkg; 3146 if (p == null) { 3147 return null; 3148 } 3149 3150 final PermissionsState permissionsState = ps.getPermissionsState(); 3151 3152 // Compute GIDs only if requested 3153 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3154 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3155 // Compute granted permissions only if package has requested permissions 3156 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3157 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3158 final PackageUserState state = ps.readUserState(userId); 3159 3160 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3161 && ps.isSystem()) { 3162 flags |= MATCH_ANY_USER; 3163 } 3164 3165 return PackageParser.generatePackageInfo(p, gids, flags, 3166 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3167 } 3168 3169 @Override 3170 public void checkPackageStartable(String packageName, int userId) { 3171 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3172 3173 synchronized (mPackages) { 3174 final PackageSetting ps = mSettings.mPackages.get(packageName); 3175 if (ps == null) { 3176 throw new SecurityException("Package " + packageName + " was not found!"); 3177 } 3178 3179 if (!ps.getInstalled(userId)) { 3180 throw new SecurityException( 3181 "Package " + packageName + " was not installed for user " + userId + "!"); 3182 } 3183 3184 if (mSafeMode && !ps.isSystem()) { 3185 throw new SecurityException("Package " + packageName + " not a system app!"); 3186 } 3187 3188 if (mFrozenPackages.contains(packageName)) { 3189 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3190 } 3191 3192 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3193 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3194 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3195 } 3196 } 3197 } 3198 3199 @Override 3200 public boolean isPackageAvailable(String packageName, int userId) { 3201 if (!sUserManager.exists(userId)) return false; 3202 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3203 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3204 synchronized (mPackages) { 3205 PackageParser.Package p = mPackages.get(packageName); 3206 if (p != null) { 3207 final PackageSetting ps = (PackageSetting) p.mExtras; 3208 if (ps != null) { 3209 final PackageUserState state = ps.readUserState(userId); 3210 if (state != null) { 3211 return PackageParser.isAvailable(state); 3212 } 3213 } 3214 } 3215 } 3216 return false; 3217 } 3218 3219 @Override 3220 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3221 if (!sUserManager.exists(userId)) return null; 3222 flags = updateFlagsForPackage(flags, userId, packageName); 3223 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3224 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3225 3226 // reader 3227 synchronized (mPackages) { 3228 // Normalize package name to hanlde renamed packages 3229 packageName = normalizePackageNameLPr(packageName); 3230 3231 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3232 PackageParser.Package p = null; 3233 if (matchFactoryOnly) { 3234 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3235 if (ps != null) { 3236 return generatePackageInfo(ps, flags, userId); 3237 } 3238 } 3239 if (p == null) { 3240 p = mPackages.get(packageName); 3241 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3242 return null; 3243 } 3244 } 3245 if (DEBUG_PACKAGE_INFO) 3246 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3247 if (p != null) { 3248 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3249 } 3250 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3251 final PackageSetting ps = mSettings.mPackages.get(packageName); 3252 return generatePackageInfo(ps, flags, userId); 3253 } 3254 } 3255 return null; 3256 } 3257 3258 @Override 3259 public String[] currentToCanonicalPackageNames(String[] names) { 3260 String[] out = new String[names.length]; 3261 // reader 3262 synchronized (mPackages) { 3263 for (int i=names.length-1; i>=0; i--) { 3264 PackageSetting ps = mSettings.mPackages.get(names[i]); 3265 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3266 } 3267 } 3268 return out; 3269 } 3270 3271 @Override 3272 public String[] canonicalToCurrentPackageNames(String[] names) { 3273 String[] out = new String[names.length]; 3274 // reader 3275 synchronized (mPackages) { 3276 for (int i=names.length-1; i>=0; i--) { 3277 String cur = mSettings.getRenamedPackageLPr(names[i]); 3278 out[i] = cur != null ? cur : names[i]; 3279 } 3280 } 3281 return out; 3282 } 3283 3284 @Override 3285 public int getPackageUid(String packageName, int flags, int userId) { 3286 if (!sUserManager.exists(userId)) return -1; 3287 flags = updateFlagsForPackage(flags, userId, packageName); 3288 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3289 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3290 3291 // reader 3292 synchronized (mPackages) { 3293 final PackageParser.Package p = mPackages.get(packageName); 3294 if (p != null && p.isMatch(flags)) { 3295 return UserHandle.getUid(userId, p.applicationInfo.uid); 3296 } 3297 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3298 final PackageSetting ps = mSettings.mPackages.get(packageName); 3299 if (ps != null && ps.isMatch(flags)) { 3300 return UserHandle.getUid(userId, ps.appId); 3301 } 3302 } 3303 } 3304 3305 return -1; 3306 } 3307 3308 @Override 3309 public int[] getPackageGids(String packageName, int flags, int userId) { 3310 if (!sUserManager.exists(userId)) return null; 3311 flags = updateFlagsForPackage(flags, userId, packageName); 3312 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3313 false /* requireFullPermission */, false /* checkShell */, 3314 "getPackageGids"); 3315 3316 // reader 3317 synchronized (mPackages) { 3318 final PackageParser.Package p = mPackages.get(packageName); 3319 if (p != null && p.isMatch(flags)) { 3320 PackageSetting ps = (PackageSetting) p.mExtras; 3321 // TODO: Shouldn't this be checking for package installed state for userId and 3322 // return null? 3323 return ps.getPermissionsState().computeGids(userId); 3324 } 3325 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3326 final PackageSetting ps = mSettings.mPackages.get(packageName); 3327 if (ps != null && ps.isMatch(flags)) { 3328 return ps.getPermissionsState().computeGids(userId); 3329 } 3330 } 3331 } 3332 3333 return null; 3334 } 3335 3336 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3337 if (bp.perm != null) { 3338 return PackageParser.generatePermissionInfo(bp.perm, flags); 3339 } 3340 PermissionInfo pi = new PermissionInfo(); 3341 pi.name = bp.name; 3342 pi.packageName = bp.sourcePackage; 3343 pi.nonLocalizedLabel = bp.name; 3344 pi.protectionLevel = bp.protectionLevel; 3345 return pi; 3346 } 3347 3348 @Override 3349 public PermissionInfo getPermissionInfo(String name, int flags) { 3350 // reader 3351 synchronized (mPackages) { 3352 final BasePermission p = mSettings.mPermissions.get(name); 3353 if (p != null) { 3354 return generatePermissionInfo(p, flags); 3355 } 3356 return null; 3357 } 3358 } 3359 3360 @Override 3361 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3362 int flags) { 3363 // reader 3364 synchronized (mPackages) { 3365 if (group != null && !mPermissionGroups.containsKey(group)) { 3366 // This is thrown as NameNotFoundException 3367 return null; 3368 } 3369 3370 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3371 for (BasePermission p : mSettings.mPermissions.values()) { 3372 if (group == null) { 3373 if (p.perm == null || p.perm.info.group == null) { 3374 out.add(generatePermissionInfo(p, flags)); 3375 } 3376 } else { 3377 if (p.perm != null && group.equals(p.perm.info.group)) { 3378 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3379 } 3380 } 3381 } 3382 return new ParceledListSlice<>(out); 3383 } 3384 } 3385 3386 @Override 3387 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3388 // reader 3389 synchronized (mPackages) { 3390 return PackageParser.generatePermissionGroupInfo( 3391 mPermissionGroups.get(name), flags); 3392 } 3393 } 3394 3395 @Override 3396 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3397 // reader 3398 synchronized (mPackages) { 3399 final int N = mPermissionGroups.size(); 3400 ArrayList<PermissionGroupInfo> out 3401 = new ArrayList<PermissionGroupInfo>(N); 3402 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3403 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3404 } 3405 return new ParceledListSlice<>(out); 3406 } 3407 } 3408 3409 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3410 int userId) { 3411 if (!sUserManager.exists(userId)) return null; 3412 PackageSetting ps = mSettings.mPackages.get(packageName); 3413 if (ps != null) { 3414 if (ps.pkg == null) { 3415 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3416 if (pInfo != null) { 3417 return pInfo.applicationInfo; 3418 } 3419 return null; 3420 } 3421 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3422 ps.readUserState(userId), userId); 3423 } 3424 return null; 3425 } 3426 3427 @Override 3428 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3429 if (!sUserManager.exists(userId)) return null; 3430 flags = updateFlagsForApplication(flags, userId, packageName); 3431 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3432 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3433 3434 // writer 3435 synchronized (mPackages) { 3436 // Normalize package name to hanlde renamed packages 3437 packageName = normalizePackageNameLPr(packageName); 3438 3439 PackageParser.Package p = mPackages.get(packageName); 3440 if (DEBUG_PACKAGE_INFO) Log.v( 3441 TAG, "getApplicationInfo " + packageName 3442 + ": " + p); 3443 if (p != null) { 3444 PackageSetting ps = mSettings.mPackages.get(packageName); 3445 if (ps == null) return null; 3446 // Note: isEnabledLP() does not apply here - always return info 3447 return PackageParser.generateApplicationInfo( 3448 p, flags, ps.readUserState(userId), userId); 3449 } 3450 if ("android".equals(packageName)||"system".equals(packageName)) { 3451 return mAndroidApplication; 3452 } 3453 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3454 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3455 } 3456 } 3457 return null; 3458 } 3459 3460 private String normalizePackageNameLPr(String packageName) { 3461 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3462 return normalizedPackageName != null ? normalizedPackageName : packageName; 3463 } 3464 3465 @Override 3466 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3467 final IPackageDataObserver observer) { 3468 mContext.enforceCallingOrSelfPermission( 3469 android.Manifest.permission.CLEAR_APP_CACHE, null); 3470 // Queue up an async operation since clearing cache may take a little while. 3471 mHandler.post(new Runnable() { 3472 public void run() { 3473 mHandler.removeCallbacks(this); 3474 boolean success = true; 3475 synchronized (mInstallLock) { 3476 try { 3477 mInstaller.freeCache(volumeUuid, freeStorageSize); 3478 } catch (InstallerException e) { 3479 Slog.w(TAG, "Couldn't clear application caches: " + e); 3480 success = false; 3481 } 3482 } 3483 if (observer != null) { 3484 try { 3485 observer.onRemoveCompleted(null, success); 3486 } catch (RemoteException e) { 3487 Slog.w(TAG, "RemoveException when invoking call back"); 3488 } 3489 } 3490 } 3491 }); 3492 } 3493 3494 @Override 3495 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3496 final IntentSender pi) { 3497 mContext.enforceCallingOrSelfPermission( 3498 android.Manifest.permission.CLEAR_APP_CACHE, null); 3499 // Queue up an async operation since clearing cache may take a little while. 3500 mHandler.post(new Runnable() { 3501 public void run() { 3502 mHandler.removeCallbacks(this); 3503 boolean success = true; 3504 synchronized (mInstallLock) { 3505 try { 3506 mInstaller.freeCache(volumeUuid, freeStorageSize); 3507 } catch (InstallerException e) { 3508 Slog.w(TAG, "Couldn't clear application caches: " + e); 3509 success = false; 3510 } 3511 } 3512 if(pi != null) { 3513 try { 3514 // Callback via pending intent 3515 int code = success ? 1 : 0; 3516 pi.sendIntent(null, code, null, 3517 null, null); 3518 } catch (SendIntentException e1) { 3519 Slog.i(TAG, "Failed to send pending intent"); 3520 } 3521 } 3522 } 3523 }); 3524 } 3525 3526 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3527 synchronized (mInstallLock) { 3528 try { 3529 mInstaller.freeCache(volumeUuid, freeStorageSize); 3530 } catch (InstallerException e) { 3531 throw new IOException("Failed to free enough space", e); 3532 } 3533 } 3534 } 3535 3536 /** 3537 * Update given flags based on encryption status of current user. 3538 */ 3539 private int updateFlags(int flags, int userId) { 3540 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3541 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3542 // Caller expressed an explicit opinion about what encryption 3543 // aware/unaware components they want to see, so fall through and 3544 // give them what they want 3545 } else { 3546 // Caller expressed no opinion, so match based on user state 3547 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3548 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3549 } else { 3550 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3551 } 3552 } 3553 return flags; 3554 } 3555 3556 private UserManagerInternal getUserManagerInternal() { 3557 if (mUserManagerInternal == null) { 3558 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3559 } 3560 return mUserManagerInternal; 3561 } 3562 3563 /** 3564 * Update given flags when being used to request {@link PackageInfo}. 3565 */ 3566 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3567 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3568 boolean triaged = true; 3569 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3570 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3571 // Caller is asking for component details, so they'd better be 3572 // asking for specific encryption matching behavior, or be triaged 3573 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3574 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3575 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3576 triaged = false; 3577 } 3578 } 3579 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3580 | PackageManager.MATCH_SYSTEM_ONLY 3581 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3582 triaged = false; 3583 } 3584 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3585 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3586 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3587 + Debug.getCallers(5)); 3588 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3589 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3590 // If the caller wants all packages and has a restricted profile associated with it, 3591 // then match all users. This is to make sure that launchers that need to access work 3592 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3593 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3594 flags |= PackageManager.MATCH_ANY_USER; 3595 } 3596 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3597 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3598 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3599 } 3600 return updateFlags(flags, userId); 3601 } 3602 3603 /** 3604 * Update given flags when being used to request {@link ApplicationInfo}. 3605 */ 3606 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3607 return updateFlagsForPackage(flags, userId, cookie); 3608 } 3609 3610 /** 3611 * Update given flags when being used to request {@link ComponentInfo}. 3612 */ 3613 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3614 if (cookie instanceof Intent) { 3615 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3616 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3617 } 3618 } 3619 3620 boolean triaged = true; 3621 // Caller is asking for component details, so they'd better be 3622 // asking for specific encryption matching behavior, or be triaged 3623 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3624 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3625 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3626 triaged = false; 3627 } 3628 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3629 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3630 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3631 } 3632 3633 return updateFlags(flags, userId); 3634 } 3635 3636 /** 3637 * Update given flags when being used to request {@link ResolveInfo}. 3638 */ 3639 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3640 // Safe mode means we shouldn't match any third-party components 3641 if (mSafeMode) { 3642 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3643 } 3644 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 3645 if (ephemeralPkgName != null) { 3646 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3647 flags |= PackageManager.MATCH_EPHEMERAL; 3648 } 3649 3650 return updateFlagsForComponent(flags, userId, cookie); 3651 } 3652 3653 @Override 3654 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3655 if (!sUserManager.exists(userId)) return null; 3656 flags = updateFlagsForComponent(flags, userId, component); 3657 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3658 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3659 synchronized (mPackages) { 3660 PackageParser.Activity a = mActivities.mActivities.get(component); 3661 3662 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3663 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3664 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3665 if (ps == null) return null; 3666 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3667 userId); 3668 } 3669 if (mResolveComponentName.equals(component)) { 3670 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3671 new PackageUserState(), userId); 3672 } 3673 } 3674 return null; 3675 } 3676 3677 @Override 3678 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3679 String resolvedType) { 3680 synchronized (mPackages) { 3681 if (component.equals(mResolveComponentName)) { 3682 // The resolver supports EVERYTHING! 3683 return true; 3684 } 3685 PackageParser.Activity a = mActivities.mActivities.get(component); 3686 if (a == null) { 3687 return false; 3688 } 3689 for (int i=0; i<a.intents.size(); i++) { 3690 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3691 intent.getData(), intent.getCategories(), TAG) >= 0) { 3692 return true; 3693 } 3694 } 3695 return false; 3696 } 3697 } 3698 3699 @Override 3700 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3701 if (!sUserManager.exists(userId)) return null; 3702 flags = updateFlagsForComponent(flags, userId, component); 3703 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3704 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3705 synchronized (mPackages) { 3706 PackageParser.Activity a = mReceivers.mActivities.get(component); 3707 if (DEBUG_PACKAGE_INFO) Log.v( 3708 TAG, "getReceiverInfo " + component + ": " + a); 3709 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3710 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3711 if (ps == null) return null; 3712 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3713 userId); 3714 } 3715 } 3716 return null; 3717 } 3718 3719 @Override 3720 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3721 if (!sUserManager.exists(userId)) return null; 3722 flags = updateFlagsForComponent(flags, userId, component); 3723 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3724 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3725 synchronized (mPackages) { 3726 PackageParser.Service s = mServices.mServices.get(component); 3727 if (DEBUG_PACKAGE_INFO) Log.v( 3728 TAG, "getServiceInfo " + component + ": " + s); 3729 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3730 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3731 if (ps == null) return null; 3732 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3733 userId); 3734 } 3735 } 3736 return null; 3737 } 3738 3739 @Override 3740 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3741 if (!sUserManager.exists(userId)) return null; 3742 flags = updateFlagsForComponent(flags, userId, component); 3743 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3744 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3745 synchronized (mPackages) { 3746 PackageParser.Provider p = mProviders.mProviders.get(component); 3747 if (DEBUG_PACKAGE_INFO) Log.v( 3748 TAG, "getProviderInfo " + component + ": " + p); 3749 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3750 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3751 if (ps == null) return null; 3752 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3753 userId); 3754 } 3755 } 3756 return null; 3757 } 3758 3759 @Override 3760 public String[] getSystemSharedLibraryNames() { 3761 Set<String> libSet; 3762 synchronized (mPackages) { 3763 libSet = mSharedLibraries.keySet(); 3764 int size = libSet.size(); 3765 if (size > 0) { 3766 String[] libs = new String[size]; 3767 libSet.toArray(libs); 3768 return libs; 3769 } 3770 } 3771 return null; 3772 } 3773 3774 @Override 3775 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3776 synchronized (mPackages) { 3777 return mServicesSystemSharedLibraryPackageName; 3778 } 3779 } 3780 3781 @Override 3782 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3783 synchronized (mPackages) { 3784 return mSharedSystemSharedLibraryPackageName; 3785 } 3786 } 3787 3788 @Override 3789 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3790 synchronized (mPackages) { 3791 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3792 3793 final FeatureInfo fi = new FeatureInfo(); 3794 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3795 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3796 res.add(fi); 3797 3798 return new ParceledListSlice<>(res); 3799 } 3800 } 3801 3802 @Override 3803 public boolean hasSystemFeature(String name, int version) { 3804 synchronized (mPackages) { 3805 final FeatureInfo feat = mAvailableFeatures.get(name); 3806 if (feat == null) { 3807 return false; 3808 } else { 3809 return feat.version >= version; 3810 } 3811 } 3812 } 3813 3814 @Override 3815 public int checkPermission(String permName, String pkgName, int userId) { 3816 if (!sUserManager.exists(userId)) { 3817 return PackageManager.PERMISSION_DENIED; 3818 } 3819 3820 synchronized (mPackages) { 3821 final PackageParser.Package p = mPackages.get(pkgName); 3822 if (p != null && p.mExtras != null) { 3823 final PackageSetting ps = (PackageSetting) p.mExtras; 3824 final PermissionsState permissionsState = ps.getPermissionsState(); 3825 if (permissionsState.hasPermission(permName, userId)) { 3826 return PackageManager.PERMISSION_GRANTED; 3827 } 3828 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3829 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3830 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3831 return PackageManager.PERMISSION_GRANTED; 3832 } 3833 } 3834 } 3835 3836 return PackageManager.PERMISSION_DENIED; 3837 } 3838 3839 @Override 3840 public int checkUidPermission(String permName, int uid) { 3841 final int userId = UserHandle.getUserId(uid); 3842 3843 if (!sUserManager.exists(userId)) { 3844 return PackageManager.PERMISSION_DENIED; 3845 } 3846 3847 synchronized (mPackages) { 3848 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3849 if (obj != null) { 3850 final SettingBase ps = (SettingBase) obj; 3851 final PermissionsState permissionsState = ps.getPermissionsState(); 3852 if (permissionsState.hasPermission(permName, userId)) { 3853 return PackageManager.PERMISSION_GRANTED; 3854 } 3855 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3856 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3857 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3858 return PackageManager.PERMISSION_GRANTED; 3859 } 3860 } else { 3861 ArraySet<String> perms = mSystemPermissions.get(uid); 3862 if (perms != null) { 3863 if (perms.contains(permName)) { 3864 return PackageManager.PERMISSION_GRANTED; 3865 } 3866 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3867 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3868 return PackageManager.PERMISSION_GRANTED; 3869 } 3870 } 3871 } 3872 } 3873 3874 return PackageManager.PERMISSION_DENIED; 3875 } 3876 3877 @Override 3878 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3879 if (UserHandle.getCallingUserId() != userId) { 3880 mContext.enforceCallingPermission( 3881 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3882 "isPermissionRevokedByPolicy for user " + userId); 3883 } 3884 3885 if (checkPermission(permission, packageName, userId) 3886 == PackageManager.PERMISSION_GRANTED) { 3887 return false; 3888 } 3889 3890 final long identity = Binder.clearCallingIdentity(); 3891 try { 3892 final int flags = getPermissionFlags(permission, packageName, userId); 3893 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3894 } finally { 3895 Binder.restoreCallingIdentity(identity); 3896 } 3897 } 3898 3899 @Override 3900 public String getPermissionControllerPackageName() { 3901 synchronized (mPackages) { 3902 return mRequiredInstallerPackage; 3903 } 3904 } 3905 3906 /** 3907 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3908 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3909 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3910 * @param message the message to log on security exception 3911 */ 3912 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3913 boolean checkShell, String message) { 3914 if (userId < 0) { 3915 throw new IllegalArgumentException("Invalid userId " + userId); 3916 } 3917 if (checkShell) { 3918 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3919 } 3920 if (userId == UserHandle.getUserId(callingUid)) return; 3921 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3922 if (requireFullPermission) { 3923 mContext.enforceCallingOrSelfPermission( 3924 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3925 } else { 3926 try { 3927 mContext.enforceCallingOrSelfPermission( 3928 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3929 } catch (SecurityException se) { 3930 mContext.enforceCallingOrSelfPermission( 3931 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3932 } 3933 } 3934 } 3935 } 3936 3937 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3938 if (callingUid == Process.SHELL_UID) { 3939 if (userHandle >= 0 3940 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3941 throw new SecurityException("Shell does not have permission to access user " 3942 + userHandle); 3943 } else if (userHandle < 0) { 3944 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3945 + Debug.getCallers(3)); 3946 } 3947 } 3948 } 3949 3950 private BasePermission findPermissionTreeLP(String permName) { 3951 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3952 if (permName.startsWith(bp.name) && 3953 permName.length() > bp.name.length() && 3954 permName.charAt(bp.name.length()) == '.') { 3955 return bp; 3956 } 3957 } 3958 return null; 3959 } 3960 3961 private BasePermission checkPermissionTreeLP(String permName) { 3962 if (permName != null) { 3963 BasePermission bp = findPermissionTreeLP(permName); 3964 if (bp != null) { 3965 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3966 return bp; 3967 } 3968 throw new SecurityException("Calling uid " 3969 + Binder.getCallingUid() 3970 + " is not allowed to add to permission tree " 3971 + bp.name + " owned by uid " + bp.uid); 3972 } 3973 } 3974 throw new SecurityException("No permission tree found for " + permName); 3975 } 3976 3977 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3978 if (s1 == null) { 3979 return s2 == null; 3980 } 3981 if (s2 == null) { 3982 return false; 3983 } 3984 if (s1.getClass() != s2.getClass()) { 3985 return false; 3986 } 3987 return s1.equals(s2); 3988 } 3989 3990 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3991 if (pi1.icon != pi2.icon) return false; 3992 if (pi1.logo != pi2.logo) return false; 3993 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3994 if (!compareStrings(pi1.name, pi2.name)) return false; 3995 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3996 // We'll take care of setting this one. 3997 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3998 // These are not currently stored in settings. 3999 //if (!compareStrings(pi1.group, pi2.group)) return false; 4000 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4001 //if (pi1.labelRes != pi2.labelRes) return false; 4002 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4003 return true; 4004 } 4005 4006 int permissionInfoFootprint(PermissionInfo info) { 4007 int size = info.name.length(); 4008 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4009 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4010 return size; 4011 } 4012 4013 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4014 int size = 0; 4015 for (BasePermission perm : mSettings.mPermissions.values()) { 4016 if (perm.uid == tree.uid) { 4017 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4018 } 4019 } 4020 return size; 4021 } 4022 4023 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4024 // We calculate the max size of permissions defined by this uid and throw 4025 // if that plus the size of 'info' would exceed our stated maximum. 4026 if (tree.uid != Process.SYSTEM_UID) { 4027 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4028 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4029 throw new SecurityException("Permission tree size cap exceeded"); 4030 } 4031 } 4032 } 4033 4034 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4035 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4036 throw new SecurityException("Label must be specified in permission"); 4037 } 4038 BasePermission tree = checkPermissionTreeLP(info.name); 4039 BasePermission bp = mSettings.mPermissions.get(info.name); 4040 boolean added = bp == null; 4041 boolean changed = true; 4042 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4043 if (added) { 4044 enforcePermissionCapLocked(info, tree); 4045 bp = new BasePermission(info.name, tree.sourcePackage, 4046 BasePermission.TYPE_DYNAMIC); 4047 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4048 throw new SecurityException( 4049 "Not allowed to modify non-dynamic permission " 4050 + info.name); 4051 } else { 4052 if (bp.protectionLevel == fixedLevel 4053 && bp.perm.owner.equals(tree.perm.owner) 4054 && bp.uid == tree.uid 4055 && comparePermissionInfos(bp.perm.info, info)) { 4056 changed = false; 4057 } 4058 } 4059 bp.protectionLevel = fixedLevel; 4060 info = new PermissionInfo(info); 4061 info.protectionLevel = fixedLevel; 4062 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4063 bp.perm.info.packageName = tree.perm.info.packageName; 4064 bp.uid = tree.uid; 4065 if (added) { 4066 mSettings.mPermissions.put(info.name, bp); 4067 } 4068 if (changed) { 4069 if (!async) { 4070 mSettings.writeLPr(); 4071 } else { 4072 scheduleWriteSettingsLocked(); 4073 } 4074 } 4075 return added; 4076 } 4077 4078 @Override 4079 public boolean addPermission(PermissionInfo info) { 4080 synchronized (mPackages) { 4081 return addPermissionLocked(info, false); 4082 } 4083 } 4084 4085 @Override 4086 public boolean addPermissionAsync(PermissionInfo info) { 4087 synchronized (mPackages) { 4088 return addPermissionLocked(info, true); 4089 } 4090 } 4091 4092 @Override 4093 public void removePermission(String name) { 4094 synchronized (mPackages) { 4095 checkPermissionTreeLP(name); 4096 BasePermission bp = mSettings.mPermissions.get(name); 4097 if (bp != null) { 4098 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4099 throw new SecurityException( 4100 "Not allowed to modify non-dynamic permission " 4101 + name); 4102 } 4103 mSettings.mPermissions.remove(name); 4104 mSettings.writeLPr(); 4105 } 4106 } 4107 } 4108 4109 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4110 BasePermission bp) { 4111 int index = pkg.requestedPermissions.indexOf(bp.name); 4112 if (index == -1) { 4113 throw new SecurityException("Package " + pkg.packageName 4114 + " has not requested permission " + bp.name); 4115 } 4116 if (!bp.isRuntime() && !bp.isDevelopment()) { 4117 throw new SecurityException("Permission " + bp.name 4118 + " is not a changeable permission type"); 4119 } 4120 } 4121 4122 @Override 4123 public void grantRuntimePermission(String packageName, String name, final int userId) { 4124 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4125 } 4126 4127 private void grantRuntimePermission(String packageName, String name, final int userId, 4128 boolean overridePolicy) { 4129 if (!sUserManager.exists(userId)) { 4130 Log.e(TAG, "No such user:" + userId); 4131 return; 4132 } 4133 4134 mContext.enforceCallingOrSelfPermission( 4135 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4136 "grantRuntimePermission"); 4137 4138 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4139 true /* requireFullPermission */, true /* checkShell */, 4140 "grantRuntimePermission"); 4141 4142 final int uid; 4143 final SettingBase sb; 4144 4145 synchronized (mPackages) { 4146 final PackageParser.Package pkg = mPackages.get(packageName); 4147 if (pkg == null) { 4148 throw new IllegalArgumentException("Unknown package: " + packageName); 4149 } 4150 4151 final BasePermission bp = mSettings.mPermissions.get(name); 4152 if (bp == null) { 4153 throw new IllegalArgumentException("Unknown permission: " + name); 4154 } 4155 4156 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4157 4158 // If a permission review is required for legacy apps we represent 4159 // their permissions as always granted runtime ones since we need 4160 // to keep the review required permission flag per user while an 4161 // install permission's state is shared across all users. 4162 if (mPermissionReviewRequired 4163 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4164 && bp.isRuntime()) { 4165 return; 4166 } 4167 4168 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4169 sb = (SettingBase) pkg.mExtras; 4170 if (sb == null) { 4171 throw new IllegalArgumentException("Unknown package: " + packageName); 4172 } 4173 4174 final PermissionsState permissionsState = sb.getPermissionsState(); 4175 4176 final int flags = permissionsState.getPermissionFlags(name, userId); 4177 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4178 throw new SecurityException("Cannot grant system fixed permission " 4179 + name + " for package " + packageName); 4180 } 4181 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4182 throw new SecurityException("Cannot grant policy fixed permission " 4183 + name + " for package " + packageName); 4184 } 4185 4186 if (bp.isDevelopment()) { 4187 // Development permissions must be handled specially, since they are not 4188 // normal runtime permissions. For now they apply to all users. 4189 if (permissionsState.grantInstallPermission(bp) != 4190 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4191 scheduleWriteSettingsLocked(); 4192 } 4193 return; 4194 } 4195 4196 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4197 throw new SecurityException("Cannot grant non-ephemeral permission" 4198 + name + " for package " + packageName); 4199 } 4200 4201 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4202 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4203 return; 4204 } 4205 4206 final int result = permissionsState.grantRuntimePermission(bp, userId); 4207 switch (result) { 4208 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4209 return; 4210 } 4211 4212 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4213 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4214 mHandler.post(new Runnable() { 4215 @Override 4216 public void run() { 4217 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4218 } 4219 }); 4220 } 4221 break; 4222 } 4223 4224 if (bp.isRuntime()) { 4225 logPermissionGranted(mContext, name, packageName); 4226 } 4227 4228 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4229 4230 // Not critical if that is lost - app has to request again. 4231 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4232 } 4233 4234 // Only need to do this if user is initialized. Otherwise it's a new user 4235 // and there are no processes running as the user yet and there's no need 4236 // to make an expensive call to remount processes for the changed permissions. 4237 if (READ_EXTERNAL_STORAGE.equals(name) 4238 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4239 final long token = Binder.clearCallingIdentity(); 4240 try { 4241 if (sUserManager.isInitialized(userId)) { 4242 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4243 StorageManagerInternal.class); 4244 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4245 } 4246 } finally { 4247 Binder.restoreCallingIdentity(token); 4248 } 4249 } 4250 } 4251 4252 @Override 4253 public void revokeRuntimePermission(String packageName, String name, int userId) { 4254 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4255 } 4256 4257 private void revokeRuntimePermission(String packageName, String name, int userId, 4258 boolean overridePolicy) { 4259 if (!sUserManager.exists(userId)) { 4260 Log.e(TAG, "No such user:" + userId); 4261 return; 4262 } 4263 4264 mContext.enforceCallingOrSelfPermission( 4265 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4266 "revokeRuntimePermission"); 4267 4268 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4269 true /* requireFullPermission */, true /* checkShell */, 4270 "revokeRuntimePermission"); 4271 4272 final int appId; 4273 4274 synchronized (mPackages) { 4275 final PackageParser.Package pkg = mPackages.get(packageName); 4276 if (pkg == null) { 4277 throw new IllegalArgumentException("Unknown package: " + packageName); 4278 } 4279 4280 final BasePermission bp = mSettings.mPermissions.get(name); 4281 if (bp == null) { 4282 throw new IllegalArgumentException("Unknown permission: " + name); 4283 } 4284 4285 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4286 4287 // If a permission review is required for legacy apps we represent 4288 // their permissions as always granted runtime ones since we need 4289 // to keep the review required permission flag per user while an 4290 // install permission's state is shared across all users. 4291 if (mPermissionReviewRequired 4292 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4293 && bp.isRuntime()) { 4294 return; 4295 } 4296 4297 SettingBase sb = (SettingBase) pkg.mExtras; 4298 if (sb == null) { 4299 throw new IllegalArgumentException("Unknown package: " + packageName); 4300 } 4301 4302 final PermissionsState permissionsState = sb.getPermissionsState(); 4303 4304 final int flags = permissionsState.getPermissionFlags(name, userId); 4305 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4306 throw new SecurityException("Cannot revoke system fixed permission " 4307 + name + " for package " + packageName); 4308 } 4309 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4310 throw new SecurityException("Cannot revoke policy fixed permission " 4311 + name + " for package " + packageName); 4312 } 4313 4314 if (bp.isDevelopment()) { 4315 // Development permissions must be handled specially, since they are not 4316 // normal runtime permissions. For now they apply to all users. 4317 if (permissionsState.revokeInstallPermission(bp) != 4318 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4319 scheduleWriteSettingsLocked(); 4320 } 4321 return; 4322 } 4323 4324 if (permissionsState.revokeRuntimePermission(bp, userId) == 4325 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4326 return; 4327 } 4328 4329 if (bp.isRuntime()) { 4330 logPermissionRevoked(mContext, name, packageName); 4331 } 4332 4333 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4334 4335 // Critical, after this call app should never have the permission. 4336 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4337 4338 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4339 } 4340 4341 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4342 } 4343 4344 /** 4345 * Get the first event id for the permission. 4346 * 4347 * <p>There are four events for each permission: <ul> 4348 * <li>Request permission: first id + 0</li> 4349 * <li>Grant permission: first id + 1</li> 4350 * <li>Request for permission denied: first id + 2</li> 4351 * <li>Revoke permission: first id + 3</li> 4352 * </ul></p> 4353 * 4354 * @param name name of the permission 4355 * 4356 * @return The first event id for the permission 4357 */ 4358 private static int getBaseEventId(@NonNull String name) { 4359 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4360 4361 if (eventIdIndex == -1) { 4362 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4363 || "user".equals(Build.TYPE)) { 4364 Log.i(TAG, "Unknown permission " + name); 4365 4366 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4367 } else { 4368 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4369 // 4370 // Also update 4371 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4372 // - metrics_constants.proto 4373 throw new IllegalStateException("Unknown permission " + name); 4374 } 4375 } 4376 4377 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4378 } 4379 4380 /** 4381 * Log that a permission was revoked. 4382 * 4383 * @param context Context of the caller 4384 * @param name name of the permission 4385 * @param packageName package permission if for 4386 */ 4387 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4388 @NonNull String packageName) { 4389 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4390 } 4391 4392 /** 4393 * Log that a permission request was granted. 4394 * 4395 * @param context Context of the caller 4396 * @param name name of the permission 4397 * @param packageName package permission if for 4398 */ 4399 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4400 @NonNull String packageName) { 4401 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4402 } 4403 4404 @Override 4405 public void resetRuntimePermissions() { 4406 mContext.enforceCallingOrSelfPermission( 4407 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4408 "revokeRuntimePermission"); 4409 4410 int callingUid = Binder.getCallingUid(); 4411 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4412 mContext.enforceCallingOrSelfPermission( 4413 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4414 "resetRuntimePermissions"); 4415 } 4416 4417 synchronized (mPackages) { 4418 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4419 for (int userId : UserManagerService.getInstance().getUserIds()) { 4420 final int packageCount = mPackages.size(); 4421 for (int i = 0; i < packageCount; i++) { 4422 PackageParser.Package pkg = mPackages.valueAt(i); 4423 if (!(pkg.mExtras instanceof PackageSetting)) { 4424 continue; 4425 } 4426 PackageSetting ps = (PackageSetting) pkg.mExtras; 4427 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4428 } 4429 } 4430 } 4431 } 4432 4433 @Override 4434 public int getPermissionFlags(String name, String packageName, int userId) { 4435 if (!sUserManager.exists(userId)) { 4436 return 0; 4437 } 4438 4439 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4440 4441 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4442 true /* requireFullPermission */, false /* checkShell */, 4443 "getPermissionFlags"); 4444 4445 synchronized (mPackages) { 4446 final PackageParser.Package pkg = mPackages.get(packageName); 4447 if (pkg == null) { 4448 return 0; 4449 } 4450 4451 final BasePermission bp = mSettings.mPermissions.get(name); 4452 if (bp == null) { 4453 return 0; 4454 } 4455 4456 SettingBase sb = (SettingBase) pkg.mExtras; 4457 if (sb == null) { 4458 return 0; 4459 } 4460 4461 PermissionsState permissionsState = sb.getPermissionsState(); 4462 return permissionsState.getPermissionFlags(name, userId); 4463 } 4464 } 4465 4466 @Override 4467 public void updatePermissionFlags(String name, String packageName, int flagMask, 4468 int flagValues, int userId) { 4469 if (!sUserManager.exists(userId)) { 4470 return; 4471 } 4472 4473 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4474 4475 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4476 true /* requireFullPermission */, true /* checkShell */, 4477 "updatePermissionFlags"); 4478 4479 // Only the system can change these flags and nothing else. 4480 if (getCallingUid() != Process.SYSTEM_UID) { 4481 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4482 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4483 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4484 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4485 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4486 } 4487 4488 synchronized (mPackages) { 4489 final PackageParser.Package pkg = mPackages.get(packageName); 4490 if (pkg == null) { 4491 throw new IllegalArgumentException("Unknown package: " + packageName); 4492 } 4493 4494 final BasePermission bp = mSettings.mPermissions.get(name); 4495 if (bp == null) { 4496 throw new IllegalArgumentException("Unknown permission: " + name); 4497 } 4498 4499 SettingBase sb = (SettingBase) pkg.mExtras; 4500 if (sb == null) { 4501 throw new IllegalArgumentException("Unknown package: " + packageName); 4502 } 4503 4504 PermissionsState permissionsState = sb.getPermissionsState(); 4505 4506 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4507 4508 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4509 // Install and runtime permissions are stored in different places, 4510 // so figure out what permission changed and persist the change. 4511 if (permissionsState.getInstallPermissionState(name) != null) { 4512 scheduleWriteSettingsLocked(); 4513 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4514 || hadState) { 4515 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4516 } 4517 } 4518 } 4519 } 4520 4521 /** 4522 * Update the permission flags for all packages and runtime permissions of a user in order 4523 * to allow device or profile owner to remove POLICY_FIXED. 4524 */ 4525 @Override 4526 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4527 if (!sUserManager.exists(userId)) { 4528 return; 4529 } 4530 4531 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4532 4533 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4534 true /* requireFullPermission */, true /* checkShell */, 4535 "updatePermissionFlagsForAllApps"); 4536 4537 // Only the system can change system fixed flags. 4538 if (getCallingUid() != Process.SYSTEM_UID) { 4539 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4540 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4541 } 4542 4543 synchronized (mPackages) { 4544 boolean changed = false; 4545 final int packageCount = mPackages.size(); 4546 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4547 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4548 SettingBase sb = (SettingBase) pkg.mExtras; 4549 if (sb == null) { 4550 continue; 4551 } 4552 PermissionsState permissionsState = sb.getPermissionsState(); 4553 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4554 userId, flagMask, flagValues); 4555 } 4556 if (changed) { 4557 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4558 } 4559 } 4560 } 4561 4562 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4563 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4564 != PackageManager.PERMISSION_GRANTED 4565 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4566 != PackageManager.PERMISSION_GRANTED) { 4567 throw new SecurityException(message + " requires " 4568 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4569 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4570 } 4571 } 4572 4573 @Override 4574 public boolean shouldShowRequestPermissionRationale(String permissionName, 4575 String packageName, int userId) { 4576 if (UserHandle.getCallingUserId() != userId) { 4577 mContext.enforceCallingPermission( 4578 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4579 "canShowRequestPermissionRationale for user " + userId); 4580 } 4581 4582 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4583 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4584 return false; 4585 } 4586 4587 if (checkPermission(permissionName, packageName, userId) 4588 == PackageManager.PERMISSION_GRANTED) { 4589 return false; 4590 } 4591 4592 final int flags; 4593 4594 final long identity = Binder.clearCallingIdentity(); 4595 try { 4596 flags = getPermissionFlags(permissionName, 4597 packageName, userId); 4598 } finally { 4599 Binder.restoreCallingIdentity(identity); 4600 } 4601 4602 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4603 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4604 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4605 4606 if ((flags & fixedFlags) != 0) { 4607 return false; 4608 } 4609 4610 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4611 } 4612 4613 @Override 4614 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4615 mContext.enforceCallingOrSelfPermission( 4616 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4617 "addOnPermissionsChangeListener"); 4618 4619 synchronized (mPackages) { 4620 mOnPermissionChangeListeners.addListenerLocked(listener); 4621 } 4622 } 4623 4624 @Override 4625 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4626 synchronized (mPackages) { 4627 mOnPermissionChangeListeners.removeListenerLocked(listener); 4628 } 4629 } 4630 4631 @Override 4632 public boolean isProtectedBroadcast(String actionName) { 4633 synchronized (mPackages) { 4634 if (mProtectedBroadcasts.contains(actionName)) { 4635 return true; 4636 } else if (actionName != null) { 4637 // TODO: remove these terrible hacks 4638 if (actionName.startsWith("android.net.netmon.lingerExpired") 4639 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4640 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4641 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4642 return true; 4643 } 4644 } 4645 } 4646 return false; 4647 } 4648 4649 @Override 4650 public int checkSignatures(String pkg1, String pkg2) { 4651 synchronized (mPackages) { 4652 final PackageParser.Package p1 = mPackages.get(pkg1); 4653 final PackageParser.Package p2 = mPackages.get(pkg2); 4654 if (p1 == null || p1.mExtras == null 4655 || p2 == null || p2.mExtras == null) { 4656 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4657 } 4658 return compareSignatures(p1.mSignatures, p2.mSignatures); 4659 } 4660 } 4661 4662 @Override 4663 public int checkUidSignatures(int uid1, int uid2) { 4664 // Map to base uids. 4665 uid1 = UserHandle.getAppId(uid1); 4666 uid2 = UserHandle.getAppId(uid2); 4667 // reader 4668 synchronized (mPackages) { 4669 Signature[] s1; 4670 Signature[] s2; 4671 Object obj = mSettings.getUserIdLPr(uid1); 4672 if (obj != null) { 4673 if (obj instanceof SharedUserSetting) { 4674 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4675 } else if (obj instanceof PackageSetting) { 4676 s1 = ((PackageSetting)obj).signatures.mSignatures; 4677 } else { 4678 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4679 } 4680 } else { 4681 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4682 } 4683 obj = mSettings.getUserIdLPr(uid2); 4684 if (obj != null) { 4685 if (obj instanceof SharedUserSetting) { 4686 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4687 } else if (obj instanceof PackageSetting) { 4688 s2 = ((PackageSetting)obj).signatures.mSignatures; 4689 } else { 4690 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4691 } 4692 } else { 4693 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4694 } 4695 return compareSignatures(s1, s2); 4696 } 4697 } 4698 4699 /** 4700 * This method should typically only be used when granting or revoking 4701 * permissions, since the app may immediately restart after this call. 4702 * <p> 4703 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4704 * guard your work against the app being relaunched. 4705 */ 4706 private void killUid(int appId, int userId, String reason) { 4707 final long identity = Binder.clearCallingIdentity(); 4708 try { 4709 IActivityManager am = ActivityManager.getService(); 4710 if (am != null) { 4711 try { 4712 am.killUid(appId, userId, reason); 4713 } catch (RemoteException e) { 4714 /* ignore - same process */ 4715 } 4716 } 4717 } finally { 4718 Binder.restoreCallingIdentity(identity); 4719 } 4720 } 4721 4722 /** 4723 * Compares two sets of signatures. Returns: 4724 * <br /> 4725 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4726 * <br /> 4727 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4728 * <br /> 4729 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4730 * <br /> 4731 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4732 * <br /> 4733 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4734 */ 4735 static int compareSignatures(Signature[] s1, Signature[] s2) { 4736 if (s1 == null) { 4737 return s2 == null 4738 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4739 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4740 } 4741 4742 if (s2 == null) { 4743 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4744 } 4745 4746 if (s1.length != s2.length) { 4747 return PackageManager.SIGNATURE_NO_MATCH; 4748 } 4749 4750 // Since both signature sets are of size 1, we can compare without HashSets. 4751 if (s1.length == 1) { 4752 return s1[0].equals(s2[0]) ? 4753 PackageManager.SIGNATURE_MATCH : 4754 PackageManager.SIGNATURE_NO_MATCH; 4755 } 4756 4757 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4758 for (Signature sig : s1) { 4759 set1.add(sig); 4760 } 4761 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4762 for (Signature sig : s2) { 4763 set2.add(sig); 4764 } 4765 // Make sure s2 contains all signatures in s1. 4766 if (set1.equals(set2)) { 4767 return PackageManager.SIGNATURE_MATCH; 4768 } 4769 return PackageManager.SIGNATURE_NO_MATCH; 4770 } 4771 4772 /** 4773 * If the database version for this type of package (internal storage or 4774 * external storage) is less than the version where package signatures 4775 * were updated, return true. 4776 */ 4777 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4778 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4779 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4780 } 4781 4782 /** 4783 * Used for backward compatibility to make sure any packages with 4784 * certificate chains get upgraded to the new style. {@code existingSigs} 4785 * will be in the old format (since they were stored on disk from before the 4786 * system upgrade) and {@code scannedSigs} will be in the newer format. 4787 */ 4788 private int compareSignaturesCompat(PackageSignatures existingSigs, 4789 PackageParser.Package scannedPkg) { 4790 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4791 return PackageManager.SIGNATURE_NO_MATCH; 4792 } 4793 4794 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4795 for (Signature sig : existingSigs.mSignatures) { 4796 existingSet.add(sig); 4797 } 4798 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4799 for (Signature sig : scannedPkg.mSignatures) { 4800 try { 4801 Signature[] chainSignatures = sig.getChainSignatures(); 4802 for (Signature chainSig : chainSignatures) { 4803 scannedCompatSet.add(chainSig); 4804 } 4805 } catch (CertificateEncodingException e) { 4806 scannedCompatSet.add(sig); 4807 } 4808 } 4809 /* 4810 * Make sure the expanded scanned set contains all signatures in the 4811 * existing one. 4812 */ 4813 if (scannedCompatSet.equals(existingSet)) { 4814 // Migrate the old signatures to the new scheme. 4815 existingSigs.assignSignatures(scannedPkg.mSignatures); 4816 // The new KeySets will be re-added later in the scanning process. 4817 synchronized (mPackages) { 4818 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4819 } 4820 return PackageManager.SIGNATURE_MATCH; 4821 } 4822 return PackageManager.SIGNATURE_NO_MATCH; 4823 } 4824 4825 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4826 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4827 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4828 } 4829 4830 private int compareSignaturesRecover(PackageSignatures existingSigs, 4831 PackageParser.Package scannedPkg) { 4832 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4833 return PackageManager.SIGNATURE_NO_MATCH; 4834 } 4835 4836 String msg = null; 4837 try { 4838 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4839 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4840 + scannedPkg.packageName); 4841 return PackageManager.SIGNATURE_MATCH; 4842 } 4843 } catch (CertificateException e) { 4844 msg = e.getMessage(); 4845 } 4846 4847 logCriticalInfo(Log.INFO, 4848 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4849 return PackageManager.SIGNATURE_NO_MATCH; 4850 } 4851 4852 @Override 4853 public List<String> getAllPackages() { 4854 synchronized (mPackages) { 4855 return new ArrayList<String>(mPackages.keySet()); 4856 } 4857 } 4858 4859 @Override 4860 public String[] getPackagesForUid(int uid) { 4861 final int userId = UserHandle.getUserId(uid); 4862 uid = UserHandle.getAppId(uid); 4863 // reader 4864 synchronized (mPackages) { 4865 Object obj = mSettings.getUserIdLPr(uid); 4866 if (obj instanceof SharedUserSetting) { 4867 final SharedUserSetting sus = (SharedUserSetting) obj; 4868 final int N = sus.packages.size(); 4869 String[] res = new String[N]; 4870 final Iterator<PackageSetting> it = sus.packages.iterator(); 4871 int i = 0; 4872 while (it.hasNext()) { 4873 PackageSetting ps = it.next(); 4874 if (ps.getInstalled(userId)) { 4875 res[i++] = ps.name; 4876 } else { 4877 res = ArrayUtils.removeElement(String.class, res, res[i]); 4878 } 4879 } 4880 return res; 4881 } else if (obj instanceof PackageSetting) { 4882 final PackageSetting ps = (PackageSetting) obj; 4883 return new String[] { ps.name }; 4884 } 4885 } 4886 return null; 4887 } 4888 4889 @Override 4890 public String getNameForUid(int uid) { 4891 // reader 4892 synchronized (mPackages) { 4893 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4894 if (obj instanceof SharedUserSetting) { 4895 final SharedUserSetting sus = (SharedUserSetting) obj; 4896 return sus.name + ":" + sus.userId; 4897 } else if (obj instanceof PackageSetting) { 4898 final PackageSetting ps = (PackageSetting) obj; 4899 return ps.name; 4900 } 4901 } 4902 return null; 4903 } 4904 4905 @Override 4906 public int getUidForSharedUser(String sharedUserName) { 4907 if(sharedUserName == null) { 4908 return -1; 4909 } 4910 // reader 4911 synchronized (mPackages) { 4912 SharedUserSetting suid; 4913 try { 4914 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4915 if (suid != null) { 4916 return suid.userId; 4917 } 4918 } catch (PackageManagerException ignore) { 4919 // can't happen, but, still need to catch it 4920 } 4921 return -1; 4922 } 4923 } 4924 4925 @Override 4926 public int getFlagsForUid(int uid) { 4927 synchronized (mPackages) { 4928 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4929 if (obj instanceof SharedUserSetting) { 4930 final SharedUserSetting sus = (SharedUserSetting) obj; 4931 return sus.pkgFlags; 4932 } else if (obj instanceof PackageSetting) { 4933 final PackageSetting ps = (PackageSetting) obj; 4934 return ps.pkgFlags; 4935 } 4936 } 4937 return 0; 4938 } 4939 4940 @Override 4941 public int getPrivateFlagsForUid(int uid) { 4942 synchronized (mPackages) { 4943 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4944 if (obj instanceof SharedUserSetting) { 4945 final SharedUserSetting sus = (SharedUserSetting) obj; 4946 return sus.pkgPrivateFlags; 4947 } else if (obj instanceof PackageSetting) { 4948 final PackageSetting ps = (PackageSetting) obj; 4949 return ps.pkgPrivateFlags; 4950 } 4951 } 4952 return 0; 4953 } 4954 4955 @Override 4956 public boolean isUidPrivileged(int uid) { 4957 uid = UserHandle.getAppId(uid); 4958 // reader 4959 synchronized (mPackages) { 4960 Object obj = mSettings.getUserIdLPr(uid); 4961 if (obj instanceof SharedUserSetting) { 4962 final SharedUserSetting sus = (SharedUserSetting) obj; 4963 final Iterator<PackageSetting> it = sus.packages.iterator(); 4964 while (it.hasNext()) { 4965 if (it.next().isPrivileged()) { 4966 return true; 4967 } 4968 } 4969 } else if (obj instanceof PackageSetting) { 4970 final PackageSetting ps = (PackageSetting) obj; 4971 return ps.isPrivileged(); 4972 } 4973 } 4974 return false; 4975 } 4976 4977 @Override 4978 public String[] getAppOpPermissionPackages(String permissionName) { 4979 synchronized (mPackages) { 4980 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4981 if (pkgs == null) { 4982 return null; 4983 } 4984 return pkgs.toArray(new String[pkgs.size()]); 4985 } 4986 } 4987 4988 @Override 4989 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4990 int flags, int userId) { 4991 try { 4992 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4993 4994 if (!sUserManager.exists(userId)) return null; 4995 flags = updateFlagsForResolve(flags, userId, intent); 4996 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4997 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4998 4999 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5000 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5001 flags, userId); 5002 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5003 5004 final ResolveInfo bestChoice = 5005 chooseBestActivity(intent, resolvedType, flags, query, userId); 5006 return bestChoice; 5007 } finally { 5008 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5009 } 5010 } 5011 5012 @Override 5013 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5014 IntentFilter filter, int match, ComponentName activity) { 5015 final int userId = UserHandle.getCallingUserId(); 5016 if (DEBUG_PREFERRED) { 5017 Log.v(TAG, "setLastChosenActivity intent=" + intent 5018 + " resolvedType=" + resolvedType 5019 + " flags=" + flags 5020 + " filter=" + filter 5021 + " match=" + match 5022 + " activity=" + activity); 5023 filter.dump(new PrintStreamPrinter(System.out), " "); 5024 } 5025 intent.setComponent(null); 5026 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5027 userId); 5028 // Find any earlier preferred or last chosen entries and nuke them 5029 findPreferredActivity(intent, resolvedType, 5030 flags, query, 0, false, true, false, userId); 5031 // Add the new activity as the last chosen for this filter 5032 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5033 "Setting last chosen"); 5034 } 5035 5036 @Override 5037 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5038 final int userId = UserHandle.getCallingUserId(); 5039 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5040 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5041 userId); 5042 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5043 false, false, false, userId); 5044 } 5045 5046 private boolean isEphemeralDisabled() { 5047 // ephemeral apps have been disabled across the board 5048 if (DISABLE_EPHEMERAL_APPS) { 5049 return true; 5050 } 5051 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5052 if (!mSystemReady) { 5053 return true; 5054 } 5055 // we can't get a content resolver until the system is ready; these checks must happen last 5056 final ContentResolver resolver = mContext.getContentResolver(); 5057 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5058 return true; 5059 } 5060 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5061 } 5062 5063 private boolean isEphemeralAllowed( 5064 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5065 boolean skipPackageCheck) { 5066 // Short circuit and return early if possible. 5067 if (isEphemeralDisabled()) { 5068 return false; 5069 } 5070 final int callingUser = UserHandle.getCallingUserId(); 5071 if (callingUser != UserHandle.USER_SYSTEM) { 5072 return false; 5073 } 5074 if (mEphemeralResolverConnection == null) { 5075 return false; 5076 } 5077 if (mEphemeralInstallerComponent == null) { 5078 return false; 5079 } 5080 if (intent.getComponent() != null) { 5081 return false; 5082 } 5083 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5084 return false; 5085 } 5086 if (!skipPackageCheck && intent.getPackage() != null) { 5087 return false; 5088 } 5089 final boolean isWebUri = hasWebURI(intent); 5090 if (!isWebUri || intent.getData().getHost() == null) { 5091 return false; 5092 } 5093 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5094 synchronized (mPackages) { 5095 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5096 for (int n = 0; n < count; n++) { 5097 ResolveInfo info = resolvedActivities.get(n); 5098 String packageName = info.activityInfo.packageName; 5099 PackageSetting ps = mSettings.mPackages.get(packageName); 5100 if (ps != null) { 5101 // Try to get the status from User settings first 5102 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5103 int status = (int) (packedStatus >> 32); 5104 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5105 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5106 if (DEBUG_EPHEMERAL) { 5107 Slog.v(TAG, "DENY ephemeral apps;" 5108 + " pkg: " + packageName + ", status: " + status); 5109 } 5110 return false; 5111 } 5112 } 5113 } 5114 } 5115 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5116 return true; 5117 } 5118 5119 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5120 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5121 int userId) { 5122 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5123 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5124 callingPackage, userId)); 5125 mHandler.sendMessage(msg); 5126 } 5127 5128 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5129 int flags, List<ResolveInfo> query, int userId) { 5130 if (query != null) { 5131 final int N = query.size(); 5132 if (N == 1) { 5133 return query.get(0); 5134 } else if (N > 1) { 5135 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5136 // If there is more than one activity with the same priority, 5137 // then let the user decide between them. 5138 ResolveInfo r0 = query.get(0); 5139 ResolveInfo r1 = query.get(1); 5140 if (DEBUG_INTENT_MATCHING || debug) { 5141 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5142 + r1.activityInfo.name + "=" + r1.priority); 5143 } 5144 // If the first activity has a higher priority, or a different 5145 // default, then it is always desirable to pick it. 5146 if (r0.priority != r1.priority 5147 || r0.preferredOrder != r1.preferredOrder 5148 || r0.isDefault != r1.isDefault) { 5149 return query.get(0); 5150 } 5151 // If we have saved a preference for a preferred activity for 5152 // this Intent, use that. 5153 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5154 flags, query, r0.priority, true, false, debug, userId); 5155 if (ri != null) { 5156 return ri; 5157 } 5158 ri = new ResolveInfo(mResolveInfo); 5159 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5160 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5161 // If all of the options come from the same package, show the application's 5162 // label and icon instead of the generic resolver's. 5163 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5164 // and then throw away the ResolveInfo itself, meaning that the caller loses 5165 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5166 // a fallback for this case; we only set the target package's resources on 5167 // the ResolveInfo, not the ActivityInfo. 5168 final String intentPackage = intent.getPackage(); 5169 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5170 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5171 ri.resolvePackageName = intentPackage; 5172 if (userNeedsBadging(userId)) { 5173 ri.noResourceId = true; 5174 } else { 5175 ri.icon = appi.icon; 5176 } 5177 ri.iconResourceId = appi.icon; 5178 ri.labelRes = appi.labelRes; 5179 } 5180 ri.activityInfo.applicationInfo = new ApplicationInfo( 5181 ri.activityInfo.applicationInfo); 5182 if (userId != 0) { 5183 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5184 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5185 } 5186 // Make sure that the resolver is displayable in car mode 5187 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5188 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5189 return ri; 5190 } 5191 } 5192 return null; 5193 } 5194 5195 /** 5196 * Return true if the given list is not empty and all of its contents have 5197 * an activityInfo with the given package name. 5198 */ 5199 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5200 if (ArrayUtils.isEmpty(list)) { 5201 return false; 5202 } 5203 for (int i = 0, N = list.size(); i < N; i++) { 5204 final ResolveInfo ri = list.get(i); 5205 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5206 if (ai == null || !packageName.equals(ai.packageName)) { 5207 return false; 5208 } 5209 } 5210 return true; 5211 } 5212 5213 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5214 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5215 final int N = query.size(); 5216 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5217 .get(userId); 5218 // Get the list of persistent preferred activities that handle the intent 5219 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5220 List<PersistentPreferredActivity> pprefs = ppir != null 5221 ? ppir.queryIntent(intent, resolvedType, 5222 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5223 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5224 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5225 : null; 5226 if (pprefs != null && pprefs.size() > 0) { 5227 final int M = pprefs.size(); 5228 for (int i=0; i<M; i++) { 5229 final PersistentPreferredActivity ppa = pprefs.get(i); 5230 if (DEBUG_PREFERRED || debug) { 5231 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5232 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5233 + "\n component=" + ppa.mComponent); 5234 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5235 } 5236 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5237 flags | MATCH_DISABLED_COMPONENTS, userId); 5238 if (DEBUG_PREFERRED || debug) { 5239 Slog.v(TAG, "Found persistent preferred activity:"); 5240 if (ai != null) { 5241 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5242 } else { 5243 Slog.v(TAG, " null"); 5244 } 5245 } 5246 if (ai == null) { 5247 // This previously registered persistent preferred activity 5248 // component is no longer known. Ignore it and do NOT remove it. 5249 continue; 5250 } 5251 for (int j=0; j<N; j++) { 5252 final ResolveInfo ri = query.get(j); 5253 if (!ri.activityInfo.applicationInfo.packageName 5254 .equals(ai.applicationInfo.packageName)) { 5255 continue; 5256 } 5257 if (!ri.activityInfo.name.equals(ai.name)) { 5258 continue; 5259 } 5260 // Found a persistent preference that can handle the intent. 5261 if (DEBUG_PREFERRED || debug) { 5262 Slog.v(TAG, "Returning persistent preferred activity: " + 5263 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5264 } 5265 return ri; 5266 } 5267 } 5268 } 5269 return null; 5270 } 5271 5272 // TODO: handle preferred activities missing while user has amnesia 5273 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5274 List<ResolveInfo> query, int priority, boolean always, 5275 boolean removeMatches, boolean debug, int userId) { 5276 if (!sUserManager.exists(userId)) return null; 5277 flags = updateFlagsForResolve(flags, userId, intent); 5278 // writer 5279 synchronized (mPackages) { 5280 if (intent.getSelector() != null) { 5281 intent = intent.getSelector(); 5282 } 5283 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5284 5285 // Try to find a matching persistent preferred activity. 5286 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5287 debug, userId); 5288 5289 // If a persistent preferred activity matched, use it. 5290 if (pri != null) { 5291 return pri; 5292 } 5293 5294 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5295 // Get the list of preferred activities that handle the intent 5296 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5297 List<PreferredActivity> prefs = pir != null 5298 ? pir.queryIntent(intent, resolvedType, 5299 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5300 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5301 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5302 : null; 5303 if (prefs != null && prefs.size() > 0) { 5304 boolean changed = false; 5305 try { 5306 // First figure out how good the original match set is. 5307 // We will only allow preferred activities that came 5308 // from the same match quality. 5309 int match = 0; 5310 5311 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5312 5313 final int N = query.size(); 5314 for (int j=0; j<N; j++) { 5315 final ResolveInfo ri = query.get(j); 5316 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5317 + ": 0x" + Integer.toHexString(match)); 5318 if (ri.match > match) { 5319 match = ri.match; 5320 } 5321 } 5322 5323 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5324 + Integer.toHexString(match)); 5325 5326 match &= IntentFilter.MATCH_CATEGORY_MASK; 5327 final int M = prefs.size(); 5328 for (int i=0; i<M; i++) { 5329 final PreferredActivity pa = prefs.get(i); 5330 if (DEBUG_PREFERRED || debug) { 5331 Slog.v(TAG, "Checking PreferredActivity ds=" 5332 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5333 + "\n component=" + pa.mPref.mComponent); 5334 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5335 } 5336 if (pa.mPref.mMatch != match) { 5337 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5338 + Integer.toHexString(pa.mPref.mMatch)); 5339 continue; 5340 } 5341 // If it's not an "always" type preferred activity and that's what we're 5342 // looking for, skip it. 5343 if (always && !pa.mPref.mAlways) { 5344 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5345 continue; 5346 } 5347 final ActivityInfo ai = getActivityInfo( 5348 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5349 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5350 userId); 5351 if (DEBUG_PREFERRED || debug) { 5352 Slog.v(TAG, "Found preferred activity:"); 5353 if (ai != null) { 5354 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5355 } else { 5356 Slog.v(TAG, " null"); 5357 } 5358 } 5359 if (ai == null) { 5360 // This previously registered preferred activity 5361 // component is no longer known. Most likely an update 5362 // to the app was installed and in the new version this 5363 // component no longer exists. Clean it up by removing 5364 // it from the preferred activities list, and skip it. 5365 Slog.w(TAG, "Removing dangling preferred activity: " 5366 + pa.mPref.mComponent); 5367 pir.removeFilter(pa); 5368 changed = true; 5369 continue; 5370 } 5371 for (int j=0; j<N; j++) { 5372 final ResolveInfo ri = query.get(j); 5373 if (!ri.activityInfo.applicationInfo.packageName 5374 .equals(ai.applicationInfo.packageName)) { 5375 continue; 5376 } 5377 if (!ri.activityInfo.name.equals(ai.name)) { 5378 continue; 5379 } 5380 5381 if (removeMatches) { 5382 pir.removeFilter(pa); 5383 changed = true; 5384 if (DEBUG_PREFERRED) { 5385 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5386 } 5387 break; 5388 } 5389 5390 // Okay we found a previously set preferred or last chosen app. 5391 // If the result set is different from when this 5392 // was created, we need to clear it and re-ask the 5393 // user their preference, if we're looking for an "always" type entry. 5394 if (always && !pa.mPref.sameSet(query)) { 5395 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5396 + intent + " type " + resolvedType); 5397 if (DEBUG_PREFERRED) { 5398 Slog.v(TAG, "Removing preferred activity since set changed " 5399 + pa.mPref.mComponent); 5400 } 5401 pir.removeFilter(pa); 5402 // Re-add the filter as a "last chosen" entry (!always) 5403 PreferredActivity lastChosen = new PreferredActivity( 5404 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5405 pir.addFilter(lastChosen); 5406 changed = true; 5407 return null; 5408 } 5409 5410 // Yay! Either the set matched or we're looking for the last chosen 5411 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5412 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5413 return ri; 5414 } 5415 } 5416 } finally { 5417 if (changed) { 5418 if (DEBUG_PREFERRED) { 5419 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5420 } 5421 scheduleWritePackageRestrictionsLocked(userId); 5422 } 5423 } 5424 } 5425 } 5426 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5427 return null; 5428 } 5429 5430 /* 5431 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5432 */ 5433 @Override 5434 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5435 int targetUserId) { 5436 mContext.enforceCallingOrSelfPermission( 5437 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5438 List<CrossProfileIntentFilter> matches = 5439 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5440 if (matches != null) { 5441 int size = matches.size(); 5442 for (int i = 0; i < size; i++) { 5443 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5444 } 5445 } 5446 if (hasWebURI(intent)) { 5447 // cross-profile app linking works only towards the parent. 5448 final UserInfo parent = getProfileParent(sourceUserId); 5449 synchronized(mPackages) { 5450 int flags = updateFlagsForResolve(0, parent.id, intent); 5451 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5452 intent, resolvedType, flags, sourceUserId, parent.id); 5453 return xpDomainInfo != null; 5454 } 5455 } 5456 return false; 5457 } 5458 5459 private UserInfo getProfileParent(int userId) { 5460 final long identity = Binder.clearCallingIdentity(); 5461 try { 5462 return sUserManager.getProfileParent(userId); 5463 } finally { 5464 Binder.restoreCallingIdentity(identity); 5465 } 5466 } 5467 5468 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5469 String resolvedType, int userId) { 5470 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5471 if (resolver != null) { 5472 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5473 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5474 } 5475 return null; 5476 } 5477 5478 @Override 5479 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5480 String resolvedType, int flags, int userId) { 5481 try { 5482 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5483 5484 return new ParceledListSlice<>( 5485 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5486 } finally { 5487 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5488 } 5489 } 5490 5491 /** 5492 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5493 * ephemeral, returns {@code null}. 5494 */ 5495 private String getEphemeralPackageName(int callingUid) { 5496 final int appId = UserHandle.getAppId(callingUid); 5497 synchronized (mPackages) { 5498 final Object obj = mSettings.getUserIdLPr(appId); 5499 if (obj instanceof PackageSetting) { 5500 final PackageSetting ps = (PackageSetting) obj; 5501 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5502 } 5503 } 5504 return null; 5505 } 5506 5507 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5508 String resolvedType, int flags, int userId) { 5509 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5510 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5511 flags = updateFlagsForResolve(flags, userId, intent); 5512 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5513 false /* requireFullPermission */, false /* checkShell */, 5514 "query intent activities"); 5515 ComponentName comp = intent.getComponent(); 5516 if (comp == null) { 5517 if (intent.getSelector() != null) { 5518 intent = intent.getSelector(); 5519 comp = intent.getComponent(); 5520 } 5521 } 5522 5523 if (comp != null) { 5524 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5525 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5526 if (ai != null) { 5527 // When specifying an explicit component, we prevent the activity from being 5528 // used when either 1) the calling package is normal and the activity is within 5529 // an ephemeral application or 2) the calling package is ephemeral and the 5530 // activity is not visible to ephemeral applications. 5531 boolean blockResolution = 5532 (ephemeralPkgName == null 5533 && (ai.applicationInfo.privateFlags 5534 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5535 || (ephemeralPkgName != null 5536 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5537 if (!blockResolution) { 5538 final ResolveInfo ri = new ResolveInfo(); 5539 ri.activityInfo = ai; 5540 list.add(ri); 5541 } 5542 } 5543 return list; 5544 } 5545 5546 // reader 5547 boolean sortResult = false; 5548 boolean addEphemeral = false; 5549 List<ResolveInfo> result; 5550 final String pkgName = intent.getPackage(); 5551 synchronized (mPackages) { 5552 if (pkgName == null) { 5553 List<CrossProfileIntentFilter> matchingFilters = 5554 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5555 // Check for results that need to skip the current profile. 5556 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5557 resolvedType, flags, userId); 5558 if (xpResolveInfo != null) { 5559 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5560 xpResult.add(xpResolveInfo); 5561 return filterForEphemeral( 5562 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5563 } 5564 5565 // Check for results in the current profile. 5566 result = filterIfNotSystemUser(mActivities.queryIntent( 5567 intent, resolvedType, flags, userId), userId); 5568 addEphemeral = 5569 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5570 5571 // Check for cross profile results. 5572 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5573 xpResolveInfo = queryCrossProfileIntents( 5574 matchingFilters, intent, resolvedType, flags, userId, 5575 hasNonNegativePriorityResult); 5576 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5577 boolean isVisibleToUser = filterIfNotSystemUser( 5578 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5579 if (isVisibleToUser) { 5580 result.add(xpResolveInfo); 5581 sortResult = true; 5582 } 5583 } 5584 if (hasWebURI(intent)) { 5585 CrossProfileDomainInfo xpDomainInfo = null; 5586 final UserInfo parent = getProfileParent(userId); 5587 if (parent != null) { 5588 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5589 flags, userId, parent.id); 5590 } 5591 if (xpDomainInfo != null) { 5592 if (xpResolveInfo != null) { 5593 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5594 // in the result. 5595 result.remove(xpResolveInfo); 5596 } 5597 if (result.size() == 0 && !addEphemeral) { 5598 // No result in current profile, but found candidate in parent user. 5599 // And we are not going to add emphemeral app, so we can return the 5600 // result straight away. 5601 result.add(xpDomainInfo.resolveInfo); 5602 return filterForEphemeral(result, ephemeralPkgName); 5603 } 5604 } else if (result.size() <= 1 && !addEphemeral) { 5605 // No result in parent user and <= 1 result in current profile, and we 5606 // are not going to add emphemeral app, so we can return the result without 5607 // further processing. 5608 return filterForEphemeral(result, ephemeralPkgName); 5609 } 5610 // We have more than one candidate (combining results from current and parent 5611 // profile), so we need filtering and sorting. 5612 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5613 intent, flags, result, xpDomainInfo, userId); 5614 sortResult = true; 5615 } 5616 } else { 5617 final PackageParser.Package pkg = mPackages.get(pkgName); 5618 if (pkg != null) { 5619 result = filterForEphemeral(filterIfNotSystemUser( 5620 mActivities.queryIntentForPackage( 5621 intent, resolvedType, flags, pkg.activities, userId), 5622 userId), ephemeralPkgName); 5623 } else { 5624 // the caller wants to resolve for a particular package; however, there 5625 // were no installed results, so, try to find an ephemeral result 5626 addEphemeral = isEphemeralAllowed( 5627 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5628 result = new ArrayList<ResolveInfo>(); 5629 } 5630 } 5631 } 5632 if (addEphemeral) { 5633 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5634 final EphemeralRequest requestObject = new EphemeralRequest( 5635 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5636 null /*launchIntent*/, null /*callingPackage*/, userId); 5637 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5638 mContext, mEphemeralResolverConnection, requestObject); 5639 if (intentInfo != null) { 5640 if (DEBUG_EPHEMERAL) { 5641 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5642 } 5643 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5644 ephemeralInstaller.ephemeralResponse = intentInfo; 5645 // make sure this resolver is the default 5646 ephemeralInstaller.isDefault = true; 5647 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5648 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5649 // add a non-generic filter 5650 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5651 ephemeralInstaller.filter.addDataPath( 5652 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5653 result.add(ephemeralInstaller); 5654 } 5655 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5656 } 5657 if (sortResult) { 5658 Collections.sort(result, mResolvePrioritySorter); 5659 } 5660 return filterForEphemeral(result, ephemeralPkgName); 5661 } 5662 5663 private static class CrossProfileDomainInfo { 5664 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5665 ResolveInfo resolveInfo; 5666 /* Best domain verification status of the activities found in the other profile */ 5667 int bestDomainVerificationStatus; 5668 } 5669 5670 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5671 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5672 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5673 sourceUserId)) { 5674 return null; 5675 } 5676 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5677 resolvedType, flags, parentUserId); 5678 5679 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5680 return null; 5681 } 5682 CrossProfileDomainInfo result = null; 5683 int size = resultTargetUser.size(); 5684 for (int i = 0; i < size; i++) { 5685 ResolveInfo riTargetUser = resultTargetUser.get(i); 5686 // Intent filter verification is only for filters that specify a host. So don't return 5687 // those that handle all web uris. 5688 if (riTargetUser.handleAllWebDataURI) { 5689 continue; 5690 } 5691 String packageName = riTargetUser.activityInfo.packageName; 5692 PackageSetting ps = mSettings.mPackages.get(packageName); 5693 if (ps == null) { 5694 continue; 5695 } 5696 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5697 int status = (int)(verificationState >> 32); 5698 if (result == null) { 5699 result = new CrossProfileDomainInfo(); 5700 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5701 sourceUserId, parentUserId); 5702 result.bestDomainVerificationStatus = status; 5703 } else { 5704 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5705 result.bestDomainVerificationStatus); 5706 } 5707 } 5708 // Don't consider matches with status NEVER across profiles. 5709 if (result != null && result.bestDomainVerificationStatus 5710 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5711 return null; 5712 } 5713 return result; 5714 } 5715 5716 /** 5717 * Verification statuses are ordered from the worse to the best, except for 5718 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5719 */ 5720 private int bestDomainVerificationStatus(int status1, int status2) { 5721 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5722 return status2; 5723 } 5724 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5725 return status1; 5726 } 5727 return (int) MathUtils.max(status1, status2); 5728 } 5729 5730 private boolean isUserEnabled(int userId) { 5731 long callingId = Binder.clearCallingIdentity(); 5732 try { 5733 UserInfo userInfo = sUserManager.getUserInfo(userId); 5734 return userInfo != null && userInfo.isEnabled(); 5735 } finally { 5736 Binder.restoreCallingIdentity(callingId); 5737 } 5738 } 5739 5740 /** 5741 * Filter out activities with systemUserOnly flag set, when current user is not System. 5742 * 5743 * @return filtered list 5744 */ 5745 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5746 if (userId == UserHandle.USER_SYSTEM) { 5747 return resolveInfos; 5748 } 5749 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5750 ResolveInfo info = resolveInfos.get(i); 5751 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5752 resolveInfos.remove(i); 5753 } 5754 } 5755 return resolveInfos; 5756 } 5757 5758 /** 5759 * Filters out ephemeral activities. 5760 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 5761 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 5762 * 5763 * @param resolveInfos The pre-filtered list of resolved activities 5764 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 5765 * is performed. 5766 * @return A filtered list of resolved activities. 5767 */ 5768 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 5769 String ephemeralPkgName) { 5770 if (ephemeralPkgName == null) { 5771 return resolveInfos; 5772 } 5773 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5774 ResolveInfo info = resolveInfos.get(i); 5775 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 5776 // allow activities that are defined in the provided package 5777 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 5778 continue; 5779 } 5780 // allow activities that have been explicitly exposed to ephemeral apps 5781 if (!isEphemeralApp 5782 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 5783 continue; 5784 } 5785 resolveInfos.remove(i); 5786 } 5787 return resolveInfos; 5788 } 5789 5790 /** 5791 * @param resolveInfos list of resolve infos in descending priority order 5792 * @return if the list contains a resolve info with non-negative priority 5793 */ 5794 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5795 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5796 } 5797 5798 private static boolean hasWebURI(Intent intent) { 5799 if (intent.getData() == null) { 5800 return false; 5801 } 5802 final String scheme = intent.getScheme(); 5803 if (TextUtils.isEmpty(scheme)) { 5804 return false; 5805 } 5806 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5807 } 5808 5809 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5810 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5811 int userId) { 5812 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5813 5814 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5815 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5816 candidates.size()); 5817 } 5818 5819 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5820 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5821 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5822 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5823 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5824 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5825 5826 synchronized (mPackages) { 5827 final int count = candidates.size(); 5828 // First, try to use linked apps. Partition the candidates into four lists: 5829 // one for the final results, one for the "do not use ever", one for "undefined status" 5830 // and finally one for "browser app type". 5831 for (int n=0; n<count; n++) { 5832 ResolveInfo info = candidates.get(n); 5833 String packageName = info.activityInfo.packageName; 5834 PackageSetting ps = mSettings.mPackages.get(packageName); 5835 if (ps != null) { 5836 // Add to the special match all list (Browser use case) 5837 if (info.handleAllWebDataURI) { 5838 matchAllList.add(info); 5839 continue; 5840 } 5841 // Try to get the status from User settings first 5842 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5843 int status = (int)(packedStatus >> 32); 5844 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5845 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5846 if (DEBUG_DOMAIN_VERIFICATION) { 5847 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5848 + " : linkgen=" + linkGeneration); 5849 } 5850 // Use link-enabled generation as preferredOrder, i.e. 5851 // prefer newly-enabled over earlier-enabled. 5852 info.preferredOrder = linkGeneration; 5853 alwaysList.add(info); 5854 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5855 if (DEBUG_DOMAIN_VERIFICATION) { 5856 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5857 } 5858 neverList.add(info); 5859 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5860 if (DEBUG_DOMAIN_VERIFICATION) { 5861 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5862 } 5863 alwaysAskList.add(info); 5864 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5865 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5866 if (DEBUG_DOMAIN_VERIFICATION) { 5867 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5868 } 5869 undefinedList.add(info); 5870 } 5871 } 5872 } 5873 5874 // We'll want to include browser possibilities in a few cases 5875 boolean includeBrowser = false; 5876 5877 // First try to add the "always" resolution(s) for the current user, if any 5878 if (alwaysList.size() > 0) { 5879 result.addAll(alwaysList); 5880 } else { 5881 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5882 result.addAll(undefinedList); 5883 // Maybe add one for the other profile. 5884 if (xpDomainInfo != null && ( 5885 xpDomainInfo.bestDomainVerificationStatus 5886 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5887 result.add(xpDomainInfo.resolveInfo); 5888 } 5889 includeBrowser = true; 5890 } 5891 5892 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5893 // If there were 'always' entries their preferred order has been set, so we also 5894 // back that off to make the alternatives equivalent 5895 if (alwaysAskList.size() > 0) { 5896 for (ResolveInfo i : result) { 5897 i.preferredOrder = 0; 5898 } 5899 result.addAll(alwaysAskList); 5900 includeBrowser = true; 5901 } 5902 5903 if (includeBrowser) { 5904 // Also add browsers (all of them or only the default one) 5905 if (DEBUG_DOMAIN_VERIFICATION) { 5906 Slog.v(TAG, " ...including browsers in candidate set"); 5907 } 5908 if ((matchFlags & MATCH_ALL) != 0) { 5909 result.addAll(matchAllList); 5910 } else { 5911 // Browser/generic handling case. If there's a default browser, go straight 5912 // to that (but only if there is no other higher-priority match). 5913 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5914 int maxMatchPrio = 0; 5915 ResolveInfo defaultBrowserMatch = null; 5916 final int numCandidates = matchAllList.size(); 5917 for (int n = 0; n < numCandidates; n++) { 5918 ResolveInfo info = matchAllList.get(n); 5919 // track the highest overall match priority... 5920 if (info.priority > maxMatchPrio) { 5921 maxMatchPrio = info.priority; 5922 } 5923 // ...and the highest-priority default browser match 5924 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5925 if (defaultBrowserMatch == null 5926 || (defaultBrowserMatch.priority < info.priority)) { 5927 if (debug) { 5928 Slog.v(TAG, "Considering default browser match " + info); 5929 } 5930 defaultBrowserMatch = info; 5931 } 5932 } 5933 } 5934 if (defaultBrowserMatch != null 5935 && defaultBrowserMatch.priority >= maxMatchPrio 5936 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5937 { 5938 if (debug) { 5939 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5940 } 5941 result.add(defaultBrowserMatch); 5942 } else { 5943 result.addAll(matchAllList); 5944 } 5945 } 5946 5947 // If there is nothing selected, add all candidates and remove the ones that the user 5948 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5949 if (result.size() == 0) { 5950 result.addAll(candidates); 5951 result.removeAll(neverList); 5952 } 5953 } 5954 } 5955 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5956 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5957 result.size()); 5958 for (ResolveInfo info : result) { 5959 Slog.v(TAG, " + " + info.activityInfo); 5960 } 5961 } 5962 return result; 5963 } 5964 5965 // Returns a packed value as a long: 5966 // 5967 // high 'int'-sized word: link status: undefined/ask/never/always. 5968 // low 'int'-sized word: relative priority among 'always' results. 5969 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5970 long result = ps.getDomainVerificationStatusForUser(userId); 5971 // if none available, get the master status 5972 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5973 if (ps.getIntentFilterVerificationInfo() != null) { 5974 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5975 } 5976 } 5977 return result; 5978 } 5979 5980 private ResolveInfo querySkipCurrentProfileIntents( 5981 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5982 int flags, int sourceUserId) { 5983 if (matchingFilters != null) { 5984 int size = matchingFilters.size(); 5985 for (int i = 0; i < size; i ++) { 5986 CrossProfileIntentFilter filter = matchingFilters.get(i); 5987 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5988 // Checking if there are activities in the target user that can handle the 5989 // intent. 5990 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5991 resolvedType, flags, sourceUserId); 5992 if (resolveInfo != null) { 5993 return resolveInfo; 5994 } 5995 } 5996 } 5997 } 5998 return null; 5999 } 6000 6001 // Return matching ResolveInfo in target user if any. 6002 private ResolveInfo queryCrossProfileIntents( 6003 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6004 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6005 if (matchingFilters != null) { 6006 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6007 // match the same intent. For performance reasons, it is better not to 6008 // run queryIntent twice for the same userId 6009 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6010 int size = matchingFilters.size(); 6011 for (int i = 0; i < size; i++) { 6012 CrossProfileIntentFilter filter = matchingFilters.get(i); 6013 int targetUserId = filter.getTargetUserId(); 6014 boolean skipCurrentProfile = 6015 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6016 boolean skipCurrentProfileIfNoMatchFound = 6017 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6018 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6019 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6020 // Checking if there are activities in the target user that can handle the 6021 // intent. 6022 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6023 resolvedType, flags, sourceUserId); 6024 if (resolveInfo != null) return resolveInfo; 6025 alreadyTriedUserIds.put(targetUserId, true); 6026 } 6027 } 6028 } 6029 return null; 6030 } 6031 6032 /** 6033 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6034 * will forward the intent to the filter's target user. 6035 * Otherwise, returns null. 6036 */ 6037 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6038 String resolvedType, int flags, int sourceUserId) { 6039 int targetUserId = filter.getTargetUserId(); 6040 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6041 resolvedType, flags, targetUserId); 6042 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6043 // If all the matches in the target profile are suspended, return null. 6044 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6045 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6046 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6047 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6048 targetUserId); 6049 } 6050 } 6051 } 6052 return null; 6053 } 6054 6055 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6056 int sourceUserId, int targetUserId) { 6057 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6058 long ident = Binder.clearCallingIdentity(); 6059 boolean targetIsProfile; 6060 try { 6061 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6062 } finally { 6063 Binder.restoreCallingIdentity(ident); 6064 } 6065 String className; 6066 if (targetIsProfile) { 6067 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6068 } else { 6069 className = FORWARD_INTENT_TO_PARENT; 6070 } 6071 ComponentName forwardingActivityComponentName = new ComponentName( 6072 mAndroidApplication.packageName, className); 6073 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6074 sourceUserId); 6075 if (!targetIsProfile) { 6076 forwardingActivityInfo.showUserIcon = targetUserId; 6077 forwardingResolveInfo.noResourceId = true; 6078 } 6079 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6080 forwardingResolveInfo.priority = 0; 6081 forwardingResolveInfo.preferredOrder = 0; 6082 forwardingResolveInfo.match = 0; 6083 forwardingResolveInfo.isDefault = true; 6084 forwardingResolveInfo.filter = filter; 6085 forwardingResolveInfo.targetUserId = targetUserId; 6086 return forwardingResolveInfo; 6087 } 6088 6089 @Override 6090 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6091 Intent[] specifics, String[] specificTypes, Intent intent, 6092 String resolvedType, int flags, int userId) { 6093 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6094 specificTypes, intent, resolvedType, flags, userId)); 6095 } 6096 6097 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6098 Intent[] specifics, String[] specificTypes, Intent intent, 6099 String resolvedType, int flags, int userId) { 6100 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6101 flags = updateFlagsForResolve(flags, userId, intent); 6102 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6103 false /* requireFullPermission */, false /* checkShell */, 6104 "query intent activity options"); 6105 final String resultsAction = intent.getAction(); 6106 6107 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6108 | PackageManager.GET_RESOLVED_FILTER, userId); 6109 6110 if (DEBUG_INTENT_MATCHING) { 6111 Log.v(TAG, "Query " + intent + ": " + results); 6112 } 6113 6114 int specificsPos = 0; 6115 int N; 6116 6117 // todo: note that the algorithm used here is O(N^2). This 6118 // isn't a problem in our current environment, but if we start running 6119 // into situations where we have more than 5 or 10 matches then this 6120 // should probably be changed to something smarter... 6121 6122 // First we go through and resolve each of the specific items 6123 // that were supplied, taking care of removing any corresponding 6124 // duplicate items in the generic resolve list. 6125 if (specifics != null) { 6126 for (int i=0; i<specifics.length; i++) { 6127 final Intent sintent = specifics[i]; 6128 if (sintent == null) { 6129 continue; 6130 } 6131 6132 if (DEBUG_INTENT_MATCHING) { 6133 Log.v(TAG, "Specific #" + i + ": " + sintent); 6134 } 6135 6136 String action = sintent.getAction(); 6137 if (resultsAction != null && resultsAction.equals(action)) { 6138 // If this action was explicitly requested, then don't 6139 // remove things that have it. 6140 action = null; 6141 } 6142 6143 ResolveInfo ri = null; 6144 ActivityInfo ai = null; 6145 6146 ComponentName comp = sintent.getComponent(); 6147 if (comp == null) { 6148 ri = resolveIntent( 6149 sintent, 6150 specificTypes != null ? specificTypes[i] : null, 6151 flags, userId); 6152 if (ri == null) { 6153 continue; 6154 } 6155 if (ri == mResolveInfo) { 6156 // ACK! Must do something better with this. 6157 } 6158 ai = ri.activityInfo; 6159 comp = new ComponentName(ai.applicationInfo.packageName, 6160 ai.name); 6161 } else { 6162 ai = getActivityInfo(comp, flags, userId); 6163 if (ai == null) { 6164 continue; 6165 } 6166 } 6167 6168 // Look for any generic query activities that are duplicates 6169 // of this specific one, and remove them from the results. 6170 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6171 N = results.size(); 6172 int j; 6173 for (j=specificsPos; j<N; j++) { 6174 ResolveInfo sri = results.get(j); 6175 if ((sri.activityInfo.name.equals(comp.getClassName()) 6176 && sri.activityInfo.applicationInfo.packageName.equals( 6177 comp.getPackageName())) 6178 || (action != null && sri.filter.matchAction(action))) { 6179 results.remove(j); 6180 if (DEBUG_INTENT_MATCHING) Log.v( 6181 TAG, "Removing duplicate item from " + j 6182 + " due to specific " + specificsPos); 6183 if (ri == null) { 6184 ri = sri; 6185 } 6186 j--; 6187 N--; 6188 } 6189 } 6190 6191 // Add this specific item to its proper place. 6192 if (ri == null) { 6193 ri = new ResolveInfo(); 6194 ri.activityInfo = ai; 6195 } 6196 results.add(specificsPos, ri); 6197 ri.specificIndex = i; 6198 specificsPos++; 6199 } 6200 } 6201 6202 // Now we go through the remaining generic results and remove any 6203 // duplicate actions that are found here. 6204 N = results.size(); 6205 for (int i=specificsPos; i<N-1; i++) { 6206 final ResolveInfo rii = results.get(i); 6207 if (rii.filter == null) { 6208 continue; 6209 } 6210 6211 // Iterate over all of the actions of this result's intent 6212 // filter... typically this should be just one. 6213 final Iterator<String> it = rii.filter.actionsIterator(); 6214 if (it == null) { 6215 continue; 6216 } 6217 while (it.hasNext()) { 6218 final String action = it.next(); 6219 if (resultsAction != null && resultsAction.equals(action)) { 6220 // If this action was explicitly requested, then don't 6221 // remove things that have it. 6222 continue; 6223 } 6224 for (int j=i+1; j<N; j++) { 6225 final ResolveInfo rij = results.get(j); 6226 if (rij.filter != null && rij.filter.hasAction(action)) { 6227 results.remove(j); 6228 if (DEBUG_INTENT_MATCHING) Log.v( 6229 TAG, "Removing duplicate item from " + j 6230 + " due to action " + action + " at " + i); 6231 j--; 6232 N--; 6233 } 6234 } 6235 } 6236 6237 // If the caller didn't request filter information, drop it now 6238 // so we don't have to marshall/unmarshall it. 6239 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6240 rii.filter = null; 6241 } 6242 } 6243 6244 // Filter out the caller activity if so requested. 6245 if (caller != null) { 6246 N = results.size(); 6247 for (int i=0; i<N; i++) { 6248 ActivityInfo ainfo = results.get(i).activityInfo; 6249 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6250 && caller.getClassName().equals(ainfo.name)) { 6251 results.remove(i); 6252 break; 6253 } 6254 } 6255 } 6256 6257 // If the caller didn't request filter information, 6258 // drop them now so we don't have to 6259 // marshall/unmarshall it. 6260 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6261 N = results.size(); 6262 for (int i=0; i<N; i++) { 6263 results.get(i).filter = null; 6264 } 6265 } 6266 6267 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6268 return results; 6269 } 6270 6271 @Override 6272 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6273 String resolvedType, int flags, int userId) { 6274 return new ParceledListSlice<>( 6275 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6276 } 6277 6278 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6279 String resolvedType, int flags, int userId) { 6280 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6281 flags = updateFlagsForResolve(flags, userId, intent); 6282 ComponentName comp = intent.getComponent(); 6283 if (comp == null) { 6284 if (intent.getSelector() != null) { 6285 intent = intent.getSelector(); 6286 comp = intent.getComponent(); 6287 } 6288 } 6289 if (comp != null) { 6290 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6291 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6292 if (ai != null) { 6293 ResolveInfo ri = new ResolveInfo(); 6294 ri.activityInfo = ai; 6295 list.add(ri); 6296 } 6297 return list; 6298 } 6299 6300 // reader 6301 synchronized (mPackages) { 6302 String pkgName = intent.getPackage(); 6303 if (pkgName == null) { 6304 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6305 } 6306 final PackageParser.Package pkg = mPackages.get(pkgName); 6307 if (pkg != null) { 6308 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6309 userId); 6310 } 6311 return Collections.emptyList(); 6312 } 6313 } 6314 6315 @Override 6316 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6317 if (!sUserManager.exists(userId)) return null; 6318 flags = updateFlagsForResolve(flags, userId, intent); 6319 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6320 if (query != null) { 6321 if (query.size() >= 1) { 6322 // If there is more than one service with the same priority, 6323 // just arbitrarily pick the first one. 6324 return query.get(0); 6325 } 6326 } 6327 return null; 6328 } 6329 6330 @Override 6331 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6332 String resolvedType, int flags, int userId) { 6333 return new ParceledListSlice<>( 6334 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6335 } 6336 6337 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6338 String resolvedType, int flags, int userId) { 6339 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6340 flags = updateFlagsForResolve(flags, userId, intent); 6341 ComponentName comp = intent.getComponent(); 6342 if (comp == null) { 6343 if (intent.getSelector() != null) { 6344 intent = intent.getSelector(); 6345 comp = intent.getComponent(); 6346 } 6347 } 6348 if (comp != null) { 6349 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6350 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6351 if (si != null) { 6352 final ResolveInfo ri = new ResolveInfo(); 6353 ri.serviceInfo = si; 6354 list.add(ri); 6355 } 6356 return list; 6357 } 6358 6359 // reader 6360 synchronized (mPackages) { 6361 String pkgName = intent.getPackage(); 6362 if (pkgName == null) { 6363 return mServices.queryIntent(intent, resolvedType, flags, userId); 6364 } 6365 final PackageParser.Package pkg = mPackages.get(pkgName); 6366 if (pkg != null) { 6367 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6368 userId); 6369 } 6370 return Collections.emptyList(); 6371 } 6372 } 6373 6374 @Override 6375 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6376 String resolvedType, int flags, int userId) { 6377 return new ParceledListSlice<>( 6378 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6379 } 6380 6381 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6382 Intent intent, String resolvedType, int flags, int userId) { 6383 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6384 flags = updateFlagsForResolve(flags, userId, intent); 6385 ComponentName comp = intent.getComponent(); 6386 if (comp == null) { 6387 if (intent.getSelector() != null) { 6388 intent = intent.getSelector(); 6389 comp = intent.getComponent(); 6390 } 6391 } 6392 if (comp != null) { 6393 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6394 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6395 if (pi != null) { 6396 final ResolveInfo ri = new ResolveInfo(); 6397 ri.providerInfo = pi; 6398 list.add(ri); 6399 } 6400 return list; 6401 } 6402 6403 // reader 6404 synchronized (mPackages) { 6405 String pkgName = intent.getPackage(); 6406 if (pkgName == null) { 6407 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6408 } 6409 final PackageParser.Package pkg = mPackages.get(pkgName); 6410 if (pkg != null) { 6411 return mProviders.queryIntentForPackage( 6412 intent, resolvedType, flags, pkg.providers, userId); 6413 } 6414 return Collections.emptyList(); 6415 } 6416 } 6417 6418 @Override 6419 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6420 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6421 flags = updateFlagsForPackage(flags, userId, null); 6422 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6423 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6424 true /* requireFullPermission */, false /* checkShell */, 6425 "get installed packages"); 6426 6427 // writer 6428 synchronized (mPackages) { 6429 ArrayList<PackageInfo> list; 6430 if (listUninstalled) { 6431 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6432 for (PackageSetting ps : mSettings.mPackages.values()) { 6433 final PackageInfo pi; 6434 if (ps.pkg != null) { 6435 pi = generatePackageInfo(ps, flags, userId); 6436 } else { 6437 pi = generatePackageInfo(ps, flags, userId); 6438 } 6439 if (pi != null) { 6440 list.add(pi); 6441 } 6442 } 6443 } else { 6444 list = new ArrayList<PackageInfo>(mPackages.size()); 6445 for (PackageParser.Package p : mPackages.values()) { 6446 final PackageInfo pi = 6447 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6448 if (pi != null) { 6449 list.add(pi); 6450 } 6451 } 6452 } 6453 6454 return new ParceledListSlice<PackageInfo>(list); 6455 } 6456 } 6457 6458 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6459 String[] permissions, boolean[] tmp, int flags, int userId) { 6460 int numMatch = 0; 6461 final PermissionsState permissionsState = ps.getPermissionsState(); 6462 for (int i=0; i<permissions.length; i++) { 6463 final String permission = permissions[i]; 6464 if (permissionsState.hasPermission(permission, userId)) { 6465 tmp[i] = true; 6466 numMatch++; 6467 } else { 6468 tmp[i] = false; 6469 } 6470 } 6471 if (numMatch == 0) { 6472 return; 6473 } 6474 final PackageInfo pi; 6475 if (ps.pkg != null) { 6476 pi = generatePackageInfo(ps, flags, userId); 6477 } else { 6478 pi = generatePackageInfo(ps, flags, userId); 6479 } 6480 // The above might return null in cases of uninstalled apps or install-state 6481 // skew across users/profiles. 6482 if (pi != null) { 6483 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6484 if (numMatch == permissions.length) { 6485 pi.requestedPermissions = permissions; 6486 } else { 6487 pi.requestedPermissions = new String[numMatch]; 6488 numMatch = 0; 6489 for (int i=0; i<permissions.length; i++) { 6490 if (tmp[i]) { 6491 pi.requestedPermissions[numMatch] = permissions[i]; 6492 numMatch++; 6493 } 6494 } 6495 } 6496 } 6497 list.add(pi); 6498 } 6499 } 6500 6501 @Override 6502 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6503 String[] permissions, int flags, int userId) { 6504 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6505 flags = updateFlagsForPackage(flags, userId, permissions); 6506 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6507 true /* requireFullPermission */, false /* checkShell */, 6508 "get packages holding permissions"); 6509 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6510 6511 // writer 6512 synchronized (mPackages) { 6513 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6514 boolean[] tmpBools = new boolean[permissions.length]; 6515 if (listUninstalled) { 6516 for (PackageSetting ps : mSettings.mPackages.values()) { 6517 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6518 userId); 6519 } 6520 } else { 6521 for (PackageParser.Package pkg : mPackages.values()) { 6522 PackageSetting ps = (PackageSetting)pkg.mExtras; 6523 if (ps != null) { 6524 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6525 userId); 6526 } 6527 } 6528 } 6529 6530 return new ParceledListSlice<PackageInfo>(list); 6531 } 6532 } 6533 6534 @Override 6535 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6536 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6537 flags = updateFlagsForApplication(flags, userId, null); 6538 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6539 6540 // writer 6541 synchronized (mPackages) { 6542 ArrayList<ApplicationInfo> list; 6543 if (listUninstalled) { 6544 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6545 for (PackageSetting ps : mSettings.mPackages.values()) { 6546 ApplicationInfo ai; 6547 int effectiveFlags = flags; 6548 if (ps.isSystem()) { 6549 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6550 } 6551 if (ps.pkg != null) { 6552 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6553 ps.readUserState(userId), userId); 6554 } else { 6555 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6556 userId); 6557 } 6558 if (ai != null) { 6559 list.add(ai); 6560 } 6561 } 6562 } else { 6563 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6564 for (PackageParser.Package p : mPackages.values()) { 6565 if (p.mExtras != null) { 6566 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6567 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6568 if (ai != null) { 6569 list.add(ai); 6570 } 6571 } 6572 } 6573 } 6574 6575 return new ParceledListSlice<ApplicationInfo>(list); 6576 } 6577 } 6578 6579 @Override 6580 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6581 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6582 return null; 6583 } 6584 6585 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6586 "getEphemeralApplications"); 6587 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6588 true /* requireFullPermission */, false /* checkShell */, 6589 "getEphemeralApplications"); 6590 synchronized (mPackages) { 6591 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6592 .getEphemeralApplicationsLPw(userId); 6593 if (ephemeralApps != null) { 6594 return new ParceledListSlice<>(ephemeralApps); 6595 } 6596 } 6597 return null; 6598 } 6599 6600 @Override 6601 public boolean isEphemeralApplication(String packageName, int userId) { 6602 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6603 true /* requireFullPermission */, false /* checkShell */, 6604 "isEphemeral"); 6605 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6606 return false; 6607 } 6608 6609 if (!isCallerSameApp(packageName)) { 6610 return false; 6611 } 6612 synchronized (mPackages) { 6613 PackageParser.Package pkg = mPackages.get(packageName); 6614 if (pkg != null) { 6615 return pkg.applicationInfo.isEphemeralApp(); 6616 } 6617 } 6618 return false; 6619 } 6620 6621 @Override 6622 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6623 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6624 return null; 6625 } 6626 6627 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6628 true /* requireFullPermission */, false /* checkShell */, 6629 "getCookie"); 6630 if (!isCallerSameApp(packageName)) { 6631 return null; 6632 } 6633 synchronized (mPackages) { 6634 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6635 packageName, userId); 6636 } 6637 } 6638 6639 @Override 6640 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6641 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6642 return true; 6643 } 6644 6645 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6646 true /* requireFullPermission */, true /* checkShell */, 6647 "setCookie"); 6648 if (!isCallerSameApp(packageName)) { 6649 return false; 6650 } 6651 synchronized (mPackages) { 6652 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6653 packageName, cookie, userId); 6654 } 6655 } 6656 6657 @Override 6658 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6659 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6660 return null; 6661 } 6662 6663 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6664 "getEphemeralApplicationIcon"); 6665 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6666 true /* requireFullPermission */, false /* checkShell */, 6667 "getEphemeralApplicationIcon"); 6668 synchronized (mPackages) { 6669 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6670 packageName, userId); 6671 } 6672 } 6673 6674 private boolean isCallerSameApp(String packageName) { 6675 PackageParser.Package pkg = mPackages.get(packageName); 6676 return pkg != null 6677 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6678 } 6679 6680 @Override 6681 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6682 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6683 } 6684 6685 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6686 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6687 6688 // reader 6689 synchronized (mPackages) { 6690 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6691 final int userId = UserHandle.getCallingUserId(); 6692 while (i.hasNext()) { 6693 final PackageParser.Package p = i.next(); 6694 if (p.applicationInfo == null) continue; 6695 6696 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6697 && !p.applicationInfo.isDirectBootAware(); 6698 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6699 && p.applicationInfo.isDirectBootAware(); 6700 6701 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6702 && (!mSafeMode || isSystemApp(p)) 6703 && (matchesUnaware || matchesAware)) { 6704 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6705 if (ps != null) { 6706 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6707 ps.readUserState(userId), userId); 6708 if (ai != null) { 6709 finalList.add(ai); 6710 } 6711 } 6712 } 6713 } 6714 } 6715 6716 return finalList; 6717 } 6718 6719 @Override 6720 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6721 if (!sUserManager.exists(userId)) return null; 6722 flags = updateFlagsForComponent(flags, userId, name); 6723 // reader 6724 synchronized (mPackages) { 6725 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6726 PackageSetting ps = provider != null 6727 ? mSettings.mPackages.get(provider.owner.packageName) 6728 : null; 6729 return ps != null 6730 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6731 ? PackageParser.generateProviderInfo(provider, flags, 6732 ps.readUserState(userId), userId) 6733 : null; 6734 } 6735 } 6736 6737 /** 6738 * @deprecated 6739 */ 6740 @Deprecated 6741 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6742 // reader 6743 synchronized (mPackages) { 6744 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6745 .entrySet().iterator(); 6746 final int userId = UserHandle.getCallingUserId(); 6747 while (i.hasNext()) { 6748 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6749 PackageParser.Provider p = entry.getValue(); 6750 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6751 6752 if (ps != null && p.syncable 6753 && (!mSafeMode || (p.info.applicationInfo.flags 6754 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6755 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6756 ps.readUserState(userId), userId); 6757 if (info != null) { 6758 outNames.add(entry.getKey()); 6759 outInfo.add(info); 6760 } 6761 } 6762 } 6763 } 6764 } 6765 6766 @Override 6767 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6768 int uid, int flags) { 6769 final int userId = processName != null ? UserHandle.getUserId(uid) 6770 : UserHandle.getCallingUserId(); 6771 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6772 flags = updateFlagsForComponent(flags, userId, processName); 6773 6774 ArrayList<ProviderInfo> finalList = null; 6775 // reader 6776 synchronized (mPackages) { 6777 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6778 while (i.hasNext()) { 6779 final PackageParser.Provider p = i.next(); 6780 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6781 if (ps != null && p.info.authority != null 6782 && (processName == null 6783 || (p.info.processName.equals(processName) 6784 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6785 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6786 if (finalList == null) { 6787 finalList = new ArrayList<ProviderInfo>(3); 6788 } 6789 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6790 ps.readUserState(userId), userId); 6791 if (info != null) { 6792 finalList.add(info); 6793 } 6794 } 6795 } 6796 } 6797 6798 if (finalList != null) { 6799 Collections.sort(finalList, mProviderInitOrderSorter); 6800 return new ParceledListSlice<ProviderInfo>(finalList); 6801 } 6802 6803 return ParceledListSlice.emptyList(); 6804 } 6805 6806 @Override 6807 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6808 // reader 6809 synchronized (mPackages) { 6810 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6811 return PackageParser.generateInstrumentationInfo(i, flags); 6812 } 6813 } 6814 6815 @Override 6816 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6817 String targetPackage, int flags) { 6818 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6819 } 6820 6821 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6822 int flags) { 6823 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6824 6825 // reader 6826 synchronized (mPackages) { 6827 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6828 while (i.hasNext()) { 6829 final PackageParser.Instrumentation p = i.next(); 6830 if (targetPackage == null 6831 || targetPackage.equals(p.info.targetPackage)) { 6832 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6833 flags); 6834 if (ii != null) { 6835 finalList.add(ii); 6836 } 6837 } 6838 } 6839 } 6840 6841 return finalList; 6842 } 6843 6844 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6845 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6846 if (overlays == null) { 6847 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6848 return; 6849 } 6850 for (PackageParser.Package opkg : overlays.values()) { 6851 // Not much to do if idmap fails: we already logged the error 6852 // and we certainly don't want to abort installation of pkg simply 6853 // because an overlay didn't fit properly. For these reasons, 6854 // ignore the return value of createIdmapForPackagePairLI. 6855 createIdmapForPackagePairLI(pkg, opkg); 6856 } 6857 } 6858 6859 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6860 PackageParser.Package opkg) { 6861 if (!opkg.mTrustedOverlay) { 6862 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6863 opkg.baseCodePath + ": overlay not trusted"); 6864 return false; 6865 } 6866 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6867 if (overlaySet == null) { 6868 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6869 opkg.baseCodePath + " but target package has no known overlays"); 6870 return false; 6871 } 6872 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6873 // TODO: generate idmap for split APKs 6874 try { 6875 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6876 } catch (InstallerException e) { 6877 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6878 + opkg.baseCodePath); 6879 return false; 6880 } 6881 PackageParser.Package[] overlayArray = 6882 overlaySet.values().toArray(new PackageParser.Package[0]); 6883 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6884 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6885 return p1.mOverlayPriority - p2.mOverlayPriority; 6886 } 6887 }; 6888 Arrays.sort(overlayArray, cmp); 6889 6890 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6891 int i = 0; 6892 for (PackageParser.Package p : overlayArray) { 6893 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6894 } 6895 return true; 6896 } 6897 6898 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6899 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6900 try { 6901 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6902 } finally { 6903 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6904 } 6905 } 6906 6907 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6908 final File[] files = dir.listFiles(); 6909 if (ArrayUtils.isEmpty(files)) { 6910 Log.d(TAG, "No files in app dir " + dir); 6911 return; 6912 } 6913 6914 if (DEBUG_PACKAGE_SCANNING) { 6915 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6916 + " flags=0x" + Integer.toHexString(parseFlags)); 6917 } 6918 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6919 mSeparateProcesses, mOnlyCore, mMetrics); 6920 6921 // Submit files for parsing in parallel 6922 int fileCount = 0; 6923 for (File file : files) { 6924 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6925 && !PackageInstallerService.isStageName(file.getName()); 6926 if (!isPackage) { 6927 // Ignore entries which are not packages 6928 continue; 6929 } 6930 parallelPackageParser.submit(file, parseFlags); 6931 fileCount++; 6932 } 6933 6934 // Process results one by one 6935 for (; fileCount > 0; fileCount--) { 6936 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 6937 Throwable throwable = parseResult.throwable; 6938 int errorCode = PackageManager.INSTALL_SUCCEEDED; 6939 6940 if (throwable == null) { 6941 try { 6942 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 6943 currentTime, null); 6944 } catch (PackageManagerException e) { 6945 errorCode = e.error; 6946 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 6947 } 6948 } else if (throwable instanceof PackageParser.PackageParserException) { 6949 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 6950 throwable; 6951 errorCode = e.error; 6952 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 6953 } else { 6954 throw new IllegalStateException("Unexpected exception occurred while parsing " 6955 + parseResult.scanFile, throwable); 6956 } 6957 6958 // Delete invalid userdata apps 6959 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6960 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 6961 logCriticalInfo(Log.WARN, 6962 "Deleting invalid package at " + parseResult.scanFile); 6963 removeCodePathLI(parseResult.scanFile); 6964 } 6965 } 6966 parallelPackageParser.close(); 6967 } 6968 6969 private static File getSettingsProblemFile() { 6970 File dataDir = Environment.getDataDirectory(); 6971 File systemDir = new File(dataDir, "system"); 6972 File fname = new File(systemDir, "uiderrors.txt"); 6973 return fname; 6974 } 6975 6976 static void reportSettingsProblem(int priority, String msg) { 6977 logCriticalInfo(priority, msg); 6978 } 6979 6980 static void logCriticalInfo(int priority, String msg) { 6981 Slog.println(priority, TAG, msg); 6982 EventLogTags.writePmCriticalInfo(msg); 6983 try { 6984 File fname = getSettingsProblemFile(); 6985 FileOutputStream out = new FileOutputStream(fname, true); 6986 PrintWriter pw = new FastPrintWriter(out); 6987 SimpleDateFormat formatter = new SimpleDateFormat(); 6988 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6989 pw.println(dateString + ": " + msg); 6990 pw.close(); 6991 FileUtils.setPermissions( 6992 fname.toString(), 6993 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6994 -1, -1); 6995 } catch (java.io.IOException e) { 6996 } 6997 } 6998 6999 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7000 if (srcFile.isDirectory()) { 7001 final File baseFile = new File(pkg.baseCodePath); 7002 long maxModifiedTime = baseFile.lastModified(); 7003 if (pkg.splitCodePaths != null) { 7004 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7005 final File splitFile = new File(pkg.splitCodePaths[i]); 7006 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7007 } 7008 } 7009 return maxModifiedTime; 7010 } 7011 return srcFile.lastModified(); 7012 } 7013 7014 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7015 final int policyFlags) throws PackageManagerException { 7016 // When upgrading from pre-N MR1, verify the package time stamp using the package 7017 // directory and not the APK file. 7018 final long lastModifiedTime = mIsPreNMR1Upgrade 7019 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7020 if (ps != null 7021 && ps.codePath.equals(srcFile) 7022 && ps.timeStamp == lastModifiedTime 7023 && !isCompatSignatureUpdateNeeded(pkg) 7024 && !isRecoverSignatureUpdateNeeded(pkg)) { 7025 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7026 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7027 ArraySet<PublicKey> signingKs; 7028 synchronized (mPackages) { 7029 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7030 } 7031 if (ps.signatures.mSignatures != null 7032 && ps.signatures.mSignatures.length != 0 7033 && signingKs != null) { 7034 // Optimization: reuse the existing cached certificates 7035 // if the package appears to be unchanged. 7036 pkg.mSignatures = ps.signatures.mSignatures; 7037 pkg.mSigningKeys = signingKs; 7038 return; 7039 } 7040 7041 Slog.w(TAG, "PackageSetting for " + ps.name 7042 + " is missing signatures. Collecting certs again to recover them."); 7043 } else { 7044 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7045 } 7046 7047 try { 7048 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7049 PackageParser.collectCertificates(pkg, policyFlags); 7050 } catch (PackageParserException e) { 7051 throw PackageManagerException.from(e); 7052 } finally { 7053 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7054 } 7055 } 7056 7057 /** 7058 * Traces a package scan. 7059 * @see #scanPackageLI(File, int, int, long, UserHandle) 7060 */ 7061 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7062 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7063 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7064 try { 7065 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7066 } finally { 7067 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7068 } 7069 } 7070 7071 /** 7072 * Scans a package and returns the newly parsed package. 7073 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7074 */ 7075 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7076 long currentTime, UserHandle user) throws PackageManagerException { 7077 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7078 PackageParser pp = new PackageParser(); 7079 pp.setSeparateProcesses(mSeparateProcesses); 7080 pp.setOnlyCoreApps(mOnlyCore); 7081 pp.setDisplayMetrics(mMetrics); 7082 7083 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7084 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7085 } 7086 7087 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7088 final PackageParser.Package pkg; 7089 try { 7090 pkg = pp.parsePackage(scanFile, parseFlags); 7091 } catch (PackageParserException e) { 7092 throw PackageManagerException.from(e); 7093 } finally { 7094 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7095 } 7096 7097 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7098 } 7099 7100 /** 7101 * Scans a package and returns the newly parsed package. 7102 * @throws PackageManagerException on a parse error. 7103 */ 7104 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7105 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7106 throws PackageManagerException { 7107 // If the package has children and this is the first dive in the function 7108 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7109 // packages (parent and children) would be successfully scanned before the 7110 // actual scan since scanning mutates internal state and we want to atomically 7111 // install the package and its children. 7112 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7113 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7114 scanFlags |= SCAN_CHECK_ONLY; 7115 } 7116 } else { 7117 scanFlags &= ~SCAN_CHECK_ONLY; 7118 } 7119 7120 // Scan the parent 7121 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7122 scanFlags, currentTime, user); 7123 7124 // Scan the children 7125 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7126 for (int i = 0; i < childCount; i++) { 7127 PackageParser.Package childPackage = pkg.childPackages.get(i); 7128 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7129 currentTime, user); 7130 } 7131 7132 7133 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7134 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7135 } 7136 7137 return scannedPkg; 7138 } 7139 7140 /** 7141 * Scans a package and returns the newly parsed package. 7142 * @throws PackageManagerException on a parse error. 7143 */ 7144 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7145 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7146 throws PackageManagerException { 7147 PackageSetting ps = null; 7148 PackageSetting updatedPkg; 7149 // reader 7150 synchronized (mPackages) { 7151 // Look to see if we already know about this package. 7152 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7153 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7154 // This package has been renamed to its original name. Let's 7155 // use that. 7156 ps = mSettings.getPackageLPr(oldName); 7157 } 7158 // If there was no original package, see one for the real package name. 7159 if (ps == null) { 7160 ps = mSettings.getPackageLPr(pkg.packageName); 7161 } 7162 // Check to see if this package could be hiding/updating a system 7163 // package. Must look for it either under the original or real 7164 // package name depending on our state. 7165 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7166 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7167 7168 // If this is a package we don't know about on the system partition, we 7169 // may need to remove disabled child packages on the system partition 7170 // or may need to not add child packages if the parent apk is updated 7171 // on the data partition and no longer defines this child package. 7172 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7173 // If this is a parent package for an updated system app and this system 7174 // app got an OTA update which no longer defines some of the child packages 7175 // we have to prune them from the disabled system packages. 7176 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7177 if (disabledPs != null) { 7178 final int scannedChildCount = (pkg.childPackages != null) 7179 ? pkg.childPackages.size() : 0; 7180 final int disabledChildCount = disabledPs.childPackageNames != null 7181 ? disabledPs.childPackageNames.size() : 0; 7182 for (int i = 0; i < disabledChildCount; i++) { 7183 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7184 boolean disabledPackageAvailable = false; 7185 for (int j = 0; j < scannedChildCount; j++) { 7186 PackageParser.Package childPkg = pkg.childPackages.get(j); 7187 if (childPkg.packageName.equals(disabledChildPackageName)) { 7188 disabledPackageAvailable = true; 7189 break; 7190 } 7191 } 7192 if (!disabledPackageAvailable) { 7193 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7194 } 7195 } 7196 } 7197 } 7198 } 7199 7200 boolean updatedPkgBetter = false; 7201 // First check if this is a system package that may involve an update 7202 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7203 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7204 // it needs to drop FLAG_PRIVILEGED. 7205 if (locationIsPrivileged(scanFile)) { 7206 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7207 } else { 7208 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7209 } 7210 7211 if (ps != null && !ps.codePath.equals(scanFile)) { 7212 // The path has changed from what was last scanned... check the 7213 // version of the new path against what we have stored to determine 7214 // what to do. 7215 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7216 if (pkg.mVersionCode <= ps.versionCode) { 7217 // The system package has been updated and the code path does not match 7218 // Ignore entry. Skip it. 7219 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7220 + " ignored: updated version " + ps.versionCode 7221 + " better than this " + pkg.mVersionCode); 7222 if (!updatedPkg.codePath.equals(scanFile)) { 7223 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7224 + ps.name + " changing from " + updatedPkg.codePathString 7225 + " to " + scanFile); 7226 updatedPkg.codePath = scanFile; 7227 updatedPkg.codePathString = scanFile.toString(); 7228 updatedPkg.resourcePath = scanFile; 7229 updatedPkg.resourcePathString = scanFile.toString(); 7230 } 7231 updatedPkg.pkg = pkg; 7232 updatedPkg.versionCode = pkg.mVersionCode; 7233 7234 // Update the disabled system child packages to point to the package too. 7235 final int childCount = updatedPkg.childPackageNames != null 7236 ? updatedPkg.childPackageNames.size() : 0; 7237 for (int i = 0; i < childCount; i++) { 7238 String childPackageName = updatedPkg.childPackageNames.get(i); 7239 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7240 childPackageName); 7241 if (updatedChildPkg != null) { 7242 updatedChildPkg.pkg = pkg; 7243 updatedChildPkg.versionCode = pkg.mVersionCode; 7244 } 7245 } 7246 7247 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7248 + scanFile + " ignored: updated version " + ps.versionCode 7249 + " better than this " + pkg.mVersionCode); 7250 } else { 7251 // The current app on the system partition is better than 7252 // what we have updated to on the data partition; switch 7253 // back to the system partition version. 7254 // At this point, its safely assumed that package installation for 7255 // apps in system partition will go through. If not there won't be a working 7256 // version of the app 7257 // writer 7258 synchronized (mPackages) { 7259 // Just remove the loaded entries from package lists. 7260 mPackages.remove(ps.name); 7261 } 7262 7263 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7264 + " reverting from " + ps.codePathString 7265 + ": new version " + pkg.mVersionCode 7266 + " better than installed " + ps.versionCode); 7267 7268 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7269 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7270 synchronized (mInstallLock) { 7271 args.cleanUpResourcesLI(); 7272 } 7273 synchronized (mPackages) { 7274 mSettings.enableSystemPackageLPw(ps.name); 7275 } 7276 updatedPkgBetter = true; 7277 } 7278 } 7279 } 7280 7281 if (updatedPkg != null) { 7282 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7283 // initially 7284 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7285 7286 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7287 // flag set initially 7288 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7289 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7290 } 7291 } 7292 7293 // Verify certificates against what was last scanned 7294 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7295 7296 /* 7297 * A new system app appeared, but we already had a non-system one of the 7298 * same name installed earlier. 7299 */ 7300 boolean shouldHideSystemApp = false; 7301 if (updatedPkg == null && ps != null 7302 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7303 /* 7304 * Check to make sure the signatures match first. If they don't, 7305 * wipe the installed application and its data. 7306 */ 7307 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7308 != PackageManager.SIGNATURE_MATCH) { 7309 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7310 + " signatures don't match existing userdata copy; removing"); 7311 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7312 "scanPackageInternalLI")) { 7313 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7314 } 7315 ps = null; 7316 } else { 7317 /* 7318 * If the newly-added system app is an older version than the 7319 * already installed version, hide it. It will be scanned later 7320 * and re-added like an update. 7321 */ 7322 if (pkg.mVersionCode <= ps.versionCode) { 7323 shouldHideSystemApp = true; 7324 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7325 + " but new version " + pkg.mVersionCode + " better than installed " 7326 + ps.versionCode + "; hiding system"); 7327 } else { 7328 /* 7329 * The newly found system app is a newer version that the 7330 * one previously installed. Simply remove the 7331 * already-installed application and replace it with our own 7332 * while keeping the application data. 7333 */ 7334 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7335 + " reverting from " + ps.codePathString + ": new version " 7336 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7337 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7338 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7339 synchronized (mInstallLock) { 7340 args.cleanUpResourcesLI(); 7341 } 7342 } 7343 } 7344 } 7345 7346 // The apk is forward locked (not public) if its code and resources 7347 // are kept in different files. (except for app in either system or 7348 // vendor path). 7349 // TODO grab this value from PackageSettings 7350 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7351 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7352 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7353 } 7354 } 7355 7356 // TODO: extend to support forward-locked splits 7357 String resourcePath = null; 7358 String baseResourcePath = null; 7359 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7360 if (ps != null && ps.resourcePathString != null) { 7361 resourcePath = ps.resourcePathString; 7362 baseResourcePath = ps.resourcePathString; 7363 } else { 7364 // Should not happen at all. Just log an error. 7365 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7366 } 7367 } else { 7368 resourcePath = pkg.codePath; 7369 baseResourcePath = pkg.baseCodePath; 7370 } 7371 7372 // Set application objects path explicitly. 7373 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7374 pkg.setApplicationInfoCodePath(pkg.codePath); 7375 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7376 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7377 pkg.setApplicationInfoResourcePath(resourcePath); 7378 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7379 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7380 7381 // Note that we invoke the following method only if we are about to unpack an application 7382 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7383 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7384 7385 /* 7386 * If the system app should be overridden by a previously installed 7387 * data, hide the system app now and let the /data/app scan pick it up 7388 * again. 7389 */ 7390 if (shouldHideSystemApp) { 7391 synchronized (mPackages) { 7392 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7393 } 7394 } 7395 7396 return scannedPkg; 7397 } 7398 7399 private static String fixProcessName(String defProcessName, 7400 String processName) { 7401 if (processName == null) { 7402 return defProcessName; 7403 } 7404 return processName; 7405 } 7406 7407 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7408 throws PackageManagerException { 7409 if (pkgSetting.signatures.mSignatures != null) { 7410 // Already existing package. Make sure signatures match 7411 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7412 == PackageManager.SIGNATURE_MATCH; 7413 if (!match) { 7414 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7415 == PackageManager.SIGNATURE_MATCH; 7416 } 7417 if (!match) { 7418 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7419 == PackageManager.SIGNATURE_MATCH; 7420 } 7421 if (!match) { 7422 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7423 + pkg.packageName + " signatures do not match the " 7424 + "previously installed version; ignoring!"); 7425 } 7426 } 7427 7428 // Check for shared user signatures 7429 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7430 // Already existing package. Make sure signatures match 7431 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7432 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7433 if (!match) { 7434 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7435 == PackageManager.SIGNATURE_MATCH; 7436 } 7437 if (!match) { 7438 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7439 == PackageManager.SIGNATURE_MATCH; 7440 } 7441 if (!match) { 7442 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7443 "Package " + pkg.packageName 7444 + " has no signatures that match those in shared user " 7445 + pkgSetting.sharedUser.name + "; ignoring!"); 7446 } 7447 } 7448 } 7449 7450 /** 7451 * Enforces that only the system UID or root's UID can call a method exposed 7452 * via Binder. 7453 * 7454 * @param message used as message if SecurityException is thrown 7455 * @throws SecurityException if the caller is not system or root 7456 */ 7457 private static final void enforceSystemOrRoot(String message) { 7458 final int uid = Binder.getCallingUid(); 7459 if (uid != Process.SYSTEM_UID && uid != 0) { 7460 throw new SecurityException(message); 7461 } 7462 } 7463 7464 @Override 7465 public void performFstrimIfNeeded() { 7466 enforceSystemOrRoot("Only the system can request fstrim"); 7467 7468 // Before everything else, see whether we need to fstrim. 7469 try { 7470 IStorageManager sm = PackageHelper.getStorageManager(); 7471 if (sm != null) { 7472 boolean doTrim = false; 7473 final long interval = android.provider.Settings.Global.getLong( 7474 mContext.getContentResolver(), 7475 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7476 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7477 if (interval > 0) { 7478 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7479 if (timeSinceLast > interval) { 7480 doTrim = true; 7481 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7482 + "; running immediately"); 7483 } 7484 } 7485 if (doTrim) { 7486 final boolean dexOptDialogShown; 7487 synchronized (mPackages) { 7488 dexOptDialogShown = mDexOptDialogShown; 7489 } 7490 if (!isFirstBoot() && dexOptDialogShown) { 7491 try { 7492 ActivityManager.getService().showBootMessage( 7493 mContext.getResources().getString( 7494 R.string.android_upgrading_fstrim), true); 7495 } catch (RemoteException e) { 7496 } 7497 } 7498 sm.runMaintenance(); 7499 } 7500 } else { 7501 Slog.e(TAG, "storageManager service unavailable!"); 7502 } 7503 } catch (RemoteException e) { 7504 // Can't happen; StorageManagerService is local 7505 } 7506 } 7507 7508 @Override 7509 public void updatePackagesIfNeeded() { 7510 enforceSystemOrRoot("Only the system can request package update"); 7511 7512 // We need to re-extract after an OTA. 7513 boolean causeUpgrade = isUpgrade(); 7514 7515 // First boot or factory reset. 7516 // Note: we also handle devices that are upgrading to N right now as if it is their 7517 // first boot, as they do not have profile data. 7518 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7519 7520 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7521 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7522 7523 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7524 return; 7525 } 7526 7527 List<PackageParser.Package> pkgs; 7528 synchronized (mPackages) { 7529 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7530 } 7531 7532 final long startTime = System.nanoTime(); 7533 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7534 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7535 7536 final int elapsedTimeSeconds = 7537 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7538 7539 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7540 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7541 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7542 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7543 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7544 } 7545 7546 /** 7547 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7548 * containing statistics about the invocation. The array consists of three elements, 7549 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7550 * and {@code numberOfPackagesFailed}. 7551 */ 7552 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7553 String compilerFilter) { 7554 7555 int numberOfPackagesVisited = 0; 7556 int numberOfPackagesOptimized = 0; 7557 int numberOfPackagesSkipped = 0; 7558 int numberOfPackagesFailed = 0; 7559 final int numberOfPackagesToDexopt = pkgs.size(); 7560 7561 for (PackageParser.Package pkg : pkgs) { 7562 numberOfPackagesVisited++; 7563 7564 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7565 if (DEBUG_DEXOPT) { 7566 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7567 } 7568 numberOfPackagesSkipped++; 7569 continue; 7570 } 7571 7572 if (DEBUG_DEXOPT) { 7573 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7574 numberOfPackagesToDexopt + ": " + pkg.packageName); 7575 } 7576 7577 if (showDialog) { 7578 try { 7579 ActivityManager.getService().showBootMessage( 7580 mContext.getResources().getString(R.string.android_upgrading_apk, 7581 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7582 } catch (RemoteException e) { 7583 } 7584 synchronized (mPackages) { 7585 mDexOptDialogShown = true; 7586 } 7587 } 7588 7589 // If the OTA updates a system app which was previously preopted to a non-preopted state 7590 // the app might end up being verified at runtime. That's because by default the apps 7591 // are verify-profile but for preopted apps there's no profile. 7592 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7593 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7594 // filter (by default interpret-only). 7595 // Note that at this stage unused apps are already filtered. 7596 if (isSystemApp(pkg) && 7597 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7598 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7599 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7600 } 7601 7602 // If the OTA updates a system app which was previously preopted to a non-preopted state 7603 // the app might end up being verified at runtime. That's because by default the apps 7604 // are verify-profile but for preopted apps there's no profile. 7605 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7606 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7607 // filter (by default interpret-only). 7608 // Note that at this stage unused apps are already filtered. 7609 if (isSystemApp(pkg) && 7610 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7611 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7612 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7613 } 7614 7615 // checkProfiles is false to avoid merging profiles during boot which 7616 // might interfere with background compilation (b/28612421). 7617 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7618 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7619 // trade-off worth doing to save boot time work. 7620 int dexOptStatus = performDexOptTraced(pkg.packageName, 7621 false /* checkProfiles */, 7622 compilerFilter, 7623 false /* force */); 7624 switch (dexOptStatus) { 7625 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7626 numberOfPackagesOptimized++; 7627 break; 7628 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7629 numberOfPackagesSkipped++; 7630 break; 7631 case PackageDexOptimizer.DEX_OPT_FAILED: 7632 numberOfPackagesFailed++; 7633 break; 7634 default: 7635 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7636 break; 7637 } 7638 } 7639 7640 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7641 numberOfPackagesFailed }; 7642 } 7643 7644 @Override 7645 public void notifyPackageUse(String packageName, int reason) { 7646 synchronized (mPackages) { 7647 PackageParser.Package p = mPackages.get(packageName); 7648 if (p == null) { 7649 return; 7650 } 7651 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7652 } 7653 } 7654 7655 // TODO: this is not used nor needed. Delete it. 7656 @Override 7657 public boolean performDexOptIfNeeded(String packageName) { 7658 int dexOptStatus = performDexOptTraced(packageName, 7659 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7660 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7661 } 7662 7663 @Override 7664 public boolean performDexOpt(String packageName, 7665 boolean checkProfiles, int compileReason, boolean force) { 7666 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7667 getCompilerFilterForReason(compileReason), force); 7668 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7669 } 7670 7671 @Override 7672 public boolean performDexOptMode(String packageName, 7673 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7674 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7675 targetCompilerFilter, force); 7676 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7677 } 7678 7679 private int performDexOptTraced(String packageName, 7680 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7681 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7682 try { 7683 return performDexOptInternal(packageName, checkProfiles, 7684 targetCompilerFilter, force); 7685 } finally { 7686 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7687 } 7688 } 7689 7690 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7691 // if the package can now be considered up to date for the given filter. 7692 private int performDexOptInternal(String packageName, 7693 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7694 PackageParser.Package p; 7695 synchronized (mPackages) { 7696 p = mPackages.get(packageName); 7697 if (p == null) { 7698 // Package could not be found. Report failure. 7699 return PackageDexOptimizer.DEX_OPT_FAILED; 7700 } 7701 mPackageUsage.maybeWriteAsync(mPackages); 7702 mCompilerStats.maybeWriteAsync(); 7703 } 7704 long callingId = Binder.clearCallingIdentity(); 7705 try { 7706 synchronized (mInstallLock) { 7707 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7708 targetCompilerFilter, force); 7709 } 7710 } finally { 7711 Binder.restoreCallingIdentity(callingId); 7712 } 7713 } 7714 7715 public ArraySet<String> getOptimizablePackages() { 7716 ArraySet<String> pkgs = new ArraySet<String>(); 7717 synchronized (mPackages) { 7718 for (PackageParser.Package p : mPackages.values()) { 7719 if (PackageDexOptimizer.canOptimizePackage(p)) { 7720 pkgs.add(p.packageName); 7721 } 7722 } 7723 } 7724 return pkgs; 7725 } 7726 7727 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7728 boolean checkProfiles, String targetCompilerFilter, 7729 boolean force) { 7730 // Select the dex optimizer based on the force parameter. 7731 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7732 // allocate an object here. 7733 PackageDexOptimizer pdo = force 7734 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7735 : mPackageDexOptimizer; 7736 7737 // Optimize all dependencies first. Note: we ignore the return value and march on 7738 // on errors. 7739 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7740 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7741 if (!deps.isEmpty()) { 7742 for (PackageParser.Package depPackage : deps) { 7743 // TODO: Analyze and investigate if we (should) profile libraries. 7744 // Currently this will do a full compilation of the library by default. 7745 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7746 false /* checkProfiles */, 7747 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7748 getOrCreateCompilerPackageStats(depPackage)); 7749 } 7750 } 7751 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7752 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7753 } 7754 7755 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7756 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7757 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7758 Set<String> collectedNames = new HashSet<>(); 7759 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7760 7761 retValue.remove(p); 7762 7763 return retValue; 7764 } else { 7765 return Collections.emptyList(); 7766 } 7767 } 7768 7769 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7770 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7771 if (!collectedNames.contains(p.packageName)) { 7772 collectedNames.add(p.packageName); 7773 collected.add(p); 7774 7775 if (p.usesLibraries != null) { 7776 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7777 } 7778 if (p.usesOptionalLibraries != null) { 7779 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7780 collectedNames); 7781 } 7782 } 7783 } 7784 7785 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7786 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7787 for (String libName : libs) { 7788 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7789 if (libPkg != null) { 7790 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7791 } 7792 } 7793 } 7794 7795 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7796 synchronized (mPackages) { 7797 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7798 if (lib != null && lib.apk != null) { 7799 return mPackages.get(lib.apk); 7800 } 7801 } 7802 return null; 7803 } 7804 7805 public void shutdown() { 7806 mPackageUsage.writeNow(mPackages); 7807 mCompilerStats.writeNow(); 7808 } 7809 7810 @Override 7811 public void dumpProfiles(String packageName) { 7812 PackageParser.Package pkg; 7813 synchronized (mPackages) { 7814 pkg = mPackages.get(packageName); 7815 if (pkg == null) { 7816 throw new IllegalArgumentException("Unknown package: " + packageName); 7817 } 7818 } 7819 /* Only the shell, root, or the app user should be able to dump profiles. */ 7820 int callingUid = Binder.getCallingUid(); 7821 if (callingUid != Process.SHELL_UID && 7822 callingUid != Process.ROOT_UID && 7823 callingUid != pkg.applicationInfo.uid) { 7824 throw new SecurityException("dumpProfiles"); 7825 } 7826 7827 synchronized (mInstallLock) { 7828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7829 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7830 try { 7831 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7832 String codePaths = TextUtils.join(";", allCodePaths); 7833 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7834 } catch (InstallerException e) { 7835 Slog.w(TAG, "Failed to dump profiles", e); 7836 } 7837 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7838 } 7839 } 7840 7841 @Override 7842 public void forceDexOpt(String packageName) { 7843 enforceSystemOrRoot("forceDexOpt"); 7844 7845 PackageParser.Package pkg; 7846 synchronized (mPackages) { 7847 pkg = mPackages.get(packageName); 7848 if (pkg == null) { 7849 throw new IllegalArgumentException("Unknown package: " + packageName); 7850 } 7851 } 7852 7853 synchronized (mInstallLock) { 7854 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7855 7856 // Whoever is calling forceDexOpt wants a fully compiled package. 7857 // Don't use profiles since that may cause compilation to be skipped. 7858 final int res = performDexOptInternalWithDependenciesLI(pkg, 7859 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7860 true /* force */); 7861 7862 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7863 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7864 throw new IllegalStateException("Failed to dexopt: " + res); 7865 } 7866 } 7867 } 7868 7869 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7870 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7871 Slog.w(TAG, "Unable to update from " + oldPkg.name 7872 + " to " + newPkg.packageName 7873 + ": old package not in system partition"); 7874 return false; 7875 } else if (mPackages.get(oldPkg.name) != null) { 7876 Slog.w(TAG, "Unable to update from " + oldPkg.name 7877 + " to " + newPkg.packageName 7878 + ": old package still exists"); 7879 return false; 7880 } 7881 return true; 7882 } 7883 7884 void removeCodePathLI(File codePath) { 7885 if (codePath.isDirectory()) { 7886 try { 7887 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7888 } catch (InstallerException e) { 7889 Slog.w(TAG, "Failed to remove code path", e); 7890 } 7891 } else { 7892 codePath.delete(); 7893 } 7894 } 7895 7896 private int[] resolveUserIds(int userId) { 7897 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7898 } 7899 7900 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7901 if (pkg == null) { 7902 Slog.wtf(TAG, "Package was null!", new Throwable()); 7903 return; 7904 } 7905 clearAppDataLeafLIF(pkg, userId, flags); 7906 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7907 for (int i = 0; i < childCount; i++) { 7908 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7909 } 7910 } 7911 7912 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7913 final PackageSetting ps; 7914 synchronized (mPackages) { 7915 ps = mSettings.mPackages.get(pkg.packageName); 7916 } 7917 for (int realUserId : resolveUserIds(userId)) { 7918 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7919 try { 7920 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7921 ceDataInode); 7922 } catch (InstallerException e) { 7923 Slog.w(TAG, String.valueOf(e)); 7924 } 7925 } 7926 } 7927 7928 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7929 if (pkg == null) { 7930 Slog.wtf(TAG, "Package was null!", new Throwable()); 7931 return; 7932 } 7933 destroyAppDataLeafLIF(pkg, userId, flags); 7934 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7935 for (int i = 0; i < childCount; i++) { 7936 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7937 } 7938 } 7939 7940 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7941 final PackageSetting ps; 7942 synchronized (mPackages) { 7943 ps = mSettings.mPackages.get(pkg.packageName); 7944 } 7945 for (int realUserId : resolveUserIds(userId)) { 7946 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7947 try { 7948 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7949 ceDataInode); 7950 } catch (InstallerException e) { 7951 Slog.w(TAG, String.valueOf(e)); 7952 } 7953 } 7954 } 7955 7956 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7957 if (pkg == null) { 7958 Slog.wtf(TAG, "Package was null!", new Throwable()); 7959 return; 7960 } 7961 destroyAppProfilesLeafLIF(pkg); 7962 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7963 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7964 for (int i = 0; i < childCount; i++) { 7965 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7966 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7967 true /* removeBaseMarker */); 7968 } 7969 } 7970 7971 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7972 boolean removeBaseMarker) { 7973 if (pkg.isForwardLocked()) { 7974 return; 7975 } 7976 7977 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7978 try { 7979 path = PackageManagerServiceUtils.realpath(new File(path)); 7980 } catch (IOException e) { 7981 // TODO: Should we return early here ? 7982 Slog.w(TAG, "Failed to get canonical path", e); 7983 continue; 7984 } 7985 7986 final String useMarker = path.replace('/', '@'); 7987 for (int realUserId : resolveUserIds(userId)) { 7988 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7989 if (removeBaseMarker) { 7990 File foreignUseMark = new File(profileDir, useMarker); 7991 if (foreignUseMark.exists()) { 7992 if (!foreignUseMark.delete()) { 7993 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7994 + pkg.packageName); 7995 } 7996 } 7997 } 7998 7999 File[] markers = profileDir.listFiles(); 8000 if (markers != null) { 8001 final String searchString = "@" + pkg.packageName + "@"; 8002 // We also delete all markers that contain the package name we're 8003 // uninstalling. These are associated with secondary dex-files belonging 8004 // to the package. Reconstructing the path of these dex files is messy 8005 // in general. 8006 for (File marker : markers) { 8007 if (marker.getName().indexOf(searchString) > 0) { 8008 if (!marker.delete()) { 8009 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8010 + pkg.packageName); 8011 } 8012 } 8013 } 8014 } 8015 } 8016 } 8017 } 8018 8019 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8020 try { 8021 mInstaller.destroyAppProfiles(pkg.packageName); 8022 } catch (InstallerException e) { 8023 Slog.w(TAG, String.valueOf(e)); 8024 } 8025 } 8026 8027 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8028 if (pkg == null) { 8029 Slog.wtf(TAG, "Package was null!", new Throwable()); 8030 return; 8031 } 8032 clearAppProfilesLeafLIF(pkg); 8033 // We don't remove the base foreign use marker when clearing profiles because 8034 // we will rename it when the app is updated. Unlike the actual profile contents, 8035 // the foreign use marker is good across installs. 8036 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8037 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8038 for (int i = 0; i < childCount; i++) { 8039 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8040 } 8041 } 8042 8043 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8044 try { 8045 mInstaller.clearAppProfiles(pkg.packageName); 8046 } catch (InstallerException e) { 8047 Slog.w(TAG, String.valueOf(e)); 8048 } 8049 } 8050 8051 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8052 long lastUpdateTime) { 8053 // Set parent install/update time 8054 PackageSetting ps = (PackageSetting) pkg.mExtras; 8055 if (ps != null) { 8056 ps.firstInstallTime = firstInstallTime; 8057 ps.lastUpdateTime = lastUpdateTime; 8058 } 8059 // Set children install/update time 8060 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8061 for (int i = 0; i < childCount; i++) { 8062 PackageParser.Package childPkg = pkg.childPackages.get(i); 8063 ps = (PackageSetting) childPkg.mExtras; 8064 if (ps != null) { 8065 ps.firstInstallTime = firstInstallTime; 8066 ps.lastUpdateTime = lastUpdateTime; 8067 } 8068 } 8069 } 8070 8071 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8072 PackageParser.Package changingLib) { 8073 if (file.path != null) { 8074 usesLibraryFiles.add(file.path); 8075 return; 8076 } 8077 PackageParser.Package p = mPackages.get(file.apk); 8078 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8079 // If we are doing this while in the middle of updating a library apk, 8080 // then we need to make sure to use that new apk for determining the 8081 // dependencies here. (We haven't yet finished committing the new apk 8082 // to the package manager state.) 8083 if (p == null || p.packageName.equals(changingLib.packageName)) { 8084 p = changingLib; 8085 } 8086 } 8087 if (p != null) { 8088 usesLibraryFiles.addAll(p.getAllCodePaths()); 8089 } 8090 } 8091 8092 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8093 PackageParser.Package changingLib) throws PackageManagerException { 8094 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8095 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8096 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8097 for (int i=0; i<N; i++) { 8098 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8099 if (file == null) { 8100 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8101 "Package " + pkg.packageName + " requires unavailable shared library " 8102 + pkg.usesLibraries.get(i) + "; failing!"); 8103 } 8104 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8105 } 8106 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8107 for (int i=0; i<N; i++) { 8108 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8109 if (file == null) { 8110 Slog.w(TAG, "Package " + pkg.packageName 8111 + " desires unavailable shared library " 8112 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8113 } else { 8114 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8115 } 8116 } 8117 N = usesLibraryFiles.size(); 8118 if (N > 0) { 8119 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8120 } else { 8121 pkg.usesLibraryFiles = null; 8122 } 8123 } 8124 } 8125 8126 private static boolean hasString(List<String> list, List<String> which) { 8127 if (list == null) { 8128 return false; 8129 } 8130 for (int i=list.size()-1; i>=0; i--) { 8131 for (int j=which.size()-1; j>=0; j--) { 8132 if (which.get(j).equals(list.get(i))) { 8133 return true; 8134 } 8135 } 8136 } 8137 return false; 8138 } 8139 8140 private void updateAllSharedLibrariesLPw() { 8141 for (PackageParser.Package pkg : mPackages.values()) { 8142 try { 8143 updateSharedLibrariesLPr(pkg, null); 8144 } catch (PackageManagerException e) { 8145 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8146 } 8147 } 8148 } 8149 8150 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8151 PackageParser.Package changingPkg) { 8152 ArrayList<PackageParser.Package> res = null; 8153 for (PackageParser.Package pkg : mPackages.values()) { 8154 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8155 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8156 if (res == null) { 8157 res = new ArrayList<PackageParser.Package>(); 8158 } 8159 res.add(pkg); 8160 try { 8161 updateSharedLibrariesLPr(pkg, changingPkg); 8162 } catch (PackageManagerException e) { 8163 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8164 } 8165 } 8166 } 8167 return res; 8168 } 8169 8170 /** 8171 * Derive the value of the {@code cpuAbiOverride} based on the provided 8172 * value and an optional stored value from the package settings. 8173 */ 8174 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8175 String cpuAbiOverride = null; 8176 8177 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8178 cpuAbiOverride = null; 8179 } else if (abiOverride != null) { 8180 cpuAbiOverride = abiOverride; 8181 } else if (settings != null) { 8182 cpuAbiOverride = settings.cpuAbiOverrideString; 8183 } 8184 8185 return cpuAbiOverride; 8186 } 8187 8188 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8189 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8190 throws PackageManagerException { 8191 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8192 // If the package has children and this is the first dive in the function 8193 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8194 // whether all packages (parent and children) would be successfully scanned 8195 // before the actual scan since scanning mutates internal state and we want 8196 // to atomically install the package and its children. 8197 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8198 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8199 scanFlags |= SCAN_CHECK_ONLY; 8200 } 8201 } else { 8202 scanFlags &= ~SCAN_CHECK_ONLY; 8203 } 8204 8205 final PackageParser.Package scannedPkg; 8206 try { 8207 // Scan the parent 8208 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8209 // Scan the children 8210 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8211 for (int i = 0; i < childCount; i++) { 8212 PackageParser.Package childPkg = pkg.childPackages.get(i); 8213 scanPackageLI(childPkg, policyFlags, 8214 scanFlags, currentTime, user); 8215 } 8216 } finally { 8217 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8218 } 8219 8220 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8221 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8222 } 8223 8224 return scannedPkg; 8225 } 8226 8227 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8228 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8229 boolean success = false; 8230 try { 8231 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8232 currentTime, user); 8233 success = true; 8234 return res; 8235 } finally { 8236 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8237 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8238 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8239 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8240 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8241 } 8242 } 8243 } 8244 8245 /** 8246 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8247 */ 8248 private static boolean apkHasCode(String fileName) { 8249 StrictJarFile jarFile = null; 8250 try { 8251 jarFile = new StrictJarFile(fileName, 8252 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8253 return jarFile.findEntry("classes.dex") != null; 8254 } catch (IOException ignore) { 8255 } finally { 8256 try { 8257 if (jarFile != null) { 8258 jarFile.close(); 8259 } 8260 } catch (IOException ignore) {} 8261 } 8262 return false; 8263 } 8264 8265 /** 8266 * Enforces code policy for the package. This ensures that if an APK has 8267 * declared hasCode="true" in its manifest that the APK actually contains 8268 * code. 8269 * 8270 * @throws PackageManagerException If bytecode could not be found when it should exist 8271 */ 8272 private static void assertCodePolicy(PackageParser.Package pkg) 8273 throws PackageManagerException { 8274 final boolean shouldHaveCode = 8275 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8276 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8277 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8278 "Package " + pkg.baseCodePath + " code is missing"); 8279 } 8280 8281 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8282 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8283 final boolean splitShouldHaveCode = 8284 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8285 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8286 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8287 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8288 } 8289 } 8290 } 8291 } 8292 8293 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8294 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8295 throws PackageManagerException { 8296 if (DEBUG_PACKAGE_SCANNING) { 8297 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8298 Log.d(TAG, "Scanning package " + pkg.packageName); 8299 } 8300 8301 applyPolicy(pkg, policyFlags); 8302 8303 assertPackageIsValid(pkg, policyFlags, scanFlags); 8304 8305 // Initialize package source and resource directories 8306 final File scanFile = new File(pkg.codePath); 8307 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8308 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8309 8310 SharedUserSetting suid = null; 8311 PackageSetting pkgSetting = null; 8312 8313 // Getting the package setting may have a side-effect, so if we 8314 // are only checking if scan would succeed, stash a copy of the 8315 // old setting to restore at the end. 8316 PackageSetting nonMutatedPs = null; 8317 8318 // We keep references to the derived CPU Abis from settings in oder to reuse 8319 // them in the case where we're not upgrading or booting for the first time. 8320 String primaryCpuAbiFromSettings = null; 8321 String secondaryCpuAbiFromSettings = null; 8322 8323 // writer 8324 synchronized (mPackages) { 8325 if (pkg.mSharedUserId != null) { 8326 // SIDE EFFECTS; may potentially allocate a new shared user 8327 suid = mSettings.getSharedUserLPw( 8328 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8329 if (DEBUG_PACKAGE_SCANNING) { 8330 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8331 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8332 + "): packages=" + suid.packages); 8333 } 8334 } 8335 8336 // Check if we are renaming from an original package name. 8337 PackageSetting origPackage = null; 8338 String realName = null; 8339 if (pkg.mOriginalPackages != null) { 8340 // This package may need to be renamed to a previously 8341 // installed name. Let's check on that... 8342 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8343 if (pkg.mOriginalPackages.contains(renamed)) { 8344 // This package had originally been installed as the 8345 // original name, and we have already taken care of 8346 // transitioning to the new one. Just update the new 8347 // one to continue using the old name. 8348 realName = pkg.mRealPackage; 8349 if (!pkg.packageName.equals(renamed)) { 8350 // Callers into this function may have already taken 8351 // care of renaming the package; only do it here if 8352 // it is not already done. 8353 pkg.setPackageName(renamed); 8354 } 8355 } else { 8356 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8357 if ((origPackage = mSettings.getPackageLPr( 8358 pkg.mOriginalPackages.get(i))) != null) { 8359 // We do have the package already installed under its 8360 // original name... should we use it? 8361 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8362 // New package is not compatible with original. 8363 origPackage = null; 8364 continue; 8365 } else if (origPackage.sharedUser != null) { 8366 // Make sure uid is compatible between packages. 8367 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8368 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8369 + " to " + pkg.packageName + ": old uid " 8370 + origPackage.sharedUser.name 8371 + " differs from " + pkg.mSharedUserId); 8372 origPackage = null; 8373 continue; 8374 } 8375 // TODO: Add case when shared user id is added [b/28144775] 8376 } else { 8377 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8378 + pkg.packageName + " to old name " + origPackage.name); 8379 } 8380 break; 8381 } 8382 } 8383 } 8384 } 8385 8386 if (mTransferedPackages.contains(pkg.packageName)) { 8387 Slog.w(TAG, "Package " + pkg.packageName 8388 + " was transferred to another, but its .apk remains"); 8389 } 8390 8391 // See comments in nonMutatedPs declaration 8392 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8393 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8394 if (foundPs != null) { 8395 nonMutatedPs = new PackageSetting(foundPs); 8396 } 8397 } 8398 8399 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8400 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8401 if (foundPs != null) { 8402 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8403 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8404 } 8405 } 8406 8407 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8408 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8409 PackageManagerService.reportSettingsProblem(Log.WARN, 8410 "Package " + pkg.packageName + " shared user changed from " 8411 + (pkgSetting.sharedUser != null 8412 ? pkgSetting.sharedUser.name : "<nothing>") 8413 + " to " 8414 + (suid != null ? suid.name : "<nothing>") 8415 + "; replacing with new"); 8416 pkgSetting = null; 8417 } 8418 final PackageSetting oldPkgSetting = 8419 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8420 final PackageSetting disabledPkgSetting = 8421 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8422 if (pkgSetting == null) { 8423 final String parentPackageName = (pkg.parentPackage != null) 8424 ? pkg.parentPackage.packageName : null; 8425 // REMOVE SharedUserSetting from method; update in a separate call 8426 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8427 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8428 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8429 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8430 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8431 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8432 UserManagerService.getInstance()); 8433 // SIDE EFFECTS; updates system state; move elsewhere 8434 if (origPackage != null) { 8435 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8436 } 8437 mSettings.addUserToSettingLPw(pkgSetting); 8438 } else { 8439 // REMOVE SharedUserSetting from method; update in a separate call. 8440 // 8441 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8442 // secondaryCpuAbi are not known at this point so we always update them 8443 // to null here, only to reset them at a later point. 8444 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8445 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8446 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8447 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8448 UserManagerService.getInstance()); 8449 } 8450 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8451 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8452 8453 // SIDE EFFECTS; modifies system state; move elsewhere 8454 if (pkgSetting.origPackage != null) { 8455 // If we are first transitioning from an original package, 8456 // fix up the new package's name now. We need to do this after 8457 // looking up the package under its new name, so getPackageLP 8458 // can take care of fiddling things correctly. 8459 pkg.setPackageName(origPackage.name); 8460 8461 // File a report about this. 8462 String msg = "New package " + pkgSetting.realName 8463 + " renamed to replace old package " + pkgSetting.name; 8464 reportSettingsProblem(Log.WARN, msg); 8465 8466 // Make a note of it. 8467 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8468 mTransferedPackages.add(origPackage.name); 8469 } 8470 8471 // No longer need to retain this. 8472 pkgSetting.origPackage = null; 8473 } 8474 8475 // SIDE EFFECTS; modifies system state; move elsewhere 8476 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8477 // Make a note of it. 8478 mTransferedPackages.add(pkg.packageName); 8479 } 8480 8481 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8482 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8483 } 8484 8485 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8486 // Check all shared libraries and map to their actual file path. 8487 // We only do this here for apps not on a system dir, because those 8488 // are the only ones that can fail an install due to this. We 8489 // will take care of the system apps by updating all of their 8490 // library paths after the scan is done. 8491 updateSharedLibrariesLPr(pkg, null); 8492 } 8493 8494 if (mFoundPolicyFile) { 8495 SELinuxMMAC.assignSeinfoValue(pkg); 8496 } 8497 8498 pkg.applicationInfo.uid = pkgSetting.appId; 8499 pkg.mExtras = pkgSetting; 8500 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8501 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8502 // We just determined the app is signed correctly, so bring 8503 // over the latest parsed certs. 8504 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8505 } else { 8506 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8507 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8508 "Package " + pkg.packageName + " upgrade keys do not match the " 8509 + "previously installed version"); 8510 } else { 8511 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8512 String msg = "System package " + pkg.packageName 8513 + " signature changed; retaining data."; 8514 reportSettingsProblem(Log.WARN, msg); 8515 } 8516 } 8517 } else { 8518 try { 8519 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8520 verifySignaturesLP(pkgSetting, pkg); 8521 // We just determined the app is signed correctly, so bring 8522 // over the latest parsed certs. 8523 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8524 } catch (PackageManagerException e) { 8525 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8526 throw e; 8527 } 8528 // The signature has changed, but this package is in the system 8529 // image... let's recover! 8530 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8531 // However... if this package is part of a shared user, but it 8532 // doesn't match the signature of the shared user, let's fail. 8533 // What this means is that you can't change the signatures 8534 // associated with an overall shared user, which doesn't seem all 8535 // that unreasonable. 8536 if (pkgSetting.sharedUser != null) { 8537 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8538 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8539 throw new PackageManagerException( 8540 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8541 "Signature mismatch for shared user: " 8542 + pkgSetting.sharedUser); 8543 } 8544 } 8545 // File a report about this. 8546 String msg = "System package " + pkg.packageName 8547 + " signature changed; retaining data."; 8548 reportSettingsProblem(Log.WARN, msg); 8549 } 8550 } 8551 8552 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8553 // This package wants to adopt ownership of permissions from 8554 // another package. 8555 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8556 final String origName = pkg.mAdoptPermissions.get(i); 8557 final PackageSetting orig = mSettings.getPackageLPr(origName); 8558 if (orig != null) { 8559 if (verifyPackageUpdateLPr(orig, pkg)) { 8560 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8561 + pkg.packageName); 8562 // SIDE EFFECTS; updates permissions system state; move elsewhere 8563 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8564 } 8565 } 8566 } 8567 } 8568 } 8569 8570 pkg.applicationInfo.processName = fixProcessName( 8571 pkg.applicationInfo.packageName, 8572 pkg.applicationInfo.processName); 8573 8574 if (pkg != mPlatformPackage) { 8575 // Get all of our default paths setup 8576 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8577 } 8578 8579 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8580 8581 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8582 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8583 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8584 derivePackageAbi( 8585 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8586 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8587 8588 // Some system apps still use directory structure for native libraries 8589 // in which case we might end up not detecting abi solely based on apk 8590 // structure. Try to detect abi based on directory structure. 8591 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8592 pkg.applicationInfo.primaryCpuAbi == null) { 8593 setBundledAppAbisAndRoots(pkg, pkgSetting); 8594 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8595 } 8596 } else { 8597 // This is not a first boot or an upgrade, don't bother deriving the 8598 // ABI during the scan. Instead, trust the value that was stored in the 8599 // package setting. 8600 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8601 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8602 8603 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8604 8605 if (DEBUG_ABI_SELECTION) { 8606 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8607 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8608 pkg.applicationInfo.secondaryCpuAbi); 8609 } 8610 } 8611 } else { 8612 if ((scanFlags & SCAN_MOVE) != 0) { 8613 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8614 // but we already have this packages package info in the PackageSetting. We just 8615 // use that and derive the native library path based on the new codepath. 8616 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8617 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8618 } 8619 8620 // Set native library paths again. For moves, the path will be updated based on the 8621 // ABIs we've determined above. For non-moves, the path will be updated based on the 8622 // ABIs we determined during compilation, but the path will depend on the final 8623 // package path (after the rename away from the stage path). 8624 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8625 } 8626 8627 // This is a special case for the "system" package, where the ABI is 8628 // dictated by the zygote configuration (and init.rc). We should keep track 8629 // of this ABI so that we can deal with "normal" applications that run under 8630 // the same UID correctly. 8631 if (mPlatformPackage == pkg) { 8632 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8633 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8634 } 8635 8636 // If there's a mismatch between the abi-override in the package setting 8637 // and the abiOverride specified for the install. Warn about this because we 8638 // would've already compiled the app without taking the package setting into 8639 // account. 8640 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8641 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8642 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8643 " for package " + pkg.packageName); 8644 } 8645 } 8646 8647 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8648 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8649 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8650 8651 // Copy the derived override back to the parsed package, so that we can 8652 // update the package settings accordingly. 8653 pkg.cpuAbiOverride = cpuAbiOverride; 8654 8655 if (DEBUG_ABI_SELECTION) { 8656 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8657 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8658 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8659 } 8660 8661 // Push the derived path down into PackageSettings so we know what to 8662 // clean up at uninstall time. 8663 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8664 8665 if (DEBUG_ABI_SELECTION) { 8666 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8667 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8668 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8669 } 8670 8671 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8672 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8673 // We don't do this here during boot because we can do it all 8674 // at once after scanning all existing packages. 8675 // 8676 // We also do this *before* we perform dexopt on this package, so that 8677 // we can avoid redundant dexopts, and also to make sure we've got the 8678 // code and package path correct. 8679 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8680 } 8681 8682 if (mFactoryTest && pkg.requestedPermissions.contains( 8683 android.Manifest.permission.FACTORY_TEST)) { 8684 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8685 } 8686 8687 if (isSystemApp(pkg)) { 8688 pkgSetting.isOrphaned = true; 8689 } 8690 8691 // Take care of first install / last update times. 8692 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8693 if (currentTime != 0) { 8694 if (pkgSetting.firstInstallTime == 0) { 8695 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8696 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8697 pkgSetting.lastUpdateTime = currentTime; 8698 } 8699 } else if (pkgSetting.firstInstallTime == 0) { 8700 // We need *something*. Take time time stamp of the file. 8701 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8702 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8703 if (scanFileTime != pkgSetting.timeStamp) { 8704 // A package on the system image has changed; consider this 8705 // to be an update. 8706 pkgSetting.lastUpdateTime = scanFileTime; 8707 } 8708 } 8709 pkgSetting.setTimeStamp(scanFileTime); 8710 8711 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8712 if (nonMutatedPs != null) { 8713 synchronized (mPackages) { 8714 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8715 } 8716 } 8717 } else { 8718 // Modify state for the given package setting 8719 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8720 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8721 } 8722 return pkg; 8723 } 8724 8725 /** 8726 * Applies policy to the parsed package based upon the given policy flags. 8727 * Ensures the package is in a good state. 8728 * <p> 8729 * Implementation detail: This method must NOT have any side effect. It would 8730 * ideally be static, but, it requires locks to read system state. 8731 */ 8732 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8733 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8734 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8735 if (pkg.applicationInfo.isDirectBootAware()) { 8736 // we're direct boot aware; set for all components 8737 for (PackageParser.Service s : pkg.services) { 8738 s.info.encryptionAware = s.info.directBootAware = true; 8739 } 8740 for (PackageParser.Provider p : pkg.providers) { 8741 p.info.encryptionAware = p.info.directBootAware = true; 8742 } 8743 for (PackageParser.Activity a : pkg.activities) { 8744 a.info.encryptionAware = a.info.directBootAware = true; 8745 } 8746 for (PackageParser.Activity r : pkg.receivers) { 8747 r.info.encryptionAware = r.info.directBootAware = true; 8748 } 8749 } 8750 } else { 8751 // Only allow system apps to be flagged as core apps. 8752 pkg.coreApp = false; 8753 // clear flags not applicable to regular apps 8754 pkg.applicationInfo.privateFlags &= 8755 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8756 pkg.applicationInfo.privateFlags &= 8757 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8758 } 8759 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8760 8761 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8762 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8763 } 8764 8765 if (!isSystemApp(pkg)) { 8766 // Only system apps can use these features. 8767 pkg.mOriginalPackages = null; 8768 pkg.mRealPackage = null; 8769 pkg.mAdoptPermissions = null; 8770 } 8771 } 8772 8773 /** 8774 * Asserts the parsed package is valid according to teh given policy. If the 8775 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8776 * <p> 8777 * Implementation detail: This method must NOT have any side effects. It would 8778 * ideally be static, but, it requires locks to read system state. 8779 * 8780 * @throws PackageManagerException If the package fails any of the validation checks 8781 */ 8782 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8783 throws PackageManagerException { 8784 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8785 assertCodePolicy(pkg); 8786 } 8787 8788 if (pkg.applicationInfo.getCodePath() == null || 8789 pkg.applicationInfo.getResourcePath() == null) { 8790 // Bail out. The resource and code paths haven't been set. 8791 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8792 "Code and resource paths haven't been set correctly"); 8793 } 8794 8795 // Make sure we're not adding any bogus keyset info 8796 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8797 ksms.assertScannedPackageValid(pkg); 8798 8799 synchronized (mPackages) { 8800 // The special "android" package can only be defined once 8801 if (pkg.packageName.equals("android")) { 8802 if (mAndroidApplication != null) { 8803 Slog.w(TAG, "*************************************************"); 8804 Slog.w(TAG, "Core android package being redefined. Skipping."); 8805 Slog.w(TAG, " codePath=" + pkg.codePath); 8806 Slog.w(TAG, "*************************************************"); 8807 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8808 "Core android package being redefined. Skipping."); 8809 } 8810 } 8811 8812 // A package name must be unique; don't allow duplicates 8813 if (mPackages.containsKey(pkg.packageName) 8814 || mSharedLibraries.containsKey(pkg.packageName)) { 8815 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8816 "Application package " + pkg.packageName 8817 + " already installed. Skipping duplicate."); 8818 } 8819 8820 // Only privileged apps and updated privileged apps can add child packages. 8821 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8822 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8823 throw new PackageManagerException("Only privileged apps can add child " 8824 + "packages. Ignoring package " + pkg.packageName); 8825 } 8826 final int childCount = pkg.childPackages.size(); 8827 for (int i = 0; i < childCount; i++) { 8828 PackageParser.Package childPkg = pkg.childPackages.get(i); 8829 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8830 childPkg.packageName)) { 8831 throw new PackageManagerException("Can't override child of " 8832 + "another disabled app. Ignoring package " + pkg.packageName); 8833 } 8834 } 8835 } 8836 8837 // If we're only installing presumed-existing packages, require that the 8838 // scanned APK is both already known and at the path previously established 8839 // for it. Previously unknown packages we pick up normally, but if we have an 8840 // a priori expectation about this package's install presence, enforce it. 8841 // With a singular exception for new system packages. When an OTA contains 8842 // a new system package, we allow the codepath to change from a system location 8843 // to the user-installed location. If we don't allow this change, any newer, 8844 // user-installed version of the application will be ignored. 8845 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8846 if (mExpectingBetter.containsKey(pkg.packageName)) { 8847 logCriticalInfo(Log.WARN, 8848 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8849 } else { 8850 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8851 if (known != null) { 8852 if (DEBUG_PACKAGE_SCANNING) { 8853 Log.d(TAG, "Examining " + pkg.codePath 8854 + " and requiring known paths " + known.codePathString 8855 + " & " + known.resourcePathString); 8856 } 8857 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8858 || !pkg.applicationInfo.getResourcePath().equals( 8859 known.resourcePathString)) { 8860 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8861 "Application package " + pkg.packageName 8862 + " found at " + pkg.applicationInfo.getCodePath() 8863 + " but expected at " + known.codePathString 8864 + "; ignoring."); 8865 } 8866 } 8867 } 8868 } 8869 8870 // Verify that this new package doesn't have any content providers 8871 // that conflict with existing packages. Only do this if the 8872 // package isn't already installed, since we don't want to break 8873 // things that are installed. 8874 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8875 final int N = pkg.providers.size(); 8876 int i; 8877 for (i=0; i<N; i++) { 8878 PackageParser.Provider p = pkg.providers.get(i); 8879 if (p.info.authority != null) { 8880 String names[] = p.info.authority.split(";"); 8881 for (int j = 0; j < names.length; j++) { 8882 if (mProvidersByAuthority.containsKey(names[j])) { 8883 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8884 final String otherPackageName = 8885 ((other != null && other.getComponentName() != null) ? 8886 other.getComponentName().getPackageName() : "?"); 8887 throw new PackageManagerException( 8888 INSTALL_FAILED_CONFLICTING_PROVIDER, 8889 "Can't install because provider name " + names[j] 8890 + " (in package " + pkg.applicationInfo.packageName 8891 + ") is already used by " + otherPackageName); 8892 } 8893 } 8894 } 8895 } 8896 } 8897 } 8898 } 8899 8900 /** 8901 * Adds a scanned package to the system. When this method is finished, the package will 8902 * be available for query, resolution, etc... 8903 */ 8904 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8905 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8906 final String pkgName = pkg.packageName; 8907 if (mCustomResolverComponentName != null && 8908 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8909 setUpCustomResolverActivity(pkg); 8910 } 8911 8912 if (pkg.packageName.equals("android")) { 8913 synchronized (mPackages) { 8914 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8915 // Set up information for our fall-back user intent resolution activity. 8916 mPlatformPackage = pkg; 8917 pkg.mVersionCode = mSdkVersion; 8918 mAndroidApplication = pkg.applicationInfo; 8919 8920 if (!mResolverReplaced) { 8921 mResolveActivity.applicationInfo = mAndroidApplication; 8922 mResolveActivity.name = ResolverActivity.class.getName(); 8923 mResolveActivity.packageName = mAndroidApplication.packageName; 8924 mResolveActivity.processName = "system:ui"; 8925 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8926 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8927 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8928 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8929 mResolveActivity.exported = true; 8930 mResolveActivity.enabled = true; 8931 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8932 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8933 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8934 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8935 | ActivityInfo.CONFIG_ORIENTATION 8936 | ActivityInfo.CONFIG_KEYBOARD 8937 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8938 mResolveInfo.activityInfo = mResolveActivity; 8939 mResolveInfo.priority = 0; 8940 mResolveInfo.preferredOrder = 0; 8941 mResolveInfo.match = 0; 8942 mResolveComponentName = new ComponentName( 8943 mAndroidApplication.packageName, mResolveActivity.name); 8944 } 8945 } 8946 } 8947 } 8948 8949 ArrayList<PackageParser.Package> clientLibPkgs = null; 8950 // writer 8951 synchronized (mPackages) { 8952 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8953 // Only system apps can add new shared libraries. 8954 if (pkg.libraryNames != null) { 8955 for (int i=0; i<pkg.libraryNames.size(); i++) { 8956 String name = pkg.libraryNames.get(i); 8957 boolean allowed = false; 8958 if (pkg.isUpdatedSystemApp()) { 8959 // New library entries can only be added through the 8960 // system image. This is important to get rid of a lot 8961 // of nasty edge cases: for example if we allowed a non- 8962 // system update of the app to add a library, then uninstalling 8963 // the update would make the library go away, and assumptions 8964 // we made such as through app install filtering would now 8965 // have allowed apps on the device which aren't compatible 8966 // with it. Better to just have the restriction here, be 8967 // conservative, and create many fewer cases that can negatively 8968 // impact the user experience. 8969 final PackageSetting sysPs = mSettings 8970 .getDisabledSystemPkgLPr(pkg.packageName); 8971 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8972 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8973 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8974 allowed = true; 8975 break; 8976 } 8977 } 8978 } 8979 } else { 8980 allowed = true; 8981 } 8982 if (allowed) { 8983 if (!mSharedLibraries.containsKey(name)) { 8984 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8985 } else if (!name.equals(pkg.packageName)) { 8986 Slog.w(TAG, "Package " + pkg.packageName + " library " 8987 + name + " already exists; skipping"); 8988 } 8989 } else { 8990 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8991 + name + " that is not declared on system image; skipping"); 8992 } 8993 } 8994 if ((scanFlags & SCAN_BOOTING) == 0) { 8995 // If we are not booting, we need to update any applications 8996 // that are clients of our shared library. If we are booting, 8997 // this will all be done once the scan is complete. 8998 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8999 } 9000 } 9001 } 9002 } 9003 9004 if ((scanFlags & SCAN_BOOTING) != 0) { 9005 // No apps can run during boot scan, so they don't need to be frozen 9006 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9007 // Caller asked to not kill app, so it's probably not frozen 9008 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9009 // Caller asked us to ignore frozen check for some reason; they 9010 // probably didn't know the package name 9011 } else { 9012 // We're doing major surgery on this package, so it better be frozen 9013 // right now to keep it from launching 9014 checkPackageFrozen(pkgName); 9015 } 9016 9017 // Also need to kill any apps that are dependent on the library. 9018 if (clientLibPkgs != null) { 9019 for (int i=0; i<clientLibPkgs.size(); i++) { 9020 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9021 killApplication(clientPkg.applicationInfo.packageName, 9022 clientPkg.applicationInfo.uid, "update lib"); 9023 } 9024 } 9025 9026 // writer 9027 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9028 9029 boolean createIdmapFailed = false; 9030 synchronized (mPackages) { 9031 // We don't expect installation to fail beyond this point 9032 9033 if (pkgSetting.pkg != null) { 9034 // Note that |user| might be null during the initial boot scan. If a codePath 9035 // for an app has changed during a boot scan, it's due to an app update that's 9036 // part of the system partition and marker changes must be applied to all users. 9037 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9038 final int[] userIds = resolveUserIds(userId); 9039 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9040 } 9041 9042 // Add the new setting to mSettings 9043 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9044 // Add the new setting to mPackages 9045 mPackages.put(pkg.applicationInfo.packageName, pkg); 9046 // Make sure we don't accidentally delete its data. 9047 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9048 while (iter.hasNext()) { 9049 PackageCleanItem item = iter.next(); 9050 if (pkgName.equals(item.packageName)) { 9051 iter.remove(); 9052 } 9053 } 9054 9055 // Add the package's KeySets to the global KeySetManagerService 9056 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9057 ksms.addScannedPackageLPw(pkg); 9058 9059 int N = pkg.providers.size(); 9060 StringBuilder r = null; 9061 int i; 9062 for (i=0; i<N; i++) { 9063 PackageParser.Provider p = pkg.providers.get(i); 9064 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9065 p.info.processName); 9066 mProviders.addProvider(p); 9067 p.syncable = p.info.isSyncable; 9068 if (p.info.authority != null) { 9069 String names[] = p.info.authority.split(";"); 9070 p.info.authority = null; 9071 for (int j = 0; j < names.length; j++) { 9072 if (j == 1 && p.syncable) { 9073 // We only want the first authority for a provider to possibly be 9074 // syncable, so if we already added this provider using a different 9075 // authority clear the syncable flag. We copy the provider before 9076 // changing it because the mProviders object contains a reference 9077 // to a provider that we don't want to change. 9078 // Only do this for the second authority since the resulting provider 9079 // object can be the same for all future authorities for this provider. 9080 p = new PackageParser.Provider(p); 9081 p.syncable = false; 9082 } 9083 if (!mProvidersByAuthority.containsKey(names[j])) { 9084 mProvidersByAuthority.put(names[j], p); 9085 if (p.info.authority == null) { 9086 p.info.authority = names[j]; 9087 } else { 9088 p.info.authority = p.info.authority + ";" + names[j]; 9089 } 9090 if (DEBUG_PACKAGE_SCANNING) { 9091 if (chatty) 9092 Log.d(TAG, "Registered content provider: " + names[j] 9093 + ", className = " + p.info.name + ", isSyncable = " 9094 + p.info.isSyncable); 9095 } 9096 } else { 9097 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9098 Slog.w(TAG, "Skipping provider name " + names[j] + 9099 " (in package " + pkg.applicationInfo.packageName + 9100 "): name already used by " 9101 + ((other != null && other.getComponentName() != null) 9102 ? other.getComponentName().getPackageName() : "?")); 9103 } 9104 } 9105 } 9106 if (chatty) { 9107 if (r == null) { 9108 r = new StringBuilder(256); 9109 } else { 9110 r.append(' '); 9111 } 9112 r.append(p.info.name); 9113 } 9114 } 9115 if (r != null) { 9116 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9117 } 9118 9119 N = pkg.services.size(); 9120 r = null; 9121 for (i=0; i<N; i++) { 9122 PackageParser.Service s = pkg.services.get(i); 9123 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9124 s.info.processName); 9125 mServices.addService(s); 9126 if (chatty) { 9127 if (r == null) { 9128 r = new StringBuilder(256); 9129 } else { 9130 r.append(' '); 9131 } 9132 r.append(s.info.name); 9133 } 9134 } 9135 if (r != null) { 9136 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9137 } 9138 9139 N = pkg.receivers.size(); 9140 r = null; 9141 for (i=0; i<N; i++) { 9142 PackageParser.Activity a = pkg.receivers.get(i); 9143 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9144 a.info.processName); 9145 mReceivers.addActivity(a, "receiver"); 9146 if (chatty) { 9147 if (r == null) { 9148 r = new StringBuilder(256); 9149 } else { 9150 r.append(' '); 9151 } 9152 r.append(a.info.name); 9153 } 9154 } 9155 if (r != null) { 9156 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9157 } 9158 9159 N = pkg.activities.size(); 9160 r = null; 9161 for (i=0; i<N; i++) { 9162 PackageParser.Activity a = pkg.activities.get(i); 9163 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9164 a.info.processName); 9165 mActivities.addActivity(a, "activity"); 9166 if (chatty) { 9167 if (r == null) { 9168 r = new StringBuilder(256); 9169 } else { 9170 r.append(' '); 9171 } 9172 r.append(a.info.name); 9173 } 9174 } 9175 if (r != null) { 9176 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9177 } 9178 9179 N = pkg.permissionGroups.size(); 9180 r = null; 9181 for (i=0; i<N; i++) { 9182 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9183 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9184 final String curPackageName = cur == null ? null : cur.info.packageName; 9185 // Dont allow ephemeral apps to define new permission groups. 9186 if (pkg.applicationInfo.isEphemeralApp()) { 9187 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9188 + pg.info.packageName 9189 + " ignored: ephemeral apps cannot define new permission groups."); 9190 continue; 9191 } 9192 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9193 if (cur == null || isPackageUpdate) { 9194 mPermissionGroups.put(pg.info.name, pg); 9195 if (chatty) { 9196 if (r == null) { 9197 r = new StringBuilder(256); 9198 } else { 9199 r.append(' '); 9200 } 9201 if (isPackageUpdate) { 9202 r.append("UPD:"); 9203 } 9204 r.append(pg.info.name); 9205 } 9206 } else { 9207 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9208 + pg.info.packageName + " ignored: original from " 9209 + cur.info.packageName); 9210 if (chatty) { 9211 if (r == null) { 9212 r = new StringBuilder(256); 9213 } else { 9214 r.append(' '); 9215 } 9216 r.append("DUP:"); 9217 r.append(pg.info.name); 9218 } 9219 } 9220 } 9221 if (r != null) { 9222 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9223 } 9224 9225 N = pkg.permissions.size(); 9226 r = null; 9227 for (i=0; i<N; i++) { 9228 PackageParser.Permission p = pkg.permissions.get(i); 9229 9230 // Dont allow ephemeral apps to define new permissions. 9231 if (pkg.applicationInfo.isEphemeralApp()) { 9232 Slog.w(TAG, "Permission " + p.info.name + " from package " 9233 + p.info.packageName 9234 + " ignored: ephemeral apps cannot define new permissions."); 9235 continue; 9236 } 9237 9238 // Assume by default that we did not install this permission into the system. 9239 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9240 9241 // Now that permission groups have a special meaning, we ignore permission 9242 // groups for legacy apps to prevent unexpected behavior. In particular, 9243 // permissions for one app being granted to someone just becase they happen 9244 // to be in a group defined by another app (before this had no implications). 9245 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9246 p.group = mPermissionGroups.get(p.info.group); 9247 // Warn for a permission in an unknown group. 9248 if (p.info.group != null && p.group == null) { 9249 Slog.w(TAG, "Permission " + p.info.name + " from package " 9250 + p.info.packageName + " in an unknown group " + p.info.group); 9251 } 9252 } 9253 9254 ArrayMap<String, BasePermission> permissionMap = 9255 p.tree ? mSettings.mPermissionTrees 9256 : mSettings.mPermissions; 9257 BasePermission bp = permissionMap.get(p.info.name); 9258 9259 // Allow system apps to redefine non-system permissions 9260 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9261 final boolean currentOwnerIsSystem = (bp.perm != null 9262 && isSystemApp(bp.perm.owner)); 9263 if (isSystemApp(p.owner)) { 9264 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9265 // It's a built-in permission and no owner, take ownership now 9266 bp.packageSetting = pkgSetting; 9267 bp.perm = p; 9268 bp.uid = pkg.applicationInfo.uid; 9269 bp.sourcePackage = p.info.packageName; 9270 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9271 } else if (!currentOwnerIsSystem) { 9272 String msg = "New decl " + p.owner + " of permission " 9273 + p.info.name + " is system; overriding " + bp.sourcePackage; 9274 reportSettingsProblem(Log.WARN, msg); 9275 bp = null; 9276 } 9277 } 9278 } 9279 9280 if (bp == null) { 9281 bp = new BasePermission(p.info.name, p.info.packageName, 9282 BasePermission.TYPE_NORMAL); 9283 permissionMap.put(p.info.name, bp); 9284 } 9285 9286 if (bp.perm == null) { 9287 if (bp.sourcePackage == null 9288 || bp.sourcePackage.equals(p.info.packageName)) { 9289 BasePermission tree = findPermissionTreeLP(p.info.name); 9290 if (tree == null 9291 || tree.sourcePackage.equals(p.info.packageName)) { 9292 bp.packageSetting = pkgSetting; 9293 bp.perm = p; 9294 bp.uid = pkg.applicationInfo.uid; 9295 bp.sourcePackage = p.info.packageName; 9296 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9297 if (chatty) { 9298 if (r == null) { 9299 r = new StringBuilder(256); 9300 } else { 9301 r.append(' '); 9302 } 9303 r.append(p.info.name); 9304 } 9305 } else { 9306 Slog.w(TAG, "Permission " + p.info.name + " from package " 9307 + p.info.packageName + " ignored: base tree " 9308 + tree.name + " is from package " 9309 + tree.sourcePackage); 9310 } 9311 } else { 9312 Slog.w(TAG, "Permission " + p.info.name + " from package " 9313 + p.info.packageName + " ignored: original from " 9314 + bp.sourcePackage); 9315 } 9316 } else if (chatty) { 9317 if (r == null) { 9318 r = new StringBuilder(256); 9319 } else { 9320 r.append(' '); 9321 } 9322 r.append("DUP:"); 9323 r.append(p.info.name); 9324 } 9325 if (bp.perm == p) { 9326 bp.protectionLevel = p.info.protectionLevel; 9327 } 9328 } 9329 9330 if (r != null) { 9331 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9332 } 9333 9334 N = pkg.instrumentation.size(); 9335 r = null; 9336 for (i=0; i<N; i++) { 9337 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9338 a.info.packageName = pkg.applicationInfo.packageName; 9339 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9340 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9341 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9342 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9343 a.info.dataDir = pkg.applicationInfo.dataDir; 9344 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9345 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9346 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9347 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9348 mInstrumentation.put(a.getComponentName(), a); 9349 if (chatty) { 9350 if (r == null) { 9351 r = new StringBuilder(256); 9352 } else { 9353 r.append(' '); 9354 } 9355 r.append(a.info.name); 9356 } 9357 } 9358 if (r != null) { 9359 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9360 } 9361 9362 if (pkg.protectedBroadcasts != null) { 9363 N = pkg.protectedBroadcasts.size(); 9364 for (i=0; i<N; i++) { 9365 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9366 } 9367 } 9368 9369 // Create idmap files for pairs of (packages, overlay packages). 9370 // Note: "android", ie framework-res.apk, is handled by native layers. 9371 if (pkg.mOverlayTarget != null) { 9372 // This is an overlay package. 9373 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9374 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9375 mOverlays.put(pkg.mOverlayTarget, 9376 new ArrayMap<String, PackageParser.Package>()); 9377 } 9378 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9379 map.put(pkg.packageName, pkg); 9380 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9381 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9382 createIdmapFailed = true; 9383 } 9384 } 9385 } else if (mOverlays.containsKey(pkg.packageName) && 9386 !pkg.packageName.equals("android")) { 9387 // This is a regular package, with one or more known overlay packages. 9388 createIdmapsForPackageLI(pkg); 9389 } 9390 } 9391 9392 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9393 9394 if (createIdmapFailed) { 9395 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9396 "scanPackageLI failed to createIdmap"); 9397 } 9398 } 9399 9400 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9401 PackageParser.Package update, int[] userIds) { 9402 if (existing.applicationInfo == null || update.applicationInfo == null) { 9403 // This isn't due to an app installation. 9404 return; 9405 } 9406 9407 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9408 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9409 9410 // The codePath hasn't changed, so there's nothing for us to do. 9411 if (Objects.equals(oldCodePath, newCodePath)) { 9412 return; 9413 } 9414 9415 File canonicalNewCodePath; 9416 try { 9417 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9418 } catch (IOException e) { 9419 Slog.w(TAG, "Failed to get canonical path.", e); 9420 return; 9421 } 9422 9423 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9424 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9425 // that the last component of the path (i.e, the name) doesn't need canonicalization 9426 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9427 // but may change in the future. Hopefully this function won't exist at that point. 9428 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9429 oldCodePath.getName()); 9430 9431 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9432 // with "@". 9433 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9434 if (!oldMarkerPrefix.endsWith("@")) { 9435 oldMarkerPrefix += "@"; 9436 } 9437 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9438 if (!newMarkerPrefix.endsWith("@")) { 9439 newMarkerPrefix += "@"; 9440 } 9441 9442 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9443 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9444 for (String updatedPath : updatedPaths) { 9445 String updatedPathName = new File(updatedPath).getName(); 9446 markerSuffixes.add(updatedPathName.replace('/', '@')); 9447 } 9448 9449 for (int userId : userIds) { 9450 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9451 9452 for (String markerSuffix : markerSuffixes) { 9453 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9454 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9455 if (oldForeignUseMark.exists()) { 9456 try { 9457 Os.rename(oldForeignUseMark.getAbsolutePath(), 9458 newForeignUseMark.getAbsolutePath()); 9459 } catch (ErrnoException e) { 9460 Slog.w(TAG, "Failed to rename foreign use marker", e); 9461 oldForeignUseMark.delete(); 9462 } 9463 } 9464 } 9465 } 9466 } 9467 9468 /** 9469 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9470 * is derived purely on the basis of the contents of {@code scanFile} and 9471 * {@code cpuAbiOverride}. 9472 * 9473 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9474 */ 9475 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9476 String cpuAbiOverride, boolean extractLibs, 9477 File appLib32InstallDir) 9478 throws PackageManagerException { 9479 // Give ourselves some initial paths; we'll come back for another 9480 // pass once we've determined ABI below. 9481 setNativeLibraryPaths(pkg, appLib32InstallDir); 9482 9483 // We would never need to extract libs for forward-locked and external packages, 9484 // since the container service will do it for us. We shouldn't attempt to 9485 // extract libs from system app when it was not updated. 9486 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9487 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9488 extractLibs = false; 9489 } 9490 9491 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9492 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9493 9494 NativeLibraryHelper.Handle handle = null; 9495 try { 9496 handle = NativeLibraryHelper.Handle.create(pkg); 9497 // TODO(multiArch): This can be null for apps that didn't go through the 9498 // usual installation process. We can calculate it again, like we 9499 // do during install time. 9500 // 9501 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9502 // unnecessary. 9503 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9504 9505 // Null out the abis so that they can be recalculated. 9506 pkg.applicationInfo.primaryCpuAbi = null; 9507 pkg.applicationInfo.secondaryCpuAbi = null; 9508 if (isMultiArch(pkg.applicationInfo)) { 9509 // Warn if we've set an abiOverride for multi-lib packages.. 9510 // By definition, we need to copy both 32 and 64 bit libraries for 9511 // such packages. 9512 if (pkg.cpuAbiOverride != null 9513 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9514 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9515 } 9516 9517 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9518 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9519 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9520 if (extractLibs) { 9521 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9522 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9523 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9524 useIsaSpecificSubdirs); 9525 } else { 9526 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9527 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9528 } 9529 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9530 } 9531 9532 maybeThrowExceptionForMultiArchCopy( 9533 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9534 9535 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9536 if (extractLibs) { 9537 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9538 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9539 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9540 useIsaSpecificSubdirs); 9541 } else { 9542 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9543 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9544 } 9545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9546 } 9547 9548 maybeThrowExceptionForMultiArchCopy( 9549 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9550 9551 if (abi64 >= 0) { 9552 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9553 } 9554 9555 if (abi32 >= 0) { 9556 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9557 if (abi64 >= 0) { 9558 if (pkg.use32bitAbi) { 9559 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9560 pkg.applicationInfo.primaryCpuAbi = abi; 9561 } else { 9562 pkg.applicationInfo.secondaryCpuAbi = abi; 9563 } 9564 } else { 9565 pkg.applicationInfo.primaryCpuAbi = abi; 9566 } 9567 } 9568 9569 } else { 9570 String[] abiList = (cpuAbiOverride != null) ? 9571 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9572 9573 // Enable gross and lame hacks for apps that are built with old 9574 // SDK tools. We must scan their APKs for renderscript bitcode and 9575 // not launch them if it's present. Don't bother checking on devices 9576 // that don't have 64 bit support. 9577 boolean needsRenderScriptOverride = false; 9578 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9579 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9580 abiList = Build.SUPPORTED_32_BIT_ABIS; 9581 needsRenderScriptOverride = true; 9582 } 9583 9584 final int copyRet; 9585 if (extractLibs) { 9586 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9587 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9588 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9589 } else { 9590 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9591 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9592 } 9593 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9594 9595 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9596 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9597 "Error unpackaging native libs for app, errorCode=" + copyRet); 9598 } 9599 9600 if (copyRet >= 0) { 9601 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9602 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9603 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9604 } else if (needsRenderScriptOverride) { 9605 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9606 } 9607 } 9608 } catch (IOException ioe) { 9609 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9610 } finally { 9611 IoUtils.closeQuietly(handle); 9612 } 9613 9614 // Now that we've calculated the ABIs and determined if it's an internal app, 9615 // we will go ahead and populate the nativeLibraryPath. 9616 setNativeLibraryPaths(pkg, appLib32InstallDir); 9617 } 9618 9619 /** 9620 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9621 * i.e, so that all packages can be run inside a single process if required. 9622 * 9623 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9624 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9625 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9626 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9627 * updating a package that belongs to a shared user. 9628 * 9629 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9630 * adds unnecessary complexity. 9631 */ 9632 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9633 PackageParser.Package scannedPackage) { 9634 String requiredInstructionSet = null; 9635 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9636 requiredInstructionSet = VMRuntime.getInstructionSet( 9637 scannedPackage.applicationInfo.primaryCpuAbi); 9638 } 9639 9640 PackageSetting requirer = null; 9641 for (PackageSetting ps : packagesForUser) { 9642 // If packagesForUser contains scannedPackage, we skip it. This will happen 9643 // when scannedPackage is an update of an existing package. Without this check, 9644 // we will never be able to change the ABI of any package belonging to a shared 9645 // user, even if it's compatible with other packages. 9646 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9647 if (ps.primaryCpuAbiString == null) { 9648 continue; 9649 } 9650 9651 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9652 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9653 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9654 // this but there's not much we can do. 9655 String errorMessage = "Instruction set mismatch, " 9656 + ((requirer == null) ? "[caller]" : requirer) 9657 + " requires " + requiredInstructionSet + " whereas " + ps 9658 + " requires " + instructionSet; 9659 Slog.w(TAG, errorMessage); 9660 } 9661 9662 if (requiredInstructionSet == null) { 9663 requiredInstructionSet = instructionSet; 9664 requirer = ps; 9665 } 9666 } 9667 } 9668 9669 if (requiredInstructionSet != null) { 9670 String adjustedAbi; 9671 if (requirer != null) { 9672 // requirer != null implies that either scannedPackage was null or that scannedPackage 9673 // did not require an ABI, in which case we have to adjust scannedPackage to match 9674 // the ABI of the set (which is the same as requirer's ABI) 9675 adjustedAbi = requirer.primaryCpuAbiString; 9676 if (scannedPackage != null) { 9677 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9678 } 9679 } else { 9680 // requirer == null implies that we're updating all ABIs in the set to 9681 // match scannedPackage. 9682 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9683 } 9684 9685 for (PackageSetting ps : packagesForUser) { 9686 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9687 if (ps.primaryCpuAbiString != null) { 9688 continue; 9689 } 9690 9691 ps.primaryCpuAbiString = adjustedAbi; 9692 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9693 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9694 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9695 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9696 + " (requirer=" 9697 + (requirer == null ? "null" : requirer.pkg.packageName) 9698 + ", scannedPackage=" 9699 + (scannedPackage != null ? scannedPackage.packageName : "null") 9700 + ")"); 9701 try { 9702 mInstaller.rmdex(ps.codePathString, 9703 getDexCodeInstructionSet(getPreferredInstructionSet())); 9704 } catch (InstallerException ignored) { 9705 } 9706 } 9707 } 9708 } 9709 } 9710 } 9711 9712 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9713 synchronized (mPackages) { 9714 mResolverReplaced = true; 9715 // Set up information for custom user intent resolution activity. 9716 mResolveActivity.applicationInfo = pkg.applicationInfo; 9717 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9718 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9719 mResolveActivity.processName = pkg.applicationInfo.packageName; 9720 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9721 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9722 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9723 mResolveActivity.theme = 0; 9724 mResolveActivity.exported = true; 9725 mResolveActivity.enabled = true; 9726 mResolveInfo.activityInfo = mResolveActivity; 9727 mResolveInfo.priority = 0; 9728 mResolveInfo.preferredOrder = 0; 9729 mResolveInfo.match = 0; 9730 mResolveComponentName = mCustomResolverComponentName; 9731 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9732 mResolveComponentName); 9733 } 9734 } 9735 9736 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9737 if (installerComponent == null) { 9738 if (DEBUG_EPHEMERAL) { 9739 Slog.d(TAG, "Clear ephemeral installer activity"); 9740 } 9741 mEphemeralInstallerActivity.applicationInfo = null; 9742 return; 9743 } 9744 9745 if (DEBUG_EPHEMERAL) { 9746 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9747 } 9748 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9749 // Set up information for ephemeral installer activity 9750 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9751 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9752 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9753 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9754 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9755 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9756 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9757 mEphemeralInstallerActivity.theme = 0; 9758 mEphemeralInstallerActivity.exported = true; 9759 mEphemeralInstallerActivity.enabled = true; 9760 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9761 mEphemeralInstallerInfo.priority = 0; 9762 mEphemeralInstallerInfo.preferredOrder = 1; 9763 mEphemeralInstallerInfo.isDefault = true; 9764 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9765 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9766 } 9767 9768 private static String calculateBundledApkRoot(final String codePathString) { 9769 final File codePath = new File(codePathString); 9770 final File codeRoot; 9771 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9772 codeRoot = Environment.getRootDirectory(); 9773 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9774 codeRoot = Environment.getOemDirectory(); 9775 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9776 codeRoot = Environment.getVendorDirectory(); 9777 } else { 9778 // Unrecognized code path; take its top real segment as the apk root: 9779 // e.g. /something/app/blah.apk => /something 9780 try { 9781 File f = codePath.getCanonicalFile(); 9782 File parent = f.getParentFile(); // non-null because codePath is a file 9783 File tmp; 9784 while ((tmp = parent.getParentFile()) != null) { 9785 f = parent; 9786 parent = tmp; 9787 } 9788 codeRoot = f; 9789 Slog.w(TAG, "Unrecognized code path " 9790 + codePath + " - using " + codeRoot); 9791 } catch (IOException e) { 9792 // Can't canonicalize the code path -- shenanigans? 9793 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9794 return Environment.getRootDirectory().getPath(); 9795 } 9796 } 9797 return codeRoot.getPath(); 9798 } 9799 9800 /** 9801 * Derive and set the location of native libraries for the given package, 9802 * which varies depending on where and how the package was installed. 9803 */ 9804 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9805 final ApplicationInfo info = pkg.applicationInfo; 9806 final String codePath = pkg.codePath; 9807 final File codeFile = new File(codePath); 9808 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9809 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9810 9811 info.nativeLibraryRootDir = null; 9812 info.nativeLibraryRootRequiresIsa = false; 9813 info.nativeLibraryDir = null; 9814 info.secondaryNativeLibraryDir = null; 9815 9816 if (isApkFile(codeFile)) { 9817 // Monolithic install 9818 if (bundledApp) { 9819 // If "/system/lib64/apkname" exists, assume that is the per-package 9820 // native library directory to use; otherwise use "/system/lib/apkname". 9821 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9822 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9823 getPrimaryInstructionSet(info)); 9824 9825 // This is a bundled system app so choose the path based on the ABI. 9826 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9827 // is just the default path. 9828 final String apkName = deriveCodePathName(codePath); 9829 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9830 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9831 apkName).getAbsolutePath(); 9832 9833 if (info.secondaryCpuAbi != null) { 9834 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9835 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9836 secondaryLibDir, apkName).getAbsolutePath(); 9837 } 9838 } else if (asecApp) { 9839 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9840 .getAbsolutePath(); 9841 } else { 9842 final String apkName = deriveCodePathName(codePath); 9843 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9844 .getAbsolutePath(); 9845 } 9846 9847 info.nativeLibraryRootRequiresIsa = false; 9848 info.nativeLibraryDir = info.nativeLibraryRootDir; 9849 } else { 9850 // Cluster install 9851 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9852 info.nativeLibraryRootRequiresIsa = true; 9853 9854 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9855 getPrimaryInstructionSet(info)).getAbsolutePath(); 9856 9857 if (info.secondaryCpuAbi != null) { 9858 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9859 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9860 } 9861 } 9862 } 9863 9864 /** 9865 * Calculate the abis and roots for a bundled app. These can uniquely 9866 * be determined from the contents of the system partition, i.e whether 9867 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9868 * of this information, and instead assume that the system was built 9869 * sensibly. 9870 */ 9871 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9872 PackageSetting pkgSetting) { 9873 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9874 9875 // If "/system/lib64/apkname" exists, assume that is the per-package 9876 // native library directory to use; otherwise use "/system/lib/apkname". 9877 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9878 setBundledAppAbi(pkg, apkRoot, apkName); 9879 // pkgSetting might be null during rescan following uninstall of updates 9880 // to a bundled app, so accommodate that possibility. The settings in 9881 // that case will be established later from the parsed package. 9882 // 9883 // If the settings aren't null, sync them up with what we've just derived. 9884 // note that apkRoot isn't stored in the package settings. 9885 if (pkgSetting != null) { 9886 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9887 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9888 } 9889 } 9890 9891 /** 9892 * Deduces the ABI of a bundled app and sets the relevant fields on the 9893 * parsed pkg object. 9894 * 9895 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9896 * under which system libraries are installed. 9897 * @param apkName the name of the installed package. 9898 */ 9899 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9900 final File codeFile = new File(pkg.codePath); 9901 9902 final boolean has64BitLibs; 9903 final boolean has32BitLibs; 9904 if (isApkFile(codeFile)) { 9905 // Monolithic install 9906 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9907 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9908 } else { 9909 // Cluster install 9910 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9911 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9912 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9913 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9914 has64BitLibs = (new File(rootDir, isa)).exists(); 9915 } else { 9916 has64BitLibs = false; 9917 } 9918 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9919 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9920 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9921 has32BitLibs = (new File(rootDir, isa)).exists(); 9922 } else { 9923 has32BitLibs = false; 9924 } 9925 } 9926 9927 if (has64BitLibs && !has32BitLibs) { 9928 // The package has 64 bit libs, but not 32 bit libs. Its primary 9929 // ABI should be 64 bit. We can safely assume here that the bundled 9930 // native libraries correspond to the most preferred ABI in the list. 9931 9932 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9933 pkg.applicationInfo.secondaryCpuAbi = null; 9934 } else if (has32BitLibs && !has64BitLibs) { 9935 // The package has 32 bit libs but not 64 bit libs. Its primary 9936 // ABI should be 32 bit. 9937 9938 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9939 pkg.applicationInfo.secondaryCpuAbi = null; 9940 } else if (has32BitLibs && has64BitLibs) { 9941 // The application has both 64 and 32 bit bundled libraries. We check 9942 // here that the app declares multiArch support, and warn if it doesn't. 9943 // 9944 // We will be lenient here and record both ABIs. The primary will be the 9945 // ABI that's higher on the list, i.e, a device that's configured to prefer 9946 // 64 bit apps will see a 64 bit primary ABI, 9947 9948 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9949 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9950 } 9951 9952 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9953 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9954 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9955 } else { 9956 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9957 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9958 } 9959 } else { 9960 pkg.applicationInfo.primaryCpuAbi = null; 9961 pkg.applicationInfo.secondaryCpuAbi = null; 9962 } 9963 } 9964 9965 private void killApplication(String pkgName, int appId, String reason) { 9966 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9967 } 9968 9969 private void killApplication(String pkgName, int appId, int userId, String reason) { 9970 // Request the ActivityManager to kill the process(only for existing packages) 9971 // so that we do not end up in a confused state while the user is still using the older 9972 // version of the application while the new one gets installed. 9973 final long token = Binder.clearCallingIdentity(); 9974 try { 9975 IActivityManager am = ActivityManager.getService(); 9976 if (am != null) { 9977 try { 9978 am.killApplication(pkgName, appId, userId, reason); 9979 } catch (RemoteException e) { 9980 } 9981 } 9982 } finally { 9983 Binder.restoreCallingIdentity(token); 9984 } 9985 } 9986 9987 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9988 // Remove the parent package setting 9989 PackageSetting ps = (PackageSetting) pkg.mExtras; 9990 if (ps != null) { 9991 removePackageLI(ps, chatty); 9992 } 9993 // Remove the child package setting 9994 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9995 for (int i = 0; i < childCount; i++) { 9996 PackageParser.Package childPkg = pkg.childPackages.get(i); 9997 ps = (PackageSetting) childPkg.mExtras; 9998 if (ps != null) { 9999 removePackageLI(ps, chatty); 10000 } 10001 } 10002 } 10003 10004 void removePackageLI(PackageSetting ps, boolean chatty) { 10005 if (DEBUG_INSTALL) { 10006 if (chatty) 10007 Log.d(TAG, "Removing package " + ps.name); 10008 } 10009 10010 // writer 10011 synchronized (mPackages) { 10012 mPackages.remove(ps.name); 10013 final PackageParser.Package pkg = ps.pkg; 10014 if (pkg != null) { 10015 cleanPackageDataStructuresLILPw(pkg, chatty); 10016 } 10017 } 10018 } 10019 10020 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10021 if (DEBUG_INSTALL) { 10022 if (chatty) 10023 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10024 } 10025 10026 // writer 10027 synchronized (mPackages) { 10028 // Remove the parent package 10029 mPackages.remove(pkg.applicationInfo.packageName); 10030 cleanPackageDataStructuresLILPw(pkg, chatty); 10031 10032 // Remove the child packages 10033 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10034 for (int i = 0; i < childCount; i++) { 10035 PackageParser.Package childPkg = pkg.childPackages.get(i); 10036 mPackages.remove(childPkg.applicationInfo.packageName); 10037 cleanPackageDataStructuresLILPw(childPkg, chatty); 10038 } 10039 } 10040 } 10041 10042 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10043 int N = pkg.providers.size(); 10044 StringBuilder r = null; 10045 int i; 10046 for (i=0; i<N; i++) { 10047 PackageParser.Provider p = pkg.providers.get(i); 10048 mProviders.removeProvider(p); 10049 if (p.info.authority == null) { 10050 10051 /* There was another ContentProvider with this authority when 10052 * this app was installed so this authority is null, 10053 * Ignore it as we don't have to unregister the provider. 10054 */ 10055 continue; 10056 } 10057 String names[] = p.info.authority.split(";"); 10058 for (int j = 0; j < names.length; j++) { 10059 if (mProvidersByAuthority.get(names[j]) == p) { 10060 mProvidersByAuthority.remove(names[j]); 10061 if (DEBUG_REMOVE) { 10062 if (chatty) 10063 Log.d(TAG, "Unregistered content provider: " + names[j] 10064 + ", className = " + p.info.name + ", isSyncable = " 10065 + p.info.isSyncable); 10066 } 10067 } 10068 } 10069 if (DEBUG_REMOVE && chatty) { 10070 if (r == null) { 10071 r = new StringBuilder(256); 10072 } else { 10073 r.append(' '); 10074 } 10075 r.append(p.info.name); 10076 } 10077 } 10078 if (r != null) { 10079 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10080 } 10081 10082 N = pkg.services.size(); 10083 r = null; 10084 for (i=0; i<N; i++) { 10085 PackageParser.Service s = pkg.services.get(i); 10086 mServices.removeService(s); 10087 if (chatty) { 10088 if (r == null) { 10089 r = new StringBuilder(256); 10090 } else { 10091 r.append(' '); 10092 } 10093 r.append(s.info.name); 10094 } 10095 } 10096 if (r != null) { 10097 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10098 } 10099 10100 N = pkg.receivers.size(); 10101 r = null; 10102 for (i=0; i<N; i++) { 10103 PackageParser.Activity a = pkg.receivers.get(i); 10104 mReceivers.removeActivity(a, "receiver"); 10105 if (DEBUG_REMOVE && chatty) { 10106 if (r == null) { 10107 r = new StringBuilder(256); 10108 } else { 10109 r.append(' '); 10110 } 10111 r.append(a.info.name); 10112 } 10113 } 10114 if (r != null) { 10115 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10116 } 10117 10118 N = pkg.activities.size(); 10119 r = null; 10120 for (i=0; i<N; i++) { 10121 PackageParser.Activity a = pkg.activities.get(i); 10122 mActivities.removeActivity(a, "activity"); 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, " Activities: " + r); 10134 } 10135 10136 N = pkg.permissions.size(); 10137 r = null; 10138 for (i=0; i<N; i++) { 10139 PackageParser.Permission p = pkg.permissions.get(i); 10140 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10141 if (bp == null) { 10142 bp = mSettings.mPermissionTrees.get(p.info.name); 10143 } 10144 if (bp != null && bp.perm == p) { 10145 bp.perm = null; 10146 if (DEBUG_REMOVE && chatty) { 10147 if (r == null) { 10148 r = new StringBuilder(256); 10149 } else { 10150 r.append(' '); 10151 } 10152 r.append(p.info.name); 10153 } 10154 } 10155 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10156 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10157 if (appOpPkgs != null) { 10158 appOpPkgs.remove(pkg.packageName); 10159 } 10160 } 10161 } 10162 if (r != null) { 10163 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10164 } 10165 10166 N = pkg.requestedPermissions.size(); 10167 r = null; 10168 for (i=0; i<N; i++) { 10169 String perm = pkg.requestedPermissions.get(i); 10170 BasePermission bp = mSettings.mPermissions.get(perm); 10171 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10172 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10173 if (appOpPkgs != null) { 10174 appOpPkgs.remove(pkg.packageName); 10175 if (appOpPkgs.isEmpty()) { 10176 mAppOpPermissionPackages.remove(perm); 10177 } 10178 } 10179 } 10180 } 10181 if (r != null) { 10182 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10183 } 10184 10185 N = pkg.instrumentation.size(); 10186 r = null; 10187 for (i=0; i<N; i++) { 10188 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10189 mInstrumentation.remove(a.getComponentName()); 10190 if (DEBUG_REMOVE && chatty) { 10191 if (r == null) { 10192 r = new StringBuilder(256); 10193 } else { 10194 r.append(' '); 10195 } 10196 r.append(a.info.name); 10197 } 10198 } 10199 if (r != null) { 10200 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10201 } 10202 10203 r = null; 10204 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10205 // Only system apps can hold shared libraries. 10206 if (pkg.libraryNames != null) { 10207 for (i=0; i<pkg.libraryNames.size(); i++) { 10208 String name = pkg.libraryNames.get(i); 10209 SharedLibraryEntry cur = mSharedLibraries.get(name); 10210 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10211 mSharedLibraries.remove(name); 10212 if (DEBUG_REMOVE && chatty) { 10213 if (r == null) { 10214 r = new StringBuilder(256); 10215 } else { 10216 r.append(' '); 10217 } 10218 r.append(name); 10219 } 10220 } 10221 } 10222 } 10223 } 10224 if (r != null) { 10225 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10226 } 10227 } 10228 10229 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10230 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10231 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10232 return true; 10233 } 10234 } 10235 return false; 10236 } 10237 10238 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10239 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10240 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10241 10242 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10243 // Update the parent permissions 10244 updatePermissionsLPw(pkg.packageName, pkg, flags); 10245 // Update the child permissions 10246 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10247 for (int i = 0; i < childCount; i++) { 10248 PackageParser.Package childPkg = pkg.childPackages.get(i); 10249 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10250 } 10251 } 10252 10253 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10254 int flags) { 10255 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10256 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10257 } 10258 10259 private void updatePermissionsLPw(String changingPkg, 10260 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10261 // Make sure there are no dangling permission trees. 10262 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10263 while (it.hasNext()) { 10264 final BasePermission bp = it.next(); 10265 if (bp.packageSetting == null) { 10266 // We may not yet have parsed the package, so just see if 10267 // we still know about its settings. 10268 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10269 } 10270 if (bp.packageSetting == null) { 10271 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10272 + " from package " + bp.sourcePackage); 10273 it.remove(); 10274 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10275 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10276 Slog.i(TAG, "Removing old permission tree: " + bp.name 10277 + " from package " + bp.sourcePackage); 10278 flags |= UPDATE_PERMISSIONS_ALL; 10279 it.remove(); 10280 } 10281 } 10282 } 10283 10284 // Make sure all dynamic permissions have been assigned to a package, 10285 // and make sure there are no dangling permissions. 10286 it = mSettings.mPermissions.values().iterator(); 10287 while (it.hasNext()) { 10288 final BasePermission bp = it.next(); 10289 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10290 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10291 + bp.name + " pkg=" + bp.sourcePackage 10292 + " info=" + bp.pendingInfo); 10293 if (bp.packageSetting == null && bp.pendingInfo != null) { 10294 final BasePermission tree = findPermissionTreeLP(bp.name); 10295 if (tree != null && tree.perm != null) { 10296 bp.packageSetting = tree.packageSetting; 10297 bp.perm = new PackageParser.Permission(tree.perm.owner, 10298 new PermissionInfo(bp.pendingInfo)); 10299 bp.perm.info.packageName = tree.perm.info.packageName; 10300 bp.perm.info.name = bp.name; 10301 bp.uid = tree.uid; 10302 } 10303 } 10304 } 10305 if (bp.packageSetting == null) { 10306 // We may not yet have parsed the package, so just see if 10307 // we still know about its settings. 10308 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10309 } 10310 if (bp.packageSetting == null) { 10311 Slog.w(TAG, "Removing dangling permission: " + bp.name 10312 + " from package " + bp.sourcePackage); 10313 it.remove(); 10314 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10315 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10316 Slog.i(TAG, "Removing old permission: " + bp.name 10317 + " from package " + bp.sourcePackage); 10318 flags |= UPDATE_PERMISSIONS_ALL; 10319 it.remove(); 10320 } 10321 } 10322 } 10323 10324 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10325 // Now update the permissions for all packages, in particular 10326 // replace the granted permissions of the system packages. 10327 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10328 for (PackageParser.Package pkg : mPackages.values()) { 10329 if (pkg != pkgInfo) { 10330 // Only replace for packages on requested volume 10331 final String volumeUuid = getVolumeUuidForPackage(pkg); 10332 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10333 && Objects.equals(replaceVolumeUuid, volumeUuid); 10334 grantPermissionsLPw(pkg, replace, changingPkg); 10335 } 10336 } 10337 } 10338 10339 if (pkgInfo != null) { 10340 // Only replace for packages on requested volume 10341 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10342 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10343 && Objects.equals(replaceVolumeUuid, volumeUuid); 10344 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10345 } 10346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10347 } 10348 10349 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10350 String packageOfInterest) { 10351 // IMPORTANT: There are two types of permissions: install and runtime. 10352 // Install time permissions are granted when the app is installed to 10353 // all device users and users added in the future. Runtime permissions 10354 // are granted at runtime explicitly to specific users. Normal and signature 10355 // protected permissions are install time permissions. Dangerous permissions 10356 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10357 // otherwise they are runtime permissions. This function does not manage 10358 // runtime permissions except for the case an app targeting Lollipop MR1 10359 // being upgraded to target a newer SDK, in which case dangerous permissions 10360 // are transformed from install time to runtime ones. 10361 10362 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10363 if (ps == null) { 10364 return; 10365 } 10366 10367 PermissionsState permissionsState = ps.getPermissionsState(); 10368 PermissionsState origPermissions = permissionsState; 10369 10370 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10371 10372 boolean runtimePermissionsRevoked = false; 10373 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10374 10375 boolean changedInstallPermission = false; 10376 10377 if (replace) { 10378 ps.installPermissionsFixed = false; 10379 if (!ps.isSharedUser()) { 10380 origPermissions = new PermissionsState(permissionsState); 10381 permissionsState.reset(); 10382 } else { 10383 // We need to know only about runtime permission changes since the 10384 // calling code always writes the install permissions state but 10385 // the runtime ones are written only if changed. The only cases of 10386 // changed runtime permissions here are promotion of an install to 10387 // runtime and revocation of a runtime from a shared user. 10388 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10389 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10390 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10391 runtimePermissionsRevoked = true; 10392 } 10393 } 10394 } 10395 10396 permissionsState.setGlobalGids(mGlobalGids); 10397 10398 final int N = pkg.requestedPermissions.size(); 10399 for (int i=0; i<N; i++) { 10400 final String name = pkg.requestedPermissions.get(i); 10401 final BasePermission bp = mSettings.mPermissions.get(name); 10402 10403 if (DEBUG_INSTALL) { 10404 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10405 } 10406 10407 if (bp == null || bp.packageSetting == null) { 10408 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10409 Slog.w(TAG, "Unknown permission " + name 10410 + " in package " + pkg.packageName); 10411 } 10412 continue; 10413 } 10414 10415 10416 // Limit ephemeral apps to ephemeral allowed permissions. 10417 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10418 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10419 + pkg.packageName); 10420 continue; 10421 } 10422 10423 final String perm = bp.name; 10424 boolean allowedSig = false; 10425 int grant = GRANT_DENIED; 10426 10427 // Keep track of app op permissions. 10428 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10429 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10430 if (pkgs == null) { 10431 pkgs = new ArraySet<>(); 10432 mAppOpPermissionPackages.put(bp.name, pkgs); 10433 } 10434 pkgs.add(pkg.packageName); 10435 } 10436 10437 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10438 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10439 >= Build.VERSION_CODES.M; 10440 switch (level) { 10441 case PermissionInfo.PROTECTION_NORMAL: { 10442 // For all apps normal permissions are install time ones. 10443 grant = GRANT_INSTALL; 10444 } break; 10445 10446 case PermissionInfo.PROTECTION_DANGEROUS: { 10447 // If a permission review is required for legacy apps we represent 10448 // their permissions as always granted runtime ones since we need 10449 // to keep the review required permission flag per user while an 10450 // install permission's state is shared across all users. 10451 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10452 // For legacy apps dangerous permissions are install time ones. 10453 grant = GRANT_INSTALL; 10454 } else if (origPermissions.hasInstallPermission(bp.name)) { 10455 // For legacy apps that became modern, install becomes runtime. 10456 grant = GRANT_UPGRADE; 10457 } else if (mPromoteSystemApps 10458 && isSystemApp(ps) 10459 && mExistingSystemPackages.contains(ps.name)) { 10460 // For legacy system apps, install becomes runtime. 10461 // We cannot check hasInstallPermission() for system apps since those 10462 // permissions were granted implicitly and not persisted pre-M. 10463 grant = GRANT_UPGRADE; 10464 } else { 10465 // For modern apps keep runtime permissions unchanged. 10466 grant = GRANT_RUNTIME; 10467 } 10468 } break; 10469 10470 case PermissionInfo.PROTECTION_SIGNATURE: { 10471 // For all apps signature permissions are install time ones. 10472 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10473 if (allowedSig) { 10474 grant = GRANT_INSTALL; 10475 } 10476 } break; 10477 } 10478 10479 if (DEBUG_INSTALL) { 10480 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10481 } 10482 10483 if (grant != GRANT_DENIED) { 10484 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10485 // If this is an existing, non-system package, then 10486 // we can't add any new permissions to it. 10487 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10488 // Except... if this is a permission that was added 10489 // to the platform (note: need to only do this when 10490 // updating the platform). 10491 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10492 grant = GRANT_DENIED; 10493 } 10494 } 10495 } 10496 10497 switch (grant) { 10498 case GRANT_INSTALL: { 10499 // Revoke this as runtime permission to handle the case of 10500 // a runtime permission being downgraded to an install one. 10501 // Also in permission review mode we keep dangerous permissions 10502 // for legacy apps 10503 for (int userId : UserManagerService.getInstance().getUserIds()) { 10504 if (origPermissions.getRuntimePermissionState( 10505 bp.name, userId) != null) { 10506 // Revoke the runtime permission and clear the flags. 10507 origPermissions.revokeRuntimePermission(bp, userId); 10508 origPermissions.updatePermissionFlags(bp, userId, 10509 PackageManager.MASK_PERMISSION_FLAGS, 0); 10510 // If we revoked a permission permission, we have to write. 10511 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10512 changedRuntimePermissionUserIds, userId); 10513 } 10514 } 10515 // Grant an install permission. 10516 if (permissionsState.grantInstallPermission(bp) != 10517 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10518 changedInstallPermission = true; 10519 } 10520 } break; 10521 10522 case GRANT_RUNTIME: { 10523 // Grant previously granted runtime permissions. 10524 for (int userId : UserManagerService.getInstance().getUserIds()) { 10525 PermissionState permissionState = origPermissions 10526 .getRuntimePermissionState(bp.name, userId); 10527 int flags = permissionState != null 10528 ? permissionState.getFlags() : 0; 10529 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10530 if (permissionsState.grantRuntimePermission(bp, userId) == 10531 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10532 // If we cannot put the permission as it was, we have to write. 10533 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10534 changedRuntimePermissionUserIds, userId); 10535 } 10536 // If the app supports runtime permissions no need for a review. 10537 if (mPermissionReviewRequired 10538 && appSupportsRuntimePermissions 10539 && (flags & PackageManager 10540 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10541 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10542 // Since we changed the flags, we have to write. 10543 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10544 changedRuntimePermissionUserIds, userId); 10545 } 10546 } else if (mPermissionReviewRequired 10547 && !appSupportsRuntimePermissions) { 10548 // For legacy apps that need a permission review, every new 10549 // runtime permission is granted but it is pending a review. 10550 // We also need to review only platform defined runtime 10551 // permissions as these are the only ones the platform knows 10552 // how to disable the API to simulate revocation as legacy 10553 // apps don't expect to run with revoked permissions. 10554 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10555 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10556 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10557 // We changed the flags, hence have to write. 10558 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10559 changedRuntimePermissionUserIds, userId); 10560 } 10561 } 10562 if (permissionsState.grantRuntimePermission(bp, userId) 10563 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10564 // We changed the permission, hence have to write. 10565 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10566 changedRuntimePermissionUserIds, userId); 10567 } 10568 } 10569 // Propagate the permission flags. 10570 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10571 } 10572 } break; 10573 10574 case GRANT_UPGRADE: { 10575 // Grant runtime permissions for a previously held install permission. 10576 PermissionState permissionState = origPermissions 10577 .getInstallPermissionState(bp.name); 10578 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10579 10580 if (origPermissions.revokeInstallPermission(bp) 10581 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10582 // We will be transferring the permission flags, so clear them. 10583 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10584 PackageManager.MASK_PERMISSION_FLAGS, 0); 10585 changedInstallPermission = true; 10586 } 10587 10588 // If the permission is not to be promoted to runtime we ignore it and 10589 // also its other flags as they are not applicable to install permissions. 10590 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10591 for (int userId : currentUserIds) { 10592 if (permissionsState.grantRuntimePermission(bp, userId) != 10593 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10594 // Transfer the permission flags. 10595 permissionsState.updatePermissionFlags(bp, userId, 10596 flags, flags); 10597 // If we granted the permission, we have to write. 10598 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10599 changedRuntimePermissionUserIds, userId); 10600 } 10601 } 10602 } 10603 } break; 10604 10605 default: { 10606 if (packageOfInterest == null 10607 || packageOfInterest.equals(pkg.packageName)) { 10608 Slog.w(TAG, "Not granting permission " + perm 10609 + " to package " + pkg.packageName 10610 + " because it was previously installed without"); 10611 } 10612 } break; 10613 } 10614 } else { 10615 if (permissionsState.revokeInstallPermission(bp) != 10616 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10617 // Also drop the permission flags. 10618 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10619 PackageManager.MASK_PERMISSION_FLAGS, 0); 10620 changedInstallPermission = true; 10621 Slog.i(TAG, "Un-granting permission " + perm 10622 + " from package " + pkg.packageName 10623 + " (protectionLevel=" + bp.protectionLevel 10624 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10625 + ")"); 10626 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10627 // Don't print warning for app op permissions, since it is fine for them 10628 // not to be granted, there is a UI for the user to decide. 10629 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10630 Slog.w(TAG, "Not granting permission " + perm 10631 + " to package " + pkg.packageName 10632 + " (protectionLevel=" + bp.protectionLevel 10633 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10634 + ")"); 10635 } 10636 } 10637 } 10638 } 10639 10640 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10641 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10642 // This is the first that we have heard about this package, so the 10643 // permissions we have now selected are fixed until explicitly 10644 // changed. 10645 ps.installPermissionsFixed = true; 10646 } 10647 10648 // Persist the runtime permissions state for users with changes. If permissions 10649 // were revoked because no app in the shared user declares them we have to 10650 // write synchronously to avoid losing runtime permissions state. 10651 for (int userId : changedRuntimePermissionUserIds) { 10652 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10653 } 10654 } 10655 10656 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10657 boolean allowed = false; 10658 final int NP = PackageParser.NEW_PERMISSIONS.length; 10659 for (int ip=0; ip<NP; ip++) { 10660 final PackageParser.NewPermissionInfo npi 10661 = PackageParser.NEW_PERMISSIONS[ip]; 10662 if (npi.name.equals(perm) 10663 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10664 allowed = true; 10665 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10666 + pkg.packageName); 10667 break; 10668 } 10669 } 10670 return allowed; 10671 } 10672 10673 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10674 BasePermission bp, PermissionsState origPermissions) { 10675 boolean privilegedPermission = (bp.protectionLevel 10676 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10677 boolean privappPermissionsDisable = 10678 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10679 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10680 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10681 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10682 && !platformPackage && platformPermission) { 10683 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10684 .getPrivAppPermissions(pkg.packageName); 10685 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10686 if (!whitelisted) { 10687 Slog.w(TAG, "Privileged permission " + perm + " for package " 10688 + pkg.packageName + " - not in privapp-permissions whitelist"); 10689 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10690 return false; 10691 } 10692 } 10693 } 10694 boolean allowed = (compareSignatures( 10695 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10696 == PackageManager.SIGNATURE_MATCH) 10697 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10698 == PackageManager.SIGNATURE_MATCH); 10699 if (!allowed && privilegedPermission) { 10700 if (isSystemApp(pkg)) { 10701 // For updated system applications, a system permission 10702 // is granted only if it had been defined by the original application. 10703 if (pkg.isUpdatedSystemApp()) { 10704 final PackageSetting sysPs = mSettings 10705 .getDisabledSystemPkgLPr(pkg.packageName); 10706 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10707 // If the original was granted this permission, we take 10708 // that grant decision as read and propagate it to the 10709 // update. 10710 if (sysPs.isPrivileged()) { 10711 allowed = true; 10712 } 10713 } else { 10714 // The system apk may have been updated with an older 10715 // version of the one on the data partition, but which 10716 // granted a new system permission that it didn't have 10717 // before. In this case we do want to allow the app to 10718 // now get the new permission if the ancestral apk is 10719 // privileged to get it. 10720 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10721 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10722 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10723 allowed = true; 10724 break; 10725 } 10726 } 10727 } 10728 // Also if a privileged parent package on the system image or any of 10729 // its children requested a privileged permission, the updated child 10730 // packages can also get the permission. 10731 if (pkg.parentPackage != null) { 10732 final PackageSetting disabledSysParentPs = mSettings 10733 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10734 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10735 && disabledSysParentPs.isPrivileged()) { 10736 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10737 allowed = true; 10738 } else if (disabledSysParentPs.pkg.childPackages != null) { 10739 final int count = disabledSysParentPs.pkg.childPackages.size(); 10740 for (int i = 0; i < count; i++) { 10741 PackageParser.Package disabledSysChildPkg = 10742 disabledSysParentPs.pkg.childPackages.get(i); 10743 if (isPackageRequestingPermission(disabledSysChildPkg, 10744 perm)) { 10745 allowed = true; 10746 break; 10747 } 10748 } 10749 } 10750 } 10751 } 10752 } 10753 } else { 10754 allowed = isPrivilegedApp(pkg); 10755 } 10756 } 10757 } 10758 if (!allowed) { 10759 if (!allowed && (bp.protectionLevel 10760 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10761 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10762 // If this was a previously normal/dangerous permission that got moved 10763 // to a system permission as part of the runtime permission redesign, then 10764 // we still want to blindly grant it to old apps. 10765 allowed = true; 10766 } 10767 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10768 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10769 // If this permission is to be granted to the system installer and 10770 // this app is an installer, then it gets the permission. 10771 allowed = true; 10772 } 10773 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10774 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10775 // If this permission is to be granted to the system verifier and 10776 // this app is a verifier, then it gets the permission. 10777 allowed = true; 10778 } 10779 if (!allowed && (bp.protectionLevel 10780 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10781 && isSystemApp(pkg)) { 10782 // Any pre-installed system app is allowed to get this permission. 10783 allowed = true; 10784 } 10785 if (!allowed && (bp.protectionLevel 10786 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10787 // For development permissions, a development permission 10788 // is granted only if it was already granted. 10789 allowed = origPermissions.hasInstallPermission(perm); 10790 } 10791 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10792 && pkg.packageName.equals(mSetupWizardPackage)) { 10793 // If this permission is to be granted to the system setup wizard and 10794 // this app is a setup wizard, then it gets the permission. 10795 allowed = true; 10796 } 10797 } 10798 return allowed; 10799 } 10800 10801 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10802 final int permCount = pkg.requestedPermissions.size(); 10803 for (int j = 0; j < permCount; j++) { 10804 String requestedPermission = pkg.requestedPermissions.get(j); 10805 if (permission.equals(requestedPermission)) { 10806 return true; 10807 } 10808 } 10809 return false; 10810 } 10811 10812 final class ActivityIntentResolver 10813 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10814 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10815 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 10816 if (!sUserManager.exists(userId)) return null; 10817 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 10818 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 10819 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 10820 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 10821 isEphemeral, userId); 10822 } 10823 10824 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10825 int userId) { 10826 if (!sUserManager.exists(userId)) return null; 10827 mFlags = flags; 10828 return super.queryIntent(intent, resolvedType, 10829 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 10830 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 10831 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 10832 } 10833 10834 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10835 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10836 if (!sUserManager.exists(userId)) return null; 10837 if (packageActivities == null) { 10838 return null; 10839 } 10840 mFlags = flags; 10841 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10842 final boolean vislbleToEphemeral = 10843 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 10844 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 10845 final int N = packageActivities.size(); 10846 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10847 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10848 10849 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10850 for (int i = 0; i < N; ++i) { 10851 intentFilters = packageActivities.get(i).intents; 10852 if (intentFilters != null && intentFilters.size() > 0) { 10853 PackageParser.ActivityIntentInfo[] array = 10854 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10855 intentFilters.toArray(array); 10856 listCut.add(array); 10857 } 10858 } 10859 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 10860 vislbleToEphemeral, isEphemeral, listCut, userId); 10861 } 10862 10863 /** 10864 * Finds a privileged activity that matches the specified activity names. 10865 */ 10866 private PackageParser.Activity findMatchingActivity( 10867 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10868 for (PackageParser.Activity sysActivity : activityList) { 10869 if (sysActivity.info.name.equals(activityInfo.name)) { 10870 return sysActivity; 10871 } 10872 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10873 return sysActivity; 10874 } 10875 if (sysActivity.info.targetActivity != null) { 10876 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10877 return sysActivity; 10878 } 10879 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10880 return sysActivity; 10881 } 10882 } 10883 } 10884 return null; 10885 } 10886 10887 public class IterGenerator<E> { 10888 public Iterator<E> generate(ActivityIntentInfo info) { 10889 return null; 10890 } 10891 } 10892 10893 public class ActionIterGenerator extends IterGenerator<String> { 10894 @Override 10895 public Iterator<String> generate(ActivityIntentInfo info) { 10896 return info.actionsIterator(); 10897 } 10898 } 10899 10900 public class CategoriesIterGenerator extends IterGenerator<String> { 10901 @Override 10902 public Iterator<String> generate(ActivityIntentInfo info) { 10903 return info.categoriesIterator(); 10904 } 10905 } 10906 10907 public class SchemesIterGenerator extends IterGenerator<String> { 10908 @Override 10909 public Iterator<String> generate(ActivityIntentInfo info) { 10910 return info.schemesIterator(); 10911 } 10912 } 10913 10914 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10915 @Override 10916 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10917 return info.authoritiesIterator(); 10918 } 10919 } 10920 10921 /** 10922 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10923 * MODIFIED. Do not pass in a list that should not be changed. 10924 */ 10925 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10926 IterGenerator<T> generator, Iterator<T> searchIterator) { 10927 // loop through the set of actions; every one must be found in the intent filter 10928 while (searchIterator.hasNext()) { 10929 // we must have at least one filter in the list to consider a match 10930 if (intentList.size() == 0) { 10931 break; 10932 } 10933 10934 final T searchAction = searchIterator.next(); 10935 10936 // loop through the set of intent filters 10937 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10938 while (intentIter.hasNext()) { 10939 final ActivityIntentInfo intentInfo = intentIter.next(); 10940 boolean selectionFound = false; 10941 10942 // loop through the intent filter's selection criteria; at least one 10943 // of them must match the searched criteria 10944 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10945 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10946 final T intentSelection = intentSelectionIter.next(); 10947 if (intentSelection != null && intentSelection.equals(searchAction)) { 10948 selectionFound = true; 10949 break; 10950 } 10951 } 10952 10953 // the selection criteria wasn't found in this filter's set; this filter 10954 // is not a potential match 10955 if (!selectionFound) { 10956 intentIter.remove(); 10957 } 10958 } 10959 } 10960 } 10961 10962 private boolean isProtectedAction(ActivityIntentInfo filter) { 10963 final Iterator<String> actionsIter = filter.actionsIterator(); 10964 while (actionsIter != null && actionsIter.hasNext()) { 10965 final String filterAction = actionsIter.next(); 10966 if (PROTECTED_ACTIONS.contains(filterAction)) { 10967 return true; 10968 } 10969 } 10970 return false; 10971 } 10972 10973 /** 10974 * Adjusts the priority of the given intent filter according to policy. 10975 * <p> 10976 * <ul> 10977 * <li>The priority for non privileged applications is capped to '0'</li> 10978 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10979 * <li>The priority for unbundled updates to privileged applications is capped to the 10980 * priority defined on the system partition</li> 10981 * </ul> 10982 * <p> 10983 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10984 * allowed to obtain any priority on any action. 10985 */ 10986 private void adjustPriority( 10987 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10988 // nothing to do; priority is fine as-is 10989 if (intent.getPriority() <= 0) { 10990 return; 10991 } 10992 10993 final ActivityInfo activityInfo = intent.activity.info; 10994 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10995 10996 final boolean privilegedApp = 10997 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10998 if (!privilegedApp) { 10999 // non-privileged applications can never define a priority >0 11000 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11001 + " package: " + applicationInfo.packageName 11002 + " activity: " + intent.activity.className 11003 + " origPrio: " + intent.getPriority()); 11004 intent.setPriority(0); 11005 return; 11006 } 11007 11008 if (systemActivities == null) { 11009 // the system package is not disabled; we're parsing the system partition 11010 if (isProtectedAction(intent)) { 11011 if (mDeferProtectedFilters) { 11012 // We can't deal with these just yet. No component should ever obtain a 11013 // >0 priority for a protected actions, with ONE exception -- the setup 11014 // wizard. The setup wizard, however, cannot be known until we're able to 11015 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11016 // until all intent filters have been processed. Chicken, meet egg. 11017 // Let the filter temporarily have a high priority and rectify the 11018 // priorities after all system packages have been scanned. 11019 mProtectedFilters.add(intent); 11020 if (DEBUG_FILTERS) { 11021 Slog.i(TAG, "Protected action; save for later;" 11022 + " package: " + applicationInfo.packageName 11023 + " activity: " + intent.activity.className 11024 + " origPrio: " + intent.getPriority()); 11025 } 11026 return; 11027 } else { 11028 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11029 Slog.i(TAG, "No setup wizard;" 11030 + " All protected intents capped to priority 0"); 11031 } 11032 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11033 if (DEBUG_FILTERS) { 11034 Slog.i(TAG, "Found setup wizard;" 11035 + " allow priority " + intent.getPriority() + ";" 11036 + " package: " + intent.activity.info.packageName 11037 + " activity: " + intent.activity.className 11038 + " priority: " + intent.getPriority()); 11039 } 11040 // setup wizard gets whatever it wants 11041 return; 11042 } 11043 Slog.w(TAG, "Protected action; cap priority to 0;" 11044 + " package: " + intent.activity.info.packageName 11045 + " activity: " + intent.activity.className 11046 + " origPrio: " + intent.getPriority()); 11047 intent.setPriority(0); 11048 return; 11049 } 11050 } 11051 // privileged apps on the system image get whatever priority they request 11052 return; 11053 } 11054 11055 // privileged app unbundled update ... try to find the same activity 11056 final PackageParser.Activity foundActivity = 11057 findMatchingActivity(systemActivities, activityInfo); 11058 if (foundActivity == null) { 11059 // this is a new activity; it cannot obtain >0 priority 11060 if (DEBUG_FILTERS) { 11061 Slog.i(TAG, "New activity; cap priority to 0;" 11062 + " package: " + applicationInfo.packageName 11063 + " activity: " + intent.activity.className 11064 + " origPrio: " + intent.getPriority()); 11065 } 11066 intent.setPriority(0); 11067 return; 11068 } 11069 11070 // found activity, now check for filter equivalence 11071 11072 // a shallow copy is enough; we modify the list, not its contents 11073 final List<ActivityIntentInfo> intentListCopy = 11074 new ArrayList<>(foundActivity.intents); 11075 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11076 11077 // find matching action subsets 11078 final Iterator<String> actionsIterator = intent.actionsIterator(); 11079 if (actionsIterator != null) { 11080 getIntentListSubset( 11081 intentListCopy, new ActionIterGenerator(), actionsIterator); 11082 if (intentListCopy.size() == 0) { 11083 // no more intents to match; we're not equivalent 11084 if (DEBUG_FILTERS) { 11085 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11086 + " package: " + applicationInfo.packageName 11087 + " activity: " + intent.activity.className 11088 + " origPrio: " + intent.getPriority()); 11089 } 11090 intent.setPriority(0); 11091 return; 11092 } 11093 } 11094 11095 // find matching category subsets 11096 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11097 if (categoriesIterator != null) { 11098 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11099 categoriesIterator); 11100 if (intentListCopy.size() == 0) { 11101 // no more intents to match; we're not equivalent 11102 if (DEBUG_FILTERS) { 11103 Slog.i(TAG, "Mismatched category; 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 schemes subsets 11114 final Iterator<String> schemesIterator = intent.schemesIterator(); 11115 if (schemesIterator != null) { 11116 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11117 schemesIterator); 11118 if (intentListCopy.size() == 0) { 11119 // no more intents to match; we're not equivalent 11120 if (DEBUG_FILTERS) { 11121 Slog.i(TAG, "Mismatched scheme; 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 authorities subsets 11132 final Iterator<IntentFilter.AuthorityEntry> 11133 authoritiesIterator = intent.authoritiesIterator(); 11134 if (authoritiesIterator != null) { 11135 getIntentListSubset(intentListCopy, 11136 new AuthoritiesIterGenerator(), 11137 authoritiesIterator); 11138 if (intentListCopy.size() == 0) { 11139 // no more intents to match; we're not equivalent 11140 if (DEBUG_FILTERS) { 11141 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11142 + " package: " + applicationInfo.packageName 11143 + " activity: " + intent.activity.className 11144 + " origPrio: " + intent.getPriority()); 11145 } 11146 intent.setPriority(0); 11147 return; 11148 } 11149 } 11150 11151 // we found matching filter(s); app gets the max priority of all intents 11152 int cappedPriority = 0; 11153 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11154 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11155 } 11156 if (intent.getPriority() > cappedPriority) { 11157 if (DEBUG_FILTERS) { 11158 Slog.i(TAG, "Found matching filter(s);" 11159 + " cap priority to " + cappedPriority + ";" 11160 + " package: " + applicationInfo.packageName 11161 + " activity: " + intent.activity.className 11162 + " origPrio: " + intent.getPriority()); 11163 } 11164 intent.setPriority(cappedPriority); 11165 return; 11166 } 11167 // all this for nothing; the requested priority was <= what was on the system 11168 } 11169 11170 public final void addActivity(PackageParser.Activity a, String type) { 11171 mActivities.put(a.getComponentName(), a); 11172 if (DEBUG_SHOW_INFO) 11173 Log.v( 11174 TAG, " " + type + " " + 11175 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11176 if (DEBUG_SHOW_INFO) 11177 Log.v(TAG, " Class=" + a.info.name); 11178 final int NI = a.intents.size(); 11179 for (int j=0; j<NI; j++) { 11180 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11181 if ("activity".equals(type)) { 11182 final PackageSetting ps = 11183 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11184 final List<PackageParser.Activity> systemActivities = 11185 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11186 adjustPriority(systemActivities, intent); 11187 } 11188 if (DEBUG_SHOW_INFO) { 11189 Log.v(TAG, " IntentFilter:"); 11190 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11191 } 11192 if (!intent.debugCheck()) { 11193 Log.w(TAG, "==> For Activity " + a.info.name); 11194 } 11195 addFilter(intent); 11196 } 11197 } 11198 11199 public final void removeActivity(PackageParser.Activity a, String type) { 11200 mActivities.remove(a.getComponentName()); 11201 if (DEBUG_SHOW_INFO) { 11202 Log.v(TAG, " " + type + " " 11203 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11204 : a.info.name) + ":"); 11205 Log.v(TAG, " Class=" + a.info.name); 11206 } 11207 final int NI = a.intents.size(); 11208 for (int j=0; j<NI; j++) { 11209 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11210 if (DEBUG_SHOW_INFO) { 11211 Log.v(TAG, " IntentFilter:"); 11212 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11213 } 11214 removeFilter(intent); 11215 } 11216 } 11217 11218 @Override 11219 protected boolean allowFilterResult( 11220 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11221 ActivityInfo filterAi = filter.activity.info; 11222 for (int i=dest.size()-1; i>=0; i--) { 11223 ActivityInfo destAi = dest.get(i).activityInfo; 11224 if (destAi.name == filterAi.name 11225 && destAi.packageName == filterAi.packageName) { 11226 return false; 11227 } 11228 } 11229 return true; 11230 } 11231 11232 @Override 11233 protected ActivityIntentInfo[] newArray(int size) { 11234 return new ActivityIntentInfo[size]; 11235 } 11236 11237 @Override 11238 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11239 if (!sUserManager.exists(userId)) return true; 11240 PackageParser.Package p = filter.activity.owner; 11241 if (p != null) { 11242 PackageSetting ps = (PackageSetting)p.mExtras; 11243 if (ps != null) { 11244 // System apps are never considered stopped for purposes of 11245 // filtering, because there may be no way for the user to 11246 // actually re-launch them. 11247 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11248 && ps.getStopped(userId); 11249 } 11250 } 11251 return false; 11252 } 11253 11254 @Override 11255 protected boolean isPackageForFilter(String packageName, 11256 PackageParser.ActivityIntentInfo info) { 11257 return packageName.equals(info.activity.owner.packageName); 11258 } 11259 11260 @Override 11261 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11262 int match, int userId) { 11263 if (!sUserManager.exists(userId)) return null; 11264 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11265 return null; 11266 } 11267 final PackageParser.Activity activity = info.activity; 11268 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11269 if (ps == null) { 11270 return null; 11271 } 11272 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11273 ps.readUserState(userId), userId); 11274 if (ai == null) { 11275 return null; 11276 } 11277 final ResolveInfo res = new ResolveInfo(); 11278 res.activityInfo = ai; 11279 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11280 res.filter = info; 11281 } 11282 if (info != null) { 11283 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11284 } 11285 res.priority = info.getPriority(); 11286 res.preferredOrder = activity.owner.mPreferredOrder; 11287 //System.out.println("Result: " + res.activityInfo.className + 11288 // " = " + res.priority); 11289 res.match = match; 11290 res.isDefault = info.hasDefault; 11291 res.labelRes = info.labelRes; 11292 res.nonLocalizedLabel = info.nonLocalizedLabel; 11293 if (userNeedsBadging(userId)) { 11294 res.noResourceId = true; 11295 } else { 11296 res.icon = info.icon; 11297 } 11298 res.iconResourceId = info.icon; 11299 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11300 return res; 11301 } 11302 11303 @Override 11304 protected void sortResults(List<ResolveInfo> results) { 11305 Collections.sort(results, mResolvePrioritySorter); 11306 } 11307 11308 @Override 11309 protected void dumpFilter(PrintWriter out, String prefix, 11310 PackageParser.ActivityIntentInfo filter) { 11311 out.print(prefix); out.print( 11312 Integer.toHexString(System.identityHashCode(filter.activity))); 11313 out.print(' '); 11314 filter.activity.printComponentShortName(out); 11315 out.print(" filter "); 11316 out.println(Integer.toHexString(System.identityHashCode(filter))); 11317 } 11318 11319 @Override 11320 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11321 return filter.activity; 11322 } 11323 11324 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11325 PackageParser.Activity activity = (PackageParser.Activity)label; 11326 out.print(prefix); out.print( 11327 Integer.toHexString(System.identityHashCode(activity))); 11328 out.print(' '); 11329 activity.printComponentShortName(out); 11330 if (count > 1) { 11331 out.print(" ("); out.print(count); out.print(" filters)"); 11332 } 11333 out.println(); 11334 } 11335 11336 // Keys are String (activity class name), values are Activity. 11337 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11338 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11339 private int mFlags; 11340 } 11341 11342 private final class ServiceIntentResolver 11343 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11344 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11345 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11346 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11347 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11348 isEphemeral, userId); 11349 } 11350 11351 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11352 int userId) { 11353 if (!sUserManager.exists(userId)) return null; 11354 mFlags = flags; 11355 return super.queryIntent(intent, resolvedType, 11356 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11357 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11358 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11359 } 11360 11361 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11362 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11363 if (!sUserManager.exists(userId)) return null; 11364 if (packageServices == null) { 11365 return null; 11366 } 11367 mFlags = flags; 11368 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11369 final boolean vislbleToEphemeral = 11370 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11371 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11372 final int N = packageServices.size(); 11373 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11374 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11375 11376 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11377 for (int i = 0; i < N; ++i) { 11378 intentFilters = packageServices.get(i).intents; 11379 if (intentFilters != null && intentFilters.size() > 0) { 11380 PackageParser.ServiceIntentInfo[] array = 11381 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11382 intentFilters.toArray(array); 11383 listCut.add(array); 11384 } 11385 } 11386 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11387 vislbleToEphemeral, isEphemeral, listCut, userId); 11388 } 11389 11390 public final void addService(PackageParser.Service s) { 11391 mServices.put(s.getComponentName(), s); 11392 if (DEBUG_SHOW_INFO) { 11393 Log.v(TAG, " " 11394 + (s.info.nonLocalizedLabel != null 11395 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11396 Log.v(TAG, " Class=" + s.info.name); 11397 } 11398 final int NI = s.intents.size(); 11399 int j; 11400 for (j=0; j<NI; j++) { 11401 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11402 if (DEBUG_SHOW_INFO) { 11403 Log.v(TAG, " IntentFilter:"); 11404 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11405 } 11406 if (!intent.debugCheck()) { 11407 Log.w(TAG, "==> For Service " + s.info.name); 11408 } 11409 addFilter(intent); 11410 } 11411 } 11412 11413 public final void removeService(PackageParser.Service s) { 11414 mServices.remove(s.getComponentName()); 11415 if (DEBUG_SHOW_INFO) { 11416 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11417 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11418 Log.v(TAG, " Class=" + s.info.name); 11419 } 11420 final int NI = s.intents.size(); 11421 int j; 11422 for (j=0; j<NI; j++) { 11423 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11424 if (DEBUG_SHOW_INFO) { 11425 Log.v(TAG, " IntentFilter:"); 11426 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11427 } 11428 removeFilter(intent); 11429 } 11430 } 11431 11432 @Override 11433 protected boolean allowFilterResult( 11434 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11435 ServiceInfo filterSi = filter.service.info; 11436 for (int i=dest.size()-1; i>=0; i--) { 11437 ServiceInfo destAi = dest.get(i).serviceInfo; 11438 if (destAi.name == filterSi.name 11439 && destAi.packageName == filterSi.packageName) { 11440 return false; 11441 } 11442 } 11443 return true; 11444 } 11445 11446 @Override 11447 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11448 return new PackageParser.ServiceIntentInfo[size]; 11449 } 11450 11451 @Override 11452 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11453 if (!sUserManager.exists(userId)) return true; 11454 PackageParser.Package p = filter.service.owner; 11455 if (p != null) { 11456 PackageSetting ps = (PackageSetting)p.mExtras; 11457 if (ps != null) { 11458 // System apps are never considered stopped for purposes of 11459 // filtering, because there may be no way for the user to 11460 // actually re-launch them. 11461 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11462 && ps.getStopped(userId); 11463 } 11464 } 11465 return false; 11466 } 11467 11468 @Override 11469 protected boolean isPackageForFilter(String packageName, 11470 PackageParser.ServiceIntentInfo info) { 11471 return packageName.equals(info.service.owner.packageName); 11472 } 11473 11474 @Override 11475 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11476 int match, int userId) { 11477 if (!sUserManager.exists(userId)) return null; 11478 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11479 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11480 return null; 11481 } 11482 final PackageParser.Service service = info.service; 11483 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11484 if (ps == null) { 11485 return null; 11486 } 11487 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11488 ps.readUserState(userId), userId); 11489 if (si == null) { 11490 return null; 11491 } 11492 final ResolveInfo res = new ResolveInfo(); 11493 res.serviceInfo = si; 11494 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11495 res.filter = filter; 11496 } 11497 res.priority = info.getPriority(); 11498 res.preferredOrder = service.owner.mPreferredOrder; 11499 res.match = match; 11500 res.isDefault = info.hasDefault; 11501 res.labelRes = info.labelRes; 11502 res.nonLocalizedLabel = info.nonLocalizedLabel; 11503 res.icon = info.icon; 11504 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11505 return res; 11506 } 11507 11508 @Override 11509 protected void sortResults(List<ResolveInfo> results) { 11510 Collections.sort(results, mResolvePrioritySorter); 11511 } 11512 11513 @Override 11514 protected void dumpFilter(PrintWriter out, String prefix, 11515 PackageParser.ServiceIntentInfo filter) { 11516 out.print(prefix); out.print( 11517 Integer.toHexString(System.identityHashCode(filter.service))); 11518 out.print(' '); 11519 filter.service.printComponentShortName(out); 11520 out.print(" filter "); 11521 out.println(Integer.toHexString(System.identityHashCode(filter))); 11522 } 11523 11524 @Override 11525 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11526 return filter.service; 11527 } 11528 11529 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11530 PackageParser.Service service = (PackageParser.Service)label; 11531 out.print(prefix); out.print( 11532 Integer.toHexString(System.identityHashCode(service))); 11533 out.print(' '); 11534 service.printComponentShortName(out); 11535 if (count > 1) { 11536 out.print(" ("); out.print(count); out.print(" filters)"); 11537 } 11538 out.println(); 11539 } 11540 11541// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11542// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11543// final List<ResolveInfo> retList = Lists.newArrayList(); 11544// while (i.hasNext()) { 11545// final ResolveInfo resolveInfo = (ResolveInfo) i; 11546// if (isEnabledLP(resolveInfo.serviceInfo)) { 11547// retList.add(resolveInfo); 11548// } 11549// } 11550// return retList; 11551// } 11552 11553 // Keys are String (activity class name), values are Activity. 11554 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11555 = new ArrayMap<ComponentName, PackageParser.Service>(); 11556 private int mFlags; 11557 } 11558 11559 private final class ProviderIntentResolver 11560 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11561 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11562 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11563 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11564 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11565 isEphemeral, userId); 11566 } 11567 11568 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11569 int userId) { 11570 if (!sUserManager.exists(userId)) 11571 return null; 11572 mFlags = flags; 11573 return super.queryIntent(intent, resolvedType, 11574 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11575 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11576 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11577 } 11578 11579 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11580 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11581 if (!sUserManager.exists(userId)) 11582 return null; 11583 if (packageProviders == null) { 11584 return null; 11585 } 11586 mFlags = flags; 11587 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11588 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11589 final boolean vislbleToEphemeral = 11590 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11591 final int N = packageProviders.size(); 11592 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11593 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11594 11595 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11596 for (int i = 0; i < N; ++i) { 11597 intentFilters = packageProviders.get(i).intents; 11598 if (intentFilters != null && intentFilters.size() > 0) { 11599 PackageParser.ProviderIntentInfo[] array = 11600 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11601 intentFilters.toArray(array); 11602 listCut.add(array); 11603 } 11604 } 11605 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11606 vislbleToEphemeral, isEphemeral, listCut, userId); 11607 } 11608 11609 public final void addProvider(PackageParser.Provider p) { 11610 if (mProviders.containsKey(p.getComponentName())) { 11611 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11612 return; 11613 } 11614 11615 mProviders.put(p.getComponentName(), p); 11616 if (DEBUG_SHOW_INFO) { 11617 Log.v(TAG, " " 11618 + (p.info.nonLocalizedLabel != null 11619 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11620 Log.v(TAG, " Class=" + p.info.name); 11621 } 11622 final int NI = p.intents.size(); 11623 int j; 11624 for (j = 0; j < NI; j++) { 11625 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11626 if (DEBUG_SHOW_INFO) { 11627 Log.v(TAG, " IntentFilter:"); 11628 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11629 } 11630 if (!intent.debugCheck()) { 11631 Log.w(TAG, "==> For Provider " + p.info.name); 11632 } 11633 addFilter(intent); 11634 } 11635 } 11636 11637 public final void removeProvider(PackageParser.Provider p) { 11638 mProviders.remove(p.getComponentName()); 11639 if (DEBUG_SHOW_INFO) { 11640 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11641 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11642 Log.v(TAG, " Class=" + p.info.name); 11643 } 11644 final int NI = p.intents.size(); 11645 int j; 11646 for (j = 0; j < NI; j++) { 11647 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11648 if (DEBUG_SHOW_INFO) { 11649 Log.v(TAG, " IntentFilter:"); 11650 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11651 } 11652 removeFilter(intent); 11653 } 11654 } 11655 11656 @Override 11657 protected boolean allowFilterResult( 11658 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11659 ProviderInfo filterPi = filter.provider.info; 11660 for (int i = dest.size() - 1; i >= 0; i--) { 11661 ProviderInfo destPi = dest.get(i).providerInfo; 11662 if (destPi.name == filterPi.name 11663 && destPi.packageName == filterPi.packageName) { 11664 return false; 11665 } 11666 } 11667 return true; 11668 } 11669 11670 @Override 11671 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11672 return new PackageParser.ProviderIntentInfo[size]; 11673 } 11674 11675 @Override 11676 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11677 if (!sUserManager.exists(userId)) 11678 return true; 11679 PackageParser.Package p = filter.provider.owner; 11680 if (p != null) { 11681 PackageSetting ps = (PackageSetting) p.mExtras; 11682 if (ps != null) { 11683 // System apps are never considered stopped for purposes of 11684 // filtering, because there may be no way for the user to 11685 // actually re-launch them. 11686 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11687 && ps.getStopped(userId); 11688 } 11689 } 11690 return false; 11691 } 11692 11693 @Override 11694 protected boolean isPackageForFilter(String packageName, 11695 PackageParser.ProviderIntentInfo info) { 11696 return packageName.equals(info.provider.owner.packageName); 11697 } 11698 11699 @Override 11700 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11701 int match, int userId) { 11702 if (!sUserManager.exists(userId)) 11703 return null; 11704 final PackageParser.ProviderIntentInfo info = filter; 11705 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11706 return null; 11707 } 11708 final PackageParser.Provider provider = info.provider; 11709 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11710 if (ps == null) { 11711 return null; 11712 } 11713 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11714 ps.readUserState(userId), userId); 11715 if (pi == null) { 11716 return null; 11717 } 11718 final ResolveInfo res = new ResolveInfo(); 11719 res.providerInfo = pi; 11720 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11721 res.filter = filter; 11722 } 11723 res.priority = info.getPriority(); 11724 res.preferredOrder = provider.owner.mPreferredOrder; 11725 res.match = match; 11726 res.isDefault = info.hasDefault; 11727 res.labelRes = info.labelRes; 11728 res.nonLocalizedLabel = info.nonLocalizedLabel; 11729 res.icon = info.icon; 11730 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11731 return res; 11732 } 11733 11734 @Override 11735 protected void sortResults(List<ResolveInfo> results) { 11736 Collections.sort(results, mResolvePrioritySorter); 11737 } 11738 11739 @Override 11740 protected void dumpFilter(PrintWriter out, String prefix, 11741 PackageParser.ProviderIntentInfo filter) { 11742 out.print(prefix); 11743 out.print( 11744 Integer.toHexString(System.identityHashCode(filter.provider))); 11745 out.print(' '); 11746 filter.provider.printComponentShortName(out); 11747 out.print(" filter "); 11748 out.println(Integer.toHexString(System.identityHashCode(filter))); 11749 } 11750 11751 @Override 11752 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11753 return filter.provider; 11754 } 11755 11756 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11757 PackageParser.Provider provider = (PackageParser.Provider)label; 11758 out.print(prefix); out.print( 11759 Integer.toHexString(System.identityHashCode(provider))); 11760 out.print(' '); 11761 provider.printComponentShortName(out); 11762 if (count > 1) { 11763 out.print(" ("); out.print(count); out.print(" filters)"); 11764 } 11765 out.println(); 11766 } 11767 11768 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11769 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11770 private int mFlags; 11771 } 11772 11773 static final class EphemeralIntentResolver 11774 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11775 /** 11776 * The result that has the highest defined order. Ordering applies on a 11777 * per-package basis. Mapping is from package name to Pair of order and 11778 * EphemeralResolveInfo. 11779 * <p> 11780 * NOTE: This is implemented as a field variable for convenience and efficiency. 11781 * By having a field variable, we're able to track filter ordering as soon as 11782 * a non-zero order is defined. Otherwise, multiple loops across the result set 11783 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11784 * this needs to be contained entirely within {@link #filterResults()}. 11785 */ 11786 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11787 11788 @Override 11789 protected EphemeralResponse[] newArray(int size) { 11790 return new EphemeralResponse[size]; 11791 } 11792 11793 @Override 11794 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11795 return true; 11796 } 11797 11798 @Override 11799 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11800 int userId) { 11801 if (!sUserManager.exists(userId)) { 11802 return null; 11803 } 11804 final String packageName = responseObj.resolveInfo.getPackageName(); 11805 final Integer order = responseObj.getOrder(); 11806 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11807 mOrderResult.get(packageName); 11808 // ordering is enabled and this item's order isn't high enough 11809 if (lastOrderResult != null && lastOrderResult.first >= order) { 11810 return null; 11811 } 11812 final EphemeralResolveInfo res = responseObj.resolveInfo; 11813 if (order > 0) { 11814 // non-zero order, enable ordering 11815 mOrderResult.put(packageName, new Pair<>(order, res)); 11816 } 11817 return responseObj; 11818 } 11819 11820 @Override 11821 protected void filterResults(List<EphemeralResponse> results) { 11822 // only do work if ordering is enabled [most of the time it won't be] 11823 if (mOrderResult.size() == 0) { 11824 return; 11825 } 11826 int resultSize = results.size(); 11827 for (int i = 0; i < resultSize; i++) { 11828 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11829 final String packageName = info.getPackageName(); 11830 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11831 if (savedInfo == null) { 11832 // package doesn't having ordering 11833 continue; 11834 } 11835 if (savedInfo.second == info) { 11836 // circled back to the highest ordered item; remove from order list 11837 mOrderResult.remove(savedInfo); 11838 if (mOrderResult.size() == 0) { 11839 // no more ordered items 11840 break; 11841 } 11842 continue; 11843 } 11844 // item has a worse order, remove it from the result list 11845 results.remove(i); 11846 resultSize--; 11847 i--; 11848 } 11849 } 11850 } 11851 11852 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11853 new Comparator<ResolveInfo>() { 11854 public int compare(ResolveInfo r1, ResolveInfo r2) { 11855 int v1 = r1.priority; 11856 int v2 = r2.priority; 11857 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11858 if (v1 != v2) { 11859 return (v1 > v2) ? -1 : 1; 11860 } 11861 v1 = r1.preferredOrder; 11862 v2 = r2.preferredOrder; 11863 if (v1 != v2) { 11864 return (v1 > v2) ? -1 : 1; 11865 } 11866 if (r1.isDefault != r2.isDefault) { 11867 return r1.isDefault ? -1 : 1; 11868 } 11869 v1 = r1.match; 11870 v2 = r2.match; 11871 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11872 if (v1 != v2) { 11873 return (v1 > v2) ? -1 : 1; 11874 } 11875 if (r1.system != r2.system) { 11876 return r1.system ? -1 : 1; 11877 } 11878 if (r1.activityInfo != null) { 11879 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11880 } 11881 if (r1.serviceInfo != null) { 11882 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11883 } 11884 if (r1.providerInfo != null) { 11885 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11886 } 11887 return 0; 11888 } 11889 }; 11890 11891 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11892 new Comparator<ProviderInfo>() { 11893 public int compare(ProviderInfo p1, ProviderInfo p2) { 11894 final int v1 = p1.initOrder; 11895 final int v2 = p2.initOrder; 11896 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11897 } 11898 }; 11899 11900 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11901 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11902 final int[] userIds) { 11903 mHandler.post(new Runnable() { 11904 @Override 11905 public void run() { 11906 try { 11907 final IActivityManager am = ActivityManager.getService(); 11908 if (am == null) return; 11909 final int[] resolvedUserIds; 11910 if (userIds == null) { 11911 resolvedUserIds = am.getRunningUserIds(); 11912 } else { 11913 resolvedUserIds = userIds; 11914 } 11915 for (int id : resolvedUserIds) { 11916 final Intent intent = new Intent(action, 11917 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11918 if (extras != null) { 11919 intent.putExtras(extras); 11920 } 11921 if (targetPkg != null) { 11922 intent.setPackage(targetPkg); 11923 } 11924 // Modify the UID when posting to other users 11925 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11926 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11927 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11928 intent.putExtra(Intent.EXTRA_UID, uid); 11929 } 11930 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11931 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11932 if (DEBUG_BROADCASTS) { 11933 RuntimeException here = new RuntimeException("here"); 11934 here.fillInStackTrace(); 11935 Slog.d(TAG, "Sending to user " + id + ": " 11936 + intent.toShortString(false, true, false, false) 11937 + " " + intent.getExtras(), here); 11938 } 11939 am.broadcastIntent(null, intent, null, finishedReceiver, 11940 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11941 null, finishedReceiver != null, false, id); 11942 } 11943 } catch (RemoteException ex) { 11944 } 11945 } 11946 }); 11947 } 11948 11949 /** 11950 * Check if the external storage media is available. This is true if there 11951 * is a mounted external storage medium or if the external storage is 11952 * emulated. 11953 */ 11954 private boolean isExternalMediaAvailable() { 11955 return mMediaMounted || Environment.isExternalStorageEmulated(); 11956 } 11957 11958 @Override 11959 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11960 // writer 11961 synchronized (mPackages) { 11962 if (!isExternalMediaAvailable()) { 11963 // If the external storage is no longer mounted at this point, 11964 // the caller may not have been able to delete all of this 11965 // packages files and can not delete any more. Bail. 11966 return null; 11967 } 11968 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11969 if (lastPackage != null) { 11970 pkgs.remove(lastPackage); 11971 } 11972 if (pkgs.size() > 0) { 11973 return pkgs.get(0); 11974 } 11975 } 11976 return null; 11977 } 11978 11979 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11980 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11981 userId, andCode ? 1 : 0, packageName); 11982 if (mSystemReady) { 11983 msg.sendToTarget(); 11984 } else { 11985 if (mPostSystemReadyMessages == null) { 11986 mPostSystemReadyMessages = new ArrayList<>(); 11987 } 11988 mPostSystemReadyMessages.add(msg); 11989 } 11990 } 11991 11992 void startCleaningPackages() { 11993 // reader 11994 if (!isExternalMediaAvailable()) { 11995 return; 11996 } 11997 synchronized (mPackages) { 11998 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11999 return; 12000 } 12001 } 12002 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12003 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12004 IActivityManager am = ActivityManager.getService(); 12005 if (am != null) { 12006 try { 12007 am.startService(null, intent, null, mContext.getOpPackageName(), 12008 UserHandle.USER_SYSTEM); 12009 } catch (RemoteException e) { 12010 } 12011 } 12012 } 12013 12014 @Override 12015 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12016 int installFlags, String installerPackageName, int userId) { 12017 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12018 12019 final int callingUid = Binder.getCallingUid(); 12020 enforceCrossUserPermission(callingUid, userId, 12021 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12022 12023 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12024 try { 12025 if (observer != null) { 12026 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12027 } 12028 } catch (RemoteException re) { 12029 } 12030 return; 12031 } 12032 12033 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12034 installFlags |= PackageManager.INSTALL_FROM_ADB; 12035 12036 } else { 12037 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12038 // about installerPackageName. 12039 12040 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12041 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12042 } 12043 12044 UserHandle user; 12045 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12046 user = UserHandle.ALL; 12047 } else { 12048 user = new UserHandle(userId); 12049 } 12050 12051 // Only system components can circumvent runtime permissions when installing. 12052 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12053 && mContext.checkCallingOrSelfPermission(Manifest.permission 12054 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12055 throw new SecurityException("You need the " 12056 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12057 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12058 } 12059 12060 final File originFile = new File(originPath); 12061 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12062 12063 final Message msg = mHandler.obtainMessage(INIT_COPY); 12064 final VerificationInfo verificationInfo = new VerificationInfo( 12065 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12066 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12067 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12068 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12069 null /*certificates*/); 12070 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12071 msg.obj = params; 12072 12073 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12074 System.identityHashCode(msg.obj)); 12075 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12076 System.identityHashCode(msg.obj)); 12077 12078 mHandler.sendMessage(msg); 12079 } 12080 12081 void installStage(String packageName, File stagedDir, String stagedCid, 12082 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12083 String installerPackageName, int installerUid, UserHandle user, 12084 Certificate[][] certificates) { 12085 if (DEBUG_EPHEMERAL) { 12086 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12087 Slog.d(TAG, "Ephemeral install of " + packageName); 12088 } 12089 } 12090 final VerificationInfo verificationInfo = new VerificationInfo( 12091 sessionParams.originatingUri, sessionParams.referrerUri, 12092 sessionParams.originatingUid, installerUid); 12093 12094 final OriginInfo origin; 12095 if (stagedDir != null) { 12096 origin = OriginInfo.fromStagedFile(stagedDir); 12097 } else { 12098 origin = OriginInfo.fromStagedContainer(stagedCid); 12099 } 12100 12101 final Message msg = mHandler.obtainMessage(INIT_COPY); 12102 final InstallParams params = new InstallParams(origin, null, observer, 12103 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12104 verificationInfo, user, sessionParams.abiOverride, 12105 sessionParams.grantedRuntimePermissions, certificates); 12106 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12107 msg.obj = params; 12108 12109 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12110 System.identityHashCode(msg.obj)); 12111 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12112 System.identityHashCode(msg.obj)); 12113 12114 mHandler.sendMessage(msg); 12115 } 12116 12117 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12118 int userId) { 12119 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12120 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12121 } 12122 12123 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12124 int appId, int... userIds) { 12125 if (ArrayUtils.isEmpty(userIds)) { 12126 return; 12127 } 12128 Bundle extras = new Bundle(1); 12129 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12130 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12131 12132 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12133 packageName, extras, 0, null, null, userIds); 12134 if (isSystem) { 12135 mHandler.post(() -> { 12136 for (int userId : userIds) { 12137 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12138 } 12139 } 12140 ); 12141 } 12142 } 12143 12144 /** 12145 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12146 * automatically without needing an explicit launch. 12147 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12148 */ 12149 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12150 // If user is not running, the app didn't miss any broadcast 12151 if (!mUserManagerInternal.isUserRunning(userId)) { 12152 return; 12153 } 12154 final IActivityManager am = ActivityManager.getService(); 12155 try { 12156 // Deliver LOCKED_BOOT_COMPLETED first 12157 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12158 .setPackage(packageName); 12159 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12160 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12161 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12162 12163 // Deliver BOOT_COMPLETED only if user is unlocked 12164 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12165 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12166 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12167 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12168 } 12169 } catch (RemoteException e) { 12170 throw e.rethrowFromSystemServer(); 12171 } 12172 } 12173 12174 @Override 12175 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12176 int userId) { 12177 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12178 PackageSetting pkgSetting; 12179 final int uid = Binder.getCallingUid(); 12180 enforceCrossUserPermission(uid, userId, 12181 true /* requireFullPermission */, true /* checkShell */, 12182 "setApplicationHiddenSetting for user " + userId); 12183 12184 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12185 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12186 return false; 12187 } 12188 12189 long callingId = Binder.clearCallingIdentity(); 12190 try { 12191 boolean sendAdded = false; 12192 boolean sendRemoved = false; 12193 // writer 12194 synchronized (mPackages) { 12195 pkgSetting = mSettings.mPackages.get(packageName); 12196 if (pkgSetting == null) { 12197 return false; 12198 } 12199 // Do not allow "android" is being disabled 12200 if ("android".equals(packageName)) { 12201 Slog.w(TAG, "Cannot hide package: android"); 12202 return false; 12203 } 12204 // Only allow protected packages to hide themselves. 12205 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12206 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12207 Slog.w(TAG, "Not hiding protected package: " + packageName); 12208 return false; 12209 } 12210 12211 if (pkgSetting.getHidden(userId) != hidden) { 12212 pkgSetting.setHidden(hidden, userId); 12213 mSettings.writePackageRestrictionsLPr(userId); 12214 if (hidden) { 12215 sendRemoved = true; 12216 } else { 12217 sendAdded = true; 12218 } 12219 } 12220 } 12221 if (sendAdded) { 12222 sendPackageAddedForUser(packageName, pkgSetting, userId); 12223 return true; 12224 } 12225 if (sendRemoved) { 12226 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12227 "hiding pkg"); 12228 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12229 return true; 12230 } 12231 } finally { 12232 Binder.restoreCallingIdentity(callingId); 12233 } 12234 return false; 12235 } 12236 12237 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12238 int userId) { 12239 final PackageRemovedInfo info = new PackageRemovedInfo(); 12240 info.removedPackage = packageName; 12241 info.removedUsers = new int[] {userId}; 12242 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12243 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12244 } 12245 12246 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12247 if (pkgList.length > 0) { 12248 Bundle extras = new Bundle(1); 12249 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12250 12251 sendPackageBroadcast( 12252 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12253 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12254 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12255 new int[] {userId}); 12256 } 12257 } 12258 12259 /** 12260 * Returns true if application is not found or there was an error. Otherwise it returns 12261 * the hidden state of the package for the given user. 12262 */ 12263 @Override 12264 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12265 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12267 true /* requireFullPermission */, false /* checkShell */, 12268 "getApplicationHidden for user " + userId); 12269 PackageSetting pkgSetting; 12270 long callingId = Binder.clearCallingIdentity(); 12271 try { 12272 // writer 12273 synchronized (mPackages) { 12274 pkgSetting = mSettings.mPackages.get(packageName); 12275 if (pkgSetting == null) { 12276 return true; 12277 } 12278 return pkgSetting.getHidden(userId); 12279 } 12280 } finally { 12281 Binder.restoreCallingIdentity(callingId); 12282 } 12283 } 12284 12285 /** 12286 * @hide 12287 */ 12288 @Override 12289 public int installExistingPackageAsUser(String packageName, int userId) { 12290 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12291 null); 12292 PackageSetting pkgSetting; 12293 final int uid = Binder.getCallingUid(); 12294 enforceCrossUserPermission(uid, userId, 12295 true /* requireFullPermission */, true /* checkShell */, 12296 "installExistingPackage for user " + userId); 12297 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12298 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12299 } 12300 12301 long callingId = Binder.clearCallingIdentity(); 12302 try { 12303 boolean installed = false; 12304 12305 // writer 12306 synchronized (mPackages) { 12307 pkgSetting = mSettings.mPackages.get(packageName); 12308 if (pkgSetting == null) { 12309 return PackageManager.INSTALL_FAILED_INVALID_URI; 12310 } 12311 if (!pkgSetting.getInstalled(userId)) { 12312 pkgSetting.setInstalled(true, userId); 12313 pkgSetting.setHidden(false, userId); 12314 mSettings.writePackageRestrictionsLPr(userId); 12315 installed = true; 12316 } 12317 } 12318 12319 if (installed) { 12320 if (pkgSetting.pkg != null) { 12321 synchronized (mInstallLock) { 12322 // We don't need to freeze for a brand new install 12323 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12324 } 12325 } 12326 sendPackageAddedForUser(packageName, pkgSetting, userId); 12327 } 12328 } finally { 12329 Binder.restoreCallingIdentity(callingId); 12330 } 12331 12332 return PackageManager.INSTALL_SUCCEEDED; 12333 } 12334 12335 boolean isUserRestricted(int userId, String restrictionKey) { 12336 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12337 if (restrictions.getBoolean(restrictionKey, false)) { 12338 Log.w(TAG, "User is restricted: " + restrictionKey); 12339 return true; 12340 } 12341 return false; 12342 } 12343 12344 @Override 12345 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12346 int userId) { 12347 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12348 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12349 true /* requireFullPermission */, true /* checkShell */, 12350 "setPackagesSuspended for user " + userId); 12351 12352 if (ArrayUtils.isEmpty(packageNames)) { 12353 return packageNames; 12354 } 12355 12356 // List of package names for whom the suspended state has changed. 12357 List<String> changedPackages = new ArrayList<>(packageNames.length); 12358 // List of package names for whom the suspended state is not set as requested in this 12359 // method. 12360 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12361 long callingId = Binder.clearCallingIdentity(); 12362 try { 12363 for (int i = 0; i < packageNames.length; i++) { 12364 String packageName = packageNames[i]; 12365 boolean changed = false; 12366 final int appId; 12367 synchronized (mPackages) { 12368 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12369 if (pkgSetting == null) { 12370 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12371 + "\". Skipping suspending/un-suspending."); 12372 unactionedPackages.add(packageName); 12373 continue; 12374 } 12375 appId = pkgSetting.appId; 12376 if (pkgSetting.getSuspended(userId) != suspended) { 12377 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12378 unactionedPackages.add(packageName); 12379 continue; 12380 } 12381 pkgSetting.setSuspended(suspended, userId); 12382 mSettings.writePackageRestrictionsLPr(userId); 12383 changed = true; 12384 changedPackages.add(packageName); 12385 } 12386 } 12387 12388 if (changed && suspended) { 12389 killApplication(packageName, UserHandle.getUid(userId, appId), 12390 "suspending package"); 12391 } 12392 } 12393 } finally { 12394 Binder.restoreCallingIdentity(callingId); 12395 } 12396 12397 if (!changedPackages.isEmpty()) { 12398 sendPackagesSuspendedForUser(changedPackages.toArray( 12399 new String[changedPackages.size()]), userId, suspended); 12400 } 12401 12402 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12403 } 12404 12405 @Override 12406 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12407 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12408 true /* requireFullPermission */, false /* checkShell */, 12409 "isPackageSuspendedForUser for user " + userId); 12410 synchronized (mPackages) { 12411 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12412 if (pkgSetting == null) { 12413 throw new IllegalArgumentException("Unknown target package: " + packageName); 12414 } 12415 return pkgSetting.getSuspended(userId); 12416 } 12417 } 12418 12419 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12420 if (isPackageDeviceAdmin(packageName, userId)) { 12421 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12422 + "\": has an active device admin"); 12423 return false; 12424 } 12425 12426 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12427 if (packageName.equals(activeLauncherPackageName)) { 12428 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12429 + "\": contains the active launcher"); 12430 return false; 12431 } 12432 12433 if (packageName.equals(mRequiredInstallerPackage)) { 12434 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12435 + "\": required for package installation"); 12436 return false; 12437 } 12438 12439 if (packageName.equals(mRequiredUninstallerPackage)) { 12440 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12441 + "\": required for package uninstallation"); 12442 return false; 12443 } 12444 12445 if (packageName.equals(mRequiredVerifierPackage)) { 12446 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12447 + "\": required for package verification"); 12448 return false; 12449 } 12450 12451 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12452 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12453 + "\": is the default dialer"); 12454 return false; 12455 } 12456 12457 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12458 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12459 + "\": protected package"); 12460 return false; 12461 } 12462 12463 return true; 12464 } 12465 12466 private String getActiveLauncherPackageName(int userId) { 12467 Intent intent = new Intent(Intent.ACTION_MAIN); 12468 intent.addCategory(Intent.CATEGORY_HOME); 12469 ResolveInfo resolveInfo = resolveIntent( 12470 intent, 12471 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12472 PackageManager.MATCH_DEFAULT_ONLY, 12473 userId); 12474 12475 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12476 } 12477 12478 private String getDefaultDialerPackageName(int userId) { 12479 synchronized (mPackages) { 12480 return mSettings.getDefaultDialerPackageNameLPw(userId); 12481 } 12482 } 12483 12484 @Override 12485 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12486 mContext.enforceCallingOrSelfPermission( 12487 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12488 "Only package verification agents can verify applications"); 12489 12490 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12491 final PackageVerificationResponse response = new PackageVerificationResponse( 12492 verificationCode, Binder.getCallingUid()); 12493 msg.arg1 = id; 12494 msg.obj = response; 12495 mHandler.sendMessage(msg); 12496 } 12497 12498 @Override 12499 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12500 long millisecondsToDelay) { 12501 mContext.enforceCallingOrSelfPermission( 12502 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12503 "Only package verification agents can extend verification timeouts"); 12504 12505 final PackageVerificationState state = mPendingVerification.get(id); 12506 final PackageVerificationResponse response = new PackageVerificationResponse( 12507 verificationCodeAtTimeout, Binder.getCallingUid()); 12508 12509 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12510 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12511 } 12512 if (millisecondsToDelay < 0) { 12513 millisecondsToDelay = 0; 12514 } 12515 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12516 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12517 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12518 } 12519 12520 if ((state != null) && !state.timeoutExtended()) { 12521 state.extendTimeout(); 12522 12523 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12524 msg.arg1 = id; 12525 msg.obj = response; 12526 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12527 } 12528 } 12529 12530 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12531 int verificationCode, UserHandle user) { 12532 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12533 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12534 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12535 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12536 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12537 12538 mContext.sendBroadcastAsUser(intent, user, 12539 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12540 } 12541 12542 private ComponentName matchComponentForVerifier(String packageName, 12543 List<ResolveInfo> receivers) { 12544 ActivityInfo targetReceiver = null; 12545 12546 final int NR = receivers.size(); 12547 for (int i = 0; i < NR; i++) { 12548 final ResolveInfo info = receivers.get(i); 12549 if (info.activityInfo == null) { 12550 continue; 12551 } 12552 12553 if (packageName.equals(info.activityInfo.packageName)) { 12554 targetReceiver = info.activityInfo; 12555 break; 12556 } 12557 } 12558 12559 if (targetReceiver == null) { 12560 return null; 12561 } 12562 12563 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12564 } 12565 12566 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12567 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12568 if (pkgInfo.verifiers.length == 0) { 12569 return null; 12570 } 12571 12572 final int N = pkgInfo.verifiers.length; 12573 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12574 for (int i = 0; i < N; i++) { 12575 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12576 12577 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12578 receivers); 12579 if (comp == null) { 12580 continue; 12581 } 12582 12583 final int verifierUid = getUidForVerifier(verifierInfo); 12584 if (verifierUid == -1) { 12585 continue; 12586 } 12587 12588 if (DEBUG_VERIFY) { 12589 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12590 + " with the correct signature"); 12591 } 12592 sufficientVerifiers.add(comp); 12593 verificationState.addSufficientVerifier(verifierUid); 12594 } 12595 12596 return sufficientVerifiers; 12597 } 12598 12599 private int getUidForVerifier(VerifierInfo verifierInfo) { 12600 synchronized (mPackages) { 12601 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12602 if (pkg == null) { 12603 return -1; 12604 } else if (pkg.mSignatures.length != 1) { 12605 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12606 + " has more than one signature; ignoring"); 12607 return -1; 12608 } 12609 12610 /* 12611 * If the public key of the package's signature does not match 12612 * our expected public key, then this is a different package and 12613 * we should skip. 12614 */ 12615 12616 final byte[] expectedPublicKey; 12617 try { 12618 final Signature verifierSig = pkg.mSignatures[0]; 12619 final PublicKey publicKey = verifierSig.getPublicKey(); 12620 expectedPublicKey = publicKey.getEncoded(); 12621 } catch (CertificateException e) { 12622 return -1; 12623 } 12624 12625 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12626 12627 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12628 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12629 + " does not have the expected public key; ignoring"); 12630 return -1; 12631 } 12632 12633 return pkg.applicationInfo.uid; 12634 } 12635 } 12636 12637 @Override 12638 public void finishPackageInstall(int token, boolean didLaunch) { 12639 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12640 12641 if (DEBUG_INSTALL) { 12642 Slog.v(TAG, "BM finishing package install for " + token); 12643 } 12644 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12645 12646 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12647 mHandler.sendMessage(msg); 12648 } 12649 12650 /** 12651 * Get the verification agent timeout. 12652 * 12653 * @return verification timeout in milliseconds 12654 */ 12655 private long getVerificationTimeout() { 12656 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12657 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12658 DEFAULT_VERIFICATION_TIMEOUT); 12659 } 12660 12661 /** 12662 * Get the default verification agent response code. 12663 * 12664 * @return default verification response code 12665 */ 12666 private int getDefaultVerificationResponse() { 12667 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12668 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12669 DEFAULT_VERIFICATION_RESPONSE); 12670 } 12671 12672 /** 12673 * Check whether or not package verification has been enabled. 12674 * 12675 * @return true if verification should be performed 12676 */ 12677 private boolean isVerificationEnabled(int userId, int installFlags) { 12678 if (!DEFAULT_VERIFY_ENABLE) { 12679 return false; 12680 } 12681 // Ephemeral apps don't get the full verification treatment 12682 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12683 if (DEBUG_EPHEMERAL) { 12684 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12685 } 12686 return false; 12687 } 12688 12689 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12690 12691 // Check if installing from ADB 12692 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12693 // Do not run verification in a test harness environment 12694 if (ActivityManager.isRunningInTestHarness()) { 12695 return false; 12696 } 12697 if (ensureVerifyAppsEnabled) { 12698 return true; 12699 } 12700 // Check if the developer does not want package verification for ADB installs 12701 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12702 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12703 return false; 12704 } 12705 } 12706 12707 if (ensureVerifyAppsEnabled) { 12708 return true; 12709 } 12710 12711 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12712 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12713 } 12714 12715 @Override 12716 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12717 throws RemoteException { 12718 mContext.enforceCallingOrSelfPermission( 12719 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12720 "Only intentfilter verification agents can verify applications"); 12721 12722 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12723 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12724 Binder.getCallingUid(), verificationCode, failedDomains); 12725 msg.arg1 = id; 12726 msg.obj = response; 12727 mHandler.sendMessage(msg); 12728 } 12729 12730 @Override 12731 public int getIntentVerificationStatus(String packageName, int userId) { 12732 synchronized (mPackages) { 12733 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12734 } 12735 } 12736 12737 @Override 12738 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12739 mContext.enforceCallingOrSelfPermission( 12740 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12741 12742 boolean result = false; 12743 synchronized (mPackages) { 12744 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12745 } 12746 if (result) { 12747 scheduleWritePackageRestrictionsLocked(userId); 12748 } 12749 return result; 12750 } 12751 12752 @Override 12753 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12754 String packageName) { 12755 synchronized (mPackages) { 12756 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12757 } 12758 } 12759 12760 @Override 12761 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12762 if (TextUtils.isEmpty(packageName)) { 12763 return ParceledListSlice.emptyList(); 12764 } 12765 synchronized (mPackages) { 12766 PackageParser.Package pkg = mPackages.get(packageName); 12767 if (pkg == null || pkg.activities == null) { 12768 return ParceledListSlice.emptyList(); 12769 } 12770 final int count = pkg.activities.size(); 12771 ArrayList<IntentFilter> result = new ArrayList<>(); 12772 for (int n=0; n<count; n++) { 12773 PackageParser.Activity activity = pkg.activities.get(n); 12774 if (activity.intents != null && activity.intents.size() > 0) { 12775 result.addAll(activity.intents); 12776 } 12777 } 12778 return new ParceledListSlice<>(result); 12779 } 12780 } 12781 12782 @Override 12783 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12784 mContext.enforceCallingOrSelfPermission( 12785 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12786 12787 synchronized (mPackages) { 12788 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12789 if (packageName != null) { 12790 result |= updateIntentVerificationStatus(packageName, 12791 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12792 userId); 12793 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12794 packageName, userId); 12795 } 12796 return result; 12797 } 12798 } 12799 12800 @Override 12801 public String getDefaultBrowserPackageName(int userId) { 12802 synchronized (mPackages) { 12803 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12804 } 12805 } 12806 12807 /** 12808 * Get the "allow unknown sources" setting. 12809 * 12810 * @return the current "allow unknown sources" setting 12811 */ 12812 private int getUnknownSourcesSettings() { 12813 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12814 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12815 -1); 12816 } 12817 12818 @Override 12819 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12820 final int uid = Binder.getCallingUid(); 12821 // writer 12822 synchronized (mPackages) { 12823 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12824 if (targetPackageSetting == null) { 12825 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12826 } 12827 12828 PackageSetting installerPackageSetting; 12829 if (installerPackageName != null) { 12830 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12831 if (installerPackageSetting == null) { 12832 throw new IllegalArgumentException("Unknown installer package: " 12833 + installerPackageName); 12834 } 12835 } else { 12836 installerPackageSetting = null; 12837 } 12838 12839 Signature[] callerSignature; 12840 Object obj = mSettings.getUserIdLPr(uid); 12841 if (obj != null) { 12842 if (obj instanceof SharedUserSetting) { 12843 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12844 } else if (obj instanceof PackageSetting) { 12845 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12846 } else { 12847 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12848 } 12849 } else { 12850 throw new SecurityException("Unknown calling UID: " + uid); 12851 } 12852 12853 // Verify: can't set installerPackageName to a package that is 12854 // not signed with the same cert as the caller. 12855 if (installerPackageSetting != null) { 12856 if (compareSignatures(callerSignature, 12857 installerPackageSetting.signatures.mSignatures) 12858 != PackageManager.SIGNATURE_MATCH) { 12859 throw new SecurityException( 12860 "Caller does not have same cert as new installer package " 12861 + installerPackageName); 12862 } 12863 } 12864 12865 // Verify: if target already has an installer package, it must 12866 // be signed with the same cert as the caller. 12867 if (targetPackageSetting.installerPackageName != null) { 12868 PackageSetting setting = mSettings.mPackages.get( 12869 targetPackageSetting.installerPackageName); 12870 // If the currently set package isn't valid, then it's always 12871 // okay to change it. 12872 if (setting != null) { 12873 if (compareSignatures(callerSignature, 12874 setting.signatures.mSignatures) 12875 != PackageManager.SIGNATURE_MATCH) { 12876 throw new SecurityException( 12877 "Caller does not have same cert as old installer package " 12878 + targetPackageSetting.installerPackageName); 12879 } 12880 } 12881 } 12882 12883 // Okay! 12884 targetPackageSetting.installerPackageName = installerPackageName; 12885 if (installerPackageName != null) { 12886 mSettings.mInstallerPackages.add(installerPackageName); 12887 } 12888 scheduleWriteSettingsLocked(); 12889 } 12890 } 12891 12892 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12893 // Queue up an async operation since the package installation may take a little while. 12894 mHandler.post(new Runnable() { 12895 public void run() { 12896 mHandler.removeCallbacks(this); 12897 // Result object to be returned 12898 PackageInstalledInfo res = new PackageInstalledInfo(); 12899 res.setReturnCode(currentStatus); 12900 res.uid = -1; 12901 res.pkg = null; 12902 res.removedInfo = null; 12903 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12904 args.doPreInstall(res.returnCode); 12905 synchronized (mInstallLock) { 12906 installPackageTracedLI(args, res); 12907 } 12908 args.doPostInstall(res.returnCode, res.uid); 12909 } 12910 12911 // A restore should be performed at this point if (a) the install 12912 // succeeded, (b) the operation is not an update, and (c) the new 12913 // package has not opted out of backup participation. 12914 final boolean update = res.removedInfo != null 12915 && res.removedInfo.removedPackage != null; 12916 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12917 boolean doRestore = !update 12918 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12919 12920 // Set up the post-install work request bookkeeping. This will be used 12921 // and cleaned up by the post-install event handling regardless of whether 12922 // there's a restore pass performed. Token values are >= 1. 12923 int token; 12924 if (mNextInstallToken < 0) mNextInstallToken = 1; 12925 token = mNextInstallToken++; 12926 12927 PostInstallData data = new PostInstallData(args, res); 12928 mRunningInstalls.put(token, data); 12929 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12930 12931 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12932 // Pass responsibility to the Backup Manager. It will perform a 12933 // restore if appropriate, then pass responsibility back to the 12934 // Package Manager to run the post-install observer callbacks 12935 // and broadcasts. 12936 IBackupManager bm = IBackupManager.Stub.asInterface( 12937 ServiceManager.getService(Context.BACKUP_SERVICE)); 12938 if (bm != null) { 12939 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12940 + " to BM for possible restore"); 12941 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12942 try { 12943 // TODO: http://b/22388012 12944 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12945 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12946 } else { 12947 doRestore = false; 12948 } 12949 } catch (RemoteException e) { 12950 // can't happen; the backup manager is local 12951 } catch (Exception e) { 12952 Slog.e(TAG, "Exception trying to enqueue restore", e); 12953 doRestore = false; 12954 } 12955 } else { 12956 Slog.e(TAG, "Backup Manager not found!"); 12957 doRestore = false; 12958 } 12959 } 12960 12961 if (!doRestore) { 12962 // No restore possible, or the Backup Manager was mysteriously not 12963 // available -- just fire the post-install work request directly. 12964 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12965 12966 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12967 12968 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12969 mHandler.sendMessage(msg); 12970 } 12971 } 12972 }); 12973 } 12974 12975 /** 12976 * Callback from PackageSettings whenever an app is first transitioned out of the 12977 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12978 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12979 * here whether the app is the target of an ongoing install, and only send the 12980 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12981 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12982 * handling. 12983 */ 12984 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12985 // Serialize this with the rest of the install-process message chain. In the 12986 // restore-at-install case, this Runnable will necessarily run before the 12987 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12988 // are coherent. In the non-restore case, the app has already completed install 12989 // and been launched through some other means, so it is not in a problematic 12990 // state for observers to see the FIRST_LAUNCH signal. 12991 mHandler.post(new Runnable() { 12992 @Override 12993 public void run() { 12994 for (int i = 0; i < mRunningInstalls.size(); i++) { 12995 final PostInstallData data = mRunningInstalls.valueAt(i); 12996 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12997 continue; 12998 } 12999 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13000 // right package; but is it for the right user? 13001 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13002 if (userId == data.res.newUsers[uIndex]) { 13003 if (DEBUG_BACKUP) { 13004 Slog.i(TAG, "Package " + pkgName 13005 + " being restored so deferring FIRST_LAUNCH"); 13006 } 13007 return; 13008 } 13009 } 13010 } 13011 } 13012 // didn't find it, so not being restored 13013 if (DEBUG_BACKUP) { 13014 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13015 } 13016 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13017 } 13018 }); 13019 } 13020 13021 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13022 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13023 installerPkg, null, userIds); 13024 } 13025 13026 private abstract class HandlerParams { 13027 private static final int MAX_RETRIES = 4; 13028 13029 /** 13030 * Number of times startCopy() has been attempted and had a non-fatal 13031 * error. 13032 */ 13033 private int mRetries = 0; 13034 13035 /** User handle for the user requesting the information or installation. */ 13036 private final UserHandle mUser; 13037 String traceMethod; 13038 int traceCookie; 13039 13040 HandlerParams(UserHandle user) { 13041 mUser = user; 13042 } 13043 13044 UserHandle getUser() { 13045 return mUser; 13046 } 13047 13048 HandlerParams setTraceMethod(String traceMethod) { 13049 this.traceMethod = traceMethod; 13050 return this; 13051 } 13052 13053 HandlerParams setTraceCookie(int traceCookie) { 13054 this.traceCookie = traceCookie; 13055 return this; 13056 } 13057 13058 final boolean startCopy() { 13059 boolean res; 13060 try { 13061 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13062 13063 if (++mRetries > MAX_RETRIES) { 13064 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13065 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13066 handleServiceError(); 13067 return false; 13068 } else { 13069 handleStartCopy(); 13070 res = true; 13071 } 13072 } catch (RemoteException e) { 13073 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13074 mHandler.sendEmptyMessage(MCS_RECONNECT); 13075 res = false; 13076 } 13077 handleReturnCode(); 13078 return res; 13079 } 13080 13081 final void serviceError() { 13082 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13083 handleServiceError(); 13084 handleReturnCode(); 13085 } 13086 13087 abstract void handleStartCopy() throws RemoteException; 13088 abstract void handleServiceError(); 13089 abstract void handleReturnCode(); 13090 } 13091 13092 class MeasureParams extends HandlerParams { 13093 private final PackageStats mStats; 13094 private boolean mSuccess; 13095 13096 private final IPackageStatsObserver mObserver; 13097 13098 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 13099 super(new UserHandle(stats.userHandle)); 13100 mObserver = observer; 13101 mStats = stats; 13102 } 13103 13104 @Override 13105 public String toString() { 13106 return "MeasureParams{" 13107 + Integer.toHexString(System.identityHashCode(this)) 13108 + " " + mStats.packageName + "}"; 13109 } 13110 13111 @Override 13112 void handleStartCopy() throws RemoteException { 13113 synchronized (mInstallLock) { 13114 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 13115 } 13116 13117 if (mSuccess) { 13118 boolean mounted = false; 13119 try { 13120 final String status = Environment.getExternalStorageState(); 13121 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13122 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13123 } catch (Exception e) { 13124 } 13125 13126 if (mounted) { 13127 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13128 13129 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13130 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13131 13132 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13133 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13134 13135 // Always subtract cache size, since it's a subdirectory 13136 mStats.externalDataSize -= mStats.externalCacheSize; 13137 13138 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13139 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13140 13141 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13142 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13143 } 13144 } 13145 } 13146 13147 @Override 13148 void handleReturnCode() { 13149 if (mObserver != null) { 13150 try { 13151 mObserver.onGetStatsCompleted(mStats, mSuccess); 13152 } catch (RemoteException e) { 13153 Slog.i(TAG, "Observer no longer exists."); 13154 } 13155 } 13156 } 13157 13158 @Override 13159 void handleServiceError() { 13160 Slog.e(TAG, "Could not measure application " + mStats.packageName 13161 + " external storage"); 13162 } 13163 } 13164 13165 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13166 throws RemoteException { 13167 long result = 0; 13168 for (File path : paths) { 13169 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13170 } 13171 return result; 13172 } 13173 13174 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13175 for (File path : paths) { 13176 try { 13177 mcs.clearDirectory(path.getAbsolutePath()); 13178 } catch (RemoteException e) { 13179 } 13180 } 13181 } 13182 13183 static class OriginInfo { 13184 /** 13185 * Location where install is coming from, before it has been 13186 * copied/renamed into place. This could be a single monolithic APK 13187 * file, or a cluster directory. This location may be untrusted. 13188 */ 13189 final File file; 13190 final String cid; 13191 13192 /** 13193 * Flag indicating that {@link #file} or {@link #cid} has already been 13194 * staged, meaning downstream users don't need to defensively copy the 13195 * contents. 13196 */ 13197 final boolean staged; 13198 13199 /** 13200 * Flag indicating that {@link #file} or {@link #cid} is an already 13201 * installed app that is being moved. 13202 */ 13203 final boolean existing; 13204 13205 final String resolvedPath; 13206 final File resolvedFile; 13207 13208 static OriginInfo fromNothing() { 13209 return new OriginInfo(null, null, false, false); 13210 } 13211 13212 static OriginInfo fromUntrustedFile(File file) { 13213 return new OriginInfo(file, null, false, false); 13214 } 13215 13216 static OriginInfo fromExistingFile(File file) { 13217 return new OriginInfo(file, null, false, true); 13218 } 13219 13220 static OriginInfo fromStagedFile(File file) { 13221 return new OriginInfo(file, null, true, false); 13222 } 13223 13224 static OriginInfo fromStagedContainer(String cid) { 13225 return new OriginInfo(null, cid, true, false); 13226 } 13227 13228 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13229 this.file = file; 13230 this.cid = cid; 13231 this.staged = staged; 13232 this.existing = existing; 13233 13234 if (cid != null) { 13235 resolvedPath = PackageHelper.getSdDir(cid); 13236 resolvedFile = new File(resolvedPath); 13237 } else if (file != null) { 13238 resolvedPath = file.getAbsolutePath(); 13239 resolvedFile = file; 13240 } else { 13241 resolvedPath = null; 13242 resolvedFile = null; 13243 } 13244 } 13245 } 13246 13247 static class MoveInfo { 13248 final int moveId; 13249 final String fromUuid; 13250 final String toUuid; 13251 final String packageName; 13252 final String dataAppName; 13253 final int appId; 13254 final String seinfo; 13255 final int targetSdkVersion; 13256 13257 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13258 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13259 this.moveId = moveId; 13260 this.fromUuid = fromUuid; 13261 this.toUuid = toUuid; 13262 this.packageName = packageName; 13263 this.dataAppName = dataAppName; 13264 this.appId = appId; 13265 this.seinfo = seinfo; 13266 this.targetSdkVersion = targetSdkVersion; 13267 } 13268 } 13269 13270 static class VerificationInfo { 13271 /** A constant used to indicate that a uid value is not present. */ 13272 public static final int NO_UID = -1; 13273 13274 /** URI referencing where the package was downloaded from. */ 13275 final Uri originatingUri; 13276 13277 /** HTTP referrer URI associated with the originatingURI. */ 13278 final Uri referrer; 13279 13280 /** UID of the application that the install request originated from. */ 13281 final int originatingUid; 13282 13283 /** UID of application requesting the install */ 13284 final int installerUid; 13285 13286 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13287 this.originatingUri = originatingUri; 13288 this.referrer = referrer; 13289 this.originatingUid = originatingUid; 13290 this.installerUid = installerUid; 13291 } 13292 } 13293 13294 class InstallParams extends HandlerParams { 13295 final OriginInfo origin; 13296 final MoveInfo move; 13297 final IPackageInstallObserver2 observer; 13298 int installFlags; 13299 final String installerPackageName; 13300 final String volumeUuid; 13301 private InstallArgs mArgs; 13302 private int mRet; 13303 final String packageAbiOverride; 13304 final String[] grantedRuntimePermissions; 13305 final VerificationInfo verificationInfo; 13306 final Certificate[][] certificates; 13307 13308 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13309 int installFlags, String installerPackageName, String volumeUuid, 13310 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13311 String[] grantedPermissions, Certificate[][] certificates) { 13312 super(user); 13313 this.origin = origin; 13314 this.move = move; 13315 this.observer = observer; 13316 this.installFlags = installFlags; 13317 this.installerPackageName = installerPackageName; 13318 this.volumeUuid = volumeUuid; 13319 this.verificationInfo = verificationInfo; 13320 this.packageAbiOverride = packageAbiOverride; 13321 this.grantedRuntimePermissions = grantedPermissions; 13322 this.certificates = certificates; 13323 } 13324 13325 @Override 13326 public String toString() { 13327 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13328 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13329 } 13330 13331 private int installLocationPolicy(PackageInfoLite pkgLite) { 13332 String packageName = pkgLite.packageName; 13333 int installLocation = pkgLite.installLocation; 13334 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13335 // reader 13336 synchronized (mPackages) { 13337 // Currently installed package which the new package is attempting to replace or 13338 // null if no such package is installed. 13339 PackageParser.Package installedPkg = mPackages.get(packageName); 13340 // Package which currently owns the data which the new package will own if installed. 13341 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13342 // will be null whereas dataOwnerPkg will contain information about the package 13343 // which was uninstalled while keeping its data. 13344 PackageParser.Package dataOwnerPkg = installedPkg; 13345 if (dataOwnerPkg == null) { 13346 PackageSetting ps = mSettings.mPackages.get(packageName); 13347 if (ps != null) { 13348 dataOwnerPkg = ps.pkg; 13349 } 13350 } 13351 13352 if (dataOwnerPkg != null) { 13353 // If installed, the package will get access to data left on the device by its 13354 // predecessor. As a security measure, this is permited only if this is not a 13355 // version downgrade or if the predecessor package is marked as debuggable and 13356 // a downgrade is explicitly requested. 13357 // 13358 // On debuggable platform builds, downgrades are permitted even for 13359 // non-debuggable packages to make testing easier. Debuggable platform builds do 13360 // not offer security guarantees and thus it's OK to disable some security 13361 // mechanisms to make debugging/testing easier on those builds. However, even on 13362 // debuggable builds downgrades of packages are permitted only if requested via 13363 // installFlags. This is because we aim to keep the behavior of debuggable 13364 // platform builds as close as possible to the behavior of non-debuggable 13365 // platform builds. 13366 final boolean downgradeRequested = 13367 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13368 final boolean packageDebuggable = 13369 (dataOwnerPkg.applicationInfo.flags 13370 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13371 final boolean downgradePermitted = 13372 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13373 if (!downgradePermitted) { 13374 try { 13375 checkDowngrade(dataOwnerPkg, pkgLite); 13376 } catch (PackageManagerException e) { 13377 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13378 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13379 } 13380 } 13381 } 13382 13383 if (installedPkg != null) { 13384 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13385 // Check for updated system application. 13386 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13387 if (onSd) { 13388 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13389 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13390 } 13391 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13392 } else { 13393 if (onSd) { 13394 // Install flag overrides everything. 13395 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13396 } 13397 // If current upgrade specifies particular preference 13398 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13399 // Application explicitly specified internal. 13400 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13401 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13402 // App explictly prefers external. Let policy decide 13403 } else { 13404 // Prefer previous location 13405 if (isExternal(installedPkg)) { 13406 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13407 } 13408 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13409 } 13410 } 13411 } else { 13412 // Invalid install. Return error code 13413 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13414 } 13415 } 13416 } 13417 // All the special cases have been taken care of. 13418 // Return result based on recommended install location. 13419 if (onSd) { 13420 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13421 } 13422 return pkgLite.recommendedInstallLocation; 13423 } 13424 13425 /* 13426 * Invoke remote method to get package information and install 13427 * location values. Override install location based on default 13428 * policy if needed and then create install arguments based 13429 * on the install location. 13430 */ 13431 public void handleStartCopy() throws RemoteException { 13432 int ret = PackageManager.INSTALL_SUCCEEDED; 13433 13434 // If we're already staged, we've firmly committed to an install location 13435 if (origin.staged) { 13436 if (origin.file != null) { 13437 installFlags |= PackageManager.INSTALL_INTERNAL; 13438 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13439 } else if (origin.cid != null) { 13440 installFlags |= PackageManager.INSTALL_EXTERNAL; 13441 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13442 } else { 13443 throw new IllegalStateException("Invalid stage location"); 13444 } 13445 } 13446 13447 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13448 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13449 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13450 PackageInfoLite pkgLite = null; 13451 13452 if (onInt && onSd) { 13453 // Check if both bits are set. 13454 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13455 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13456 } else if (onSd && ephemeral) { 13457 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13458 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13459 } else { 13460 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13461 packageAbiOverride); 13462 13463 if (DEBUG_EPHEMERAL && ephemeral) { 13464 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13465 } 13466 13467 /* 13468 * If we have too little free space, try to free cache 13469 * before giving up. 13470 */ 13471 if (!origin.staged && pkgLite.recommendedInstallLocation 13472 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13473 // TODO: focus freeing disk space on the target device 13474 final StorageManager storage = StorageManager.from(mContext); 13475 final long lowThreshold = storage.getStorageLowBytes( 13476 Environment.getDataDirectory()); 13477 13478 final long sizeBytes = mContainerService.calculateInstalledSize( 13479 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13480 13481 try { 13482 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13483 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13484 installFlags, packageAbiOverride); 13485 } catch (InstallerException e) { 13486 Slog.w(TAG, "Failed to free cache", e); 13487 } 13488 13489 /* 13490 * The cache free must have deleted the file we 13491 * downloaded to install. 13492 * 13493 * TODO: fix the "freeCache" call to not delete 13494 * the file we care about. 13495 */ 13496 if (pkgLite.recommendedInstallLocation 13497 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13498 pkgLite.recommendedInstallLocation 13499 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13500 } 13501 } 13502 } 13503 13504 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13505 int loc = pkgLite.recommendedInstallLocation; 13506 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13507 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13508 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13509 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13510 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13511 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13512 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13513 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13514 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13515 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13516 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13517 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13518 } else { 13519 // Override with defaults if needed. 13520 loc = installLocationPolicy(pkgLite); 13521 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13522 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13523 } else if (!onSd && !onInt) { 13524 // Override install location with flags 13525 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13526 // Set the flag to install on external media. 13527 installFlags |= PackageManager.INSTALL_EXTERNAL; 13528 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13529 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13530 if (DEBUG_EPHEMERAL) { 13531 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13532 } 13533 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13534 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13535 |PackageManager.INSTALL_INTERNAL); 13536 } else { 13537 // Make sure the flag for installing on external 13538 // media is unset 13539 installFlags |= PackageManager.INSTALL_INTERNAL; 13540 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13541 } 13542 } 13543 } 13544 } 13545 13546 final InstallArgs args = createInstallArgs(this); 13547 mArgs = args; 13548 13549 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13550 // TODO: http://b/22976637 13551 // Apps installed for "all" users use the device owner to verify the app 13552 UserHandle verifierUser = getUser(); 13553 if (verifierUser == UserHandle.ALL) { 13554 verifierUser = UserHandle.SYSTEM; 13555 } 13556 13557 /* 13558 * Determine if we have any installed package verifiers. If we 13559 * do, then we'll defer to them to verify the packages. 13560 */ 13561 final int requiredUid = mRequiredVerifierPackage == null ? -1 13562 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13563 verifierUser.getIdentifier()); 13564 if (!origin.existing && requiredUid != -1 13565 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13566 final Intent verification = new Intent( 13567 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13568 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13569 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13570 PACKAGE_MIME_TYPE); 13571 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13572 13573 // Query all live verifiers based on current user state 13574 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13575 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13576 13577 if (DEBUG_VERIFY) { 13578 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13579 + verification.toString() + " with " + pkgLite.verifiers.length 13580 + " optional verifiers"); 13581 } 13582 13583 final int verificationId = mPendingVerificationToken++; 13584 13585 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13586 13587 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13588 installerPackageName); 13589 13590 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13591 installFlags); 13592 13593 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13594 pkgLite.packageName); 13595 13596 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13597 pkgLite.versionCode); 13598 13599 if (verificationInfo != null) { 13600 if (verificationInfo.originatingUri != null) { 13601 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13602 verificationInfo.originatingUri); 13603 } 13604 if (verificationInfo.referrer != null) { 13605 verification.putExtra(Intent.EXTRA_REFERRER, 13606 verificationInfo.referrer); 13607 } 13608 if (verificationInfo.originatingUid >= 0) { 13609 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13610 verificationInfo.originatingUid); 13611 } 13612 if (verificationInfo.installerUid >= 0) { 13613 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13614 verificationInfo.installerUid); 13615 } 13616 } 13617 13618 final PackageVerificationState verificationState = new PackageVerificationState( 13619 requiredUid, args); 13620 13621 mPendingVerification.append(verificationId, verificationState); 13622 13623 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13624 receivers, verificationState); 13625 13626 /* 13627 * If any sufficient verifiers were listed in the package 13628 * manifest, attempt to ask them. 13629 */ 13630 if (sufficientVerifiers != null) { 13631 final int N = sufficientVerifiers.size(); 13632 if (N == 0) { 13633 Slog.i(TAG, "Additional verifiers required, but none installed."); 13634 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13635 } else { 13636 for (int i = 0; i < N; i++) { 13637 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13638 13639 final Intent sufficientIntent = new Intent(verification); 13640 sufficientIntent.setComponent(verifierComponent); 13641 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13642 } 13643 } 13644 } 13645 13646 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13647 mRequiredVerifierPackage, receivers); 13648 if (ret == PackageManager.INSTALL_SUCCEEDED 13649 && mRequiredVerifierPackage != null) { 13650 Trace.asyncTraceBegin( 13651 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13652 /* 13653 * Send the intent to the required verification agent, 13654 * but only start the verification timeout after the 13655 * target BroadcastReceivers have run. 13656 */ 13657 verification.setComponent(requiredVerifierComponent); 13658 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13659 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13660 new BroadcastReceiver() { 13661 @Override 13662 public void onReceive(Context context, Intent intent) { 13663 final Message msg = mHandler 13664 .obtainMessage(CHECK_PENDING_VERIFICATION); 13665 msg.arg1 = verificationId; 13666 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13667 } 13668 }, null, 0, null, null); 13669 13670 /* 13671 * We don't want the copy to proceed until verification 13672 * succeeds, so null out this field. 13673 */ 13674 mArgs = null; 13675 } 13676 } else { 13677 /* 13678 * No package verification is enabled, so immediately start 13679 * the remote call to initiate copy using temporary file. 13680 */ 13681 ret = args.copyApk(mContainerService, true); 13682 } 13683 } 13684 13685 mRet = ret; 13686 } 13687 13688 @Override 13689 void handleReturnCode() { 13690 // If mArgs is null, then MCS couldn't be reached. When it 13691 // reconnects, it will try again to install. At that point, this 13692 // will succeed. 13693 if (mArgs != null) { 13694 processPendingInstall(mArgs, mRet); 13695 } 13696 } 13697 13698 @Override 13699 void handleServiceError() { 13700 mArgs = createInstallArgs(this); 13701 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13702 } 13703 13704 public boolean isForwardLocked() { 13705 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13706 } 13707 } 13708 13709 /** 13710 * Used during creation of InstallArgs 13711 * 13712 * @param installFlags package installation flags 13713 * @return true if should be installed on external storage 13714 */ 13715 private static boolean installOnExternalAsec(int installFlags) { 13716 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13717 return false; 13718 } 13719 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13720 return true; 13721 } 13722 return false; 13723 } 13724 13725 /** 13726 * Used during creation of InstallArgs 13727 * 13728 * @param installFlags package installation flags 13729 * @return true if should be installed as forward locked 13730 */ 13731 private static boolean installForwardLocked(int installFlags) { 13732 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13733 } 13734 13735 private InstallArgs createInstallArgs(InstallParams params) { 13736 if (params.move != null) { 13737 return new MoveInstallArgs(params); 13738 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13739 return new AsecInstallArgs(params); 13740 } else { 13741 return new FileInstallArgs(params); 13742 } 13743 } 13744 13745 /** 13746 * Create args that describe an existing installed package. Typically used 13747 * when cleaning up old installs, or used as a move source. 13748 */ 13749 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13750 String resourcePath, String[] instructionSets) { 13751 final boolean isInAsec; 13752 if (installOnExternalAsec(installFlags)) { 13753 /* Apps on SD card are always in ASEC containers. */ 13754 isInAsec = true; 13755 } else if (installForwardLocked(installFlags) 13756 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13757 /* 13758 * Forward-locked apps are only in ASEC containers if they're the 13759 * new style 13760 */ 13761 isInAsec = true; 13762 } else { 13763 isInAsec = false; 13764 } 13765 13766 if (isInAsec) { 13767 return new AsecInstallArgs(codePath, instructionSets, 13768 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13769 } else { 13770 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13771 } 13772 } 13773 13774 static abstract class InstallArgs { 13775 /** @see InstallParams#origin */ 13776 final OriginInfo origin; 13777 /** @see InstallParams#move */ 13778 final MoveInfo move; 13779 13780 final IPackageInstallObserver2 observer; 13781 // Always refers to PackageManager flags only 13782 final int installFlags; 13783 final String installerPackageName; 13784 final String volumeUuid; 13785 final UserHandle user; 13786 final String abiOverride; 13787 final String[] installGrantPermissions; 13788 /** If non-null, drop an async trace when the install completes */ 13789 final String traceMethod; 13790 final int traceCookie; 13791 final Certificate[][] certificates; 13792 13793 // The list of instruction sets supported by this app. This is currently 13794 // only used during the rmdex() phase to clean up resources. We can get rid of this 13795 // if we move dex files under the common app path. 13796 /* nullable */ String[] instructionSets; 13797 13798 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13799 int installFlags, String installerPackageName, String volumeUuid, 13800 UserHandle user, String[] instructionSets, 13801 String abiOverride, String[] installGrantPermissions, 13802 String traceMethod, int traceCookie, Certificate[][] certificates) { 13803 this.origin = origin; 13804 this.move = move; 13805 this.installFlags = installFlags; 13806 this.observer = observer; 13807 this.installerPackageName = installerPackageName; 13808 this.volumeUuid = volumeUuid; 13809 this.user = user; 13810 this.instructionSets = instructionSets; 13811 this.abiOverride = abiOverride; 13812 this.installGrantPermissions = installGrantPermissions; 13813 this.traceMethod = traceMethod; 13814 this.traceCookie = traceCookie; 13815 this.certificates = certificates; 13816 } 13817 13818 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13819 abstract int doPreInstall(int status); 13820 13821 /** 13822 * Rename package into final resting place. All paths on the given 13823 * scanned package should be updated to reflect the rename. 13824 */ 13825 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13826 abstract int doPostInstall(int status, int uid); 13827 13828 /** @see PackageSettingBase#codePathString */ 13829 abstract String getCodePath(); 13830 /** @see PackageSettingBase#resourcePathString */ 13831 abstract String getResourcePath(); 13832 13833 // Need installer lock especially for dex file removal. 13834 abstract void cleanUpResourcesLI(); 13835 abstract boolean doPostDeleteLI(boolean delete); 13836 13837 /** 13838 * Called before the source arguments are copied. This is used mostly 13839 * for MoveParams when it needs to read the source file to put it in the 13840 * destination. 13841 */ 13842 int doPreCopy() { 13843 return PackageManager.INSTALL_SUCCEEDED; 13844 } 13845 13846 /** 13847 * Called after the source arguments are copied. This is used mostly for 13848 * MoveParams when it needs to read the source file to put it in the 13849 * destination. 13850 */ 13851 int doPostCopy(int uid) { 13852 return PackageManager.INSTALL_SUCCEEDED; 13853 } 13854 13855 protected boolean isFwdLocked() { 13856 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13857 } 13858 13859 protected boolean isExternalAsec() { 13860 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13861 } 13862 13863 protected boolean isEphemeral() { 13864 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13865 } 13866 13867 UserHandle getUser() { 13868 return user; 13869 } 13870 } 13871 13872 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13873 if (!allCodePaths.isEmpty()) { 13874 if (instructionSets == null) { 13875 throw new IllegalStateException("instructionSet == null"); 13876 } 13877 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13878 for (String codePath : allCodePaths) { 13879 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13880 try { 13881 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13882 } catch (InstallerException ignored) { 13883 } 13884 } 13885 } 13886 } 13887 } 13888 13889 /** 13890 * Logic to handle installation of non-ASEC applications, including copying 13891 * and renaming logic. 13892 */ 13893 class FileInstallArgs extends InstallArgs { 13894 private File codeFile; 13895 private File resourceFile; 13896 13897 // Example topology: 13898 // /data/app/com.example/base.apk 13899 // /data/app/com.example/split_foo.apk 13900 // /data/app/com.example/lib/arm/libfoo.so 13901 // /data/app/com.example/lib/arm64/libfoo.so 13902 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13903 13904 /** New install */ 13905 FileInstallArgs(InstallParams params) { 13906 super(params.origin, params.move, params.observer, params.installFlags, 13907 params.installerPackageName, params.volumeUuid, 13908 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13909 params.grantedRuntimePermissions, 13910 params.traceMethod, params.traceCookie, params.certificates); 13911 if (isFwdLocked()) { 13912 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13913 } 13914 } 13915 13916 /** Existing install */ 13917 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13918 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13919 null, null, null, 0, null /*certificates*/); 13920 this.codeFile = (codePath != null) ? new File(codePath) : null; 13921 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13922 } 13923 13924 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13926 try { 13927 return doCopyApk(imcs, temp); 13928 } finally { 13929 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13930 } 13931 } 13932 13933 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13934 if (origin.staged) { 13935 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13936 codeFile = origin.file; 13937 resourceFile = origin.file; 13938 return PackageManager.INSTALL_SUCCEEDED; 13939 } 13940 13941 try { 13942 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13943 final File tempDir = 13944 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13945 codeFile = tempDir; 13946 resourceFile = tempDir; 13947 } catch (IOException e) { 13948 Slog.w(TAG, "Failed to create copy file: " + e); 13949 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13950 } 13951 13952 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13953 @Override 13954 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13955 if (!FileUtils.isValidExtFilename(name)) { 13956 throw new IllegalArgumentException("Invalid filename: " + name); 13957 } 13958 try { 13959 final File file = new File(codeFile, name); 13960 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13961 O_RDWR | O_CREAT, 0644); 13962 Os.chmod(file.getAbsolutePath(), 0644); 13963 return new ParcelFileDescriptor(fd); 13964 } catch (ErrnoException e) { 13965 throw new RemoteException("Failed to open: " + e.getMessage()); 13966 } 13967 } 13968 }; 13969 13970 int ret = PackageManager.INSTALL_SUCCEEDED; 13971 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13972 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13973 Slog.e(TAG, "Failed to copy package"); 13974 return ret; 13975 } 13976 13977 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13978 NativeLibraryHelper.Handle handle = null; 13979 try { 13980 handle = NativeLibraryHelper.Handle.create(codeFile); 13981 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13982 abiOverride); 13983 } catch (IOException e) { 13984 Slog.e(TAG, "Copying native libraries failed", e); 13985 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13986 } finally { 13987 IoUtils.closeQuietly(handle); 13988 } 13989 13990 return ret; 13991 } 13992 13993 int doPreInstall(int status) { 13994 if (status != PackageManager.INSTALL_SUCCEEDED) { 13995 cleanUp(); 13996 } 13997 return status; 13998 } 13999 14000 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14001 if (status != PackageManager.INSTALL_SUCCEEDED) { 14002 cleanUp(); 14003 return false; 14004 } 14005 14006 final File targetDir = codeFile.getParentFile(); 14007 final File beforeCodeFile = codeFile; 14008 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14009 14010 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14011 try { 14012 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14013 } catch (ErrnoException e) { 14014 Slog.w(TAG, "Failed to rename", e); 14015 return false; 14016 } 14017 14018 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14019 Slog.w(TAG, "Failed to restorecon"); 14020 return false; 14021 } 14022 14023 // Reflect the rename internally 14024 codeFile = afterCodeFile; 14025 resourceFile = afterCodeFile; 14026 14027 // Reflect the rename in scanned details 14028 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14029 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14030 afterCodeFile, pkg.baseCodePath)); 14031 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14032 afterCodeFile, pkg.splitCodePaths)); 14033 14034 // Reflect the rename in app info 14035 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14036 pkg.setApplicationInfoCodePath(pkg.codePath); 14037 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14038 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14039 pkg.setApplicationInfoResourcePath(pkg.codePath); 14040 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14041 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14042 14043 return true; 14044 } 14045 14046 int doPostInstall(int status, int uid) { 14047 if (status != PackageManager.INSTALL_SUCCEEDED) { 14048 cleanUp(); 14049 } 14050 return status; 14051 } 14052 14053 @Override 14054 String getCodePath() { 14055 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14056 } 14057 14058 @Override 14059 String getResourcePath() { 14060 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14061 } 14062 14063 private boolean cleanUp() { 14064 if (codeFile == null || !codeFile.exists()) { 14065 return false; 14066 } 14067 14068 removeCodePathLI(codeFile); 14069 14070 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14071 resourceFile.delete(); 14072 } 14073 14074 return true; 14075 } 14076 14077 void cleanUpResourcesLI() { 14078 // Try enumerating all code paths before deleting 14079 List<String> allCodePaths = Collections.EMPTY_LIST; 14080 if (codeFile != null && codeFile.exists()) { 14081 try { 14082 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14083 allCodePaths = pkg.getAllCodePaths(); 14084 } catch (PackageParserException e) { 14085 // Ignored; we tried our best 14086 } 14087 } 14088 14089 cleanUp(); 14090 removeDexFiles(allCodePaths, instructionSets); 14091 } 14092 14093 boolean doPostDeleteLI(boolean delete) { 14094 // XXX err, shouldn't we respect the delete flag? 14095 cleanUpResourcesLI(); 14096 return true; 14097 } 14098 } 14099 14100 private boolean isAsecExternal(String cid) { 14101 final String asecPath = PackageHelper.getSdFilesystem(cid); 14102 return !asecPath.startsWith(mAsecInternalPath); 14103 } 14104 14105 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 14106 PackageManagerException { 14107 if (copyRet < 0) { 14108 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 14109 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 14110 throw new PackageManagerException(copyRet, message); 14111 } 14112 } 14113 } 14114 14115 /** 14116 * Extract the StorageManagerService "container ID" from the full code path of an 14117 * .apk. 14118 */ 14119 static String cidFromCodePath(String fullCodePath) { 14120 int eidx = fullCodePath.lastIndexOf("/"); 14121 String subStr1 = fullCodePath.substring(0, eidx); 14122 int sidx = subStr1.lastIndexOf("/"); 14123 return subStr1.substring(sidx+1, eidx); 14124 } 14125 14126 /** 14127 * Logic to handle installation of ASEC applications, including copying and 14128 * renaming logic. 14129 */ 14130 class AsecInstallArgs extends InstallArgs { 14131 static final String RES_FILE_NAME = "pkg.apk"; 14132 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14133 14134 String cid; 14135 String packagePath; 14136 String resourcePath; 14137 14138 /** New install */ 14139 AsecInstallArgs(InstallParams params) { 14140 super(params.origin, params.move, params.observer, params.installFlags, 14141 params.installerPackageName, params.volumeUuid, 14142 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14143 params.grantedRuntimePermissions, 14144 params.traceMethod, params.traceCookie, params.certificates); 14145 } 14146 14147 /** Existing install */ 14148 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14149 boolean isExternal, boolean isForwardLocked) { 14150 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14151 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14152 instructionSets, null, null, null, 0, null /*certificates*/); 14153 // Hackily pretend we're still looking at a full code path 14154 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14155 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14156 } 14157 14158 // Extract cid from fullCodePath 14159 int eidx = fullCodePath.lastIndexOf("/"); 14160 String subStr1 = fullCodePath.substring(0, eidx); 14161 int sidx = subStr1.lastIndexOf("/"); 14162 cid = subStr1.substring(sidx+1, eidx); 14163 setMountPath(subStr1); 14164 } 14165 14166 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14167 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14168 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14169 instructionSets, null, null, null, 0, null /*certificates*/); 14170 this.cid = cid; 14171 setMountPath(PackageHelper.getSdDir(cid)); 14172 } 14173 14174 void createCopyFile() { 14175 cid = mInstallerService.allocateExternalStageCidLegacy(); 14176 } 14177 14178 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14179 if (origin.staged && origin.cid != null) { 14180 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14181 cid = origin.cid; 14182 setMountPath(PackageHelper.getSdDir(cid)); 14183 return PackageManager.INSTALL_SUCCEEDED; 14184 } 14185 14186 if (temp) { 14187 createCopyFile(); 14188 } else { 14189 /* 14190 * Pre-emptively destroy the container since it's destroyed if 14191 * copying fails due to it existing anyway. 14192 */ 14193 PackageHelper.destroySdDir(cid); 14194 } 14195 14196 final String newMountPath = imcs.copyPackageToContainer( 14197 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14198 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14199 14200 if (newMountPath != null) { 14201 setMountPath(newMountPath); 14202 return PackageManager.INSTALL_SUCCEEDED; 14203 } else { 14204 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14205 } 14206 } 14207 14208 @Override 14209 String getCodePath() { 14210 return packagePath; 14211 } 14212 14213 @Override 14214 String getResourcePath() { 14215 return resourcePath; 14216 } 14217 14218 int doPreInstall(int status) { 14219 if (status != PackageManager.INSTALL_SUCCEEDED) { 14220 // Destroy container 14221 PackageHelper.destroySdDir(cid); 14222 } else { 14223 boolean mounted = PackageHelper.isContainerMounted(cid); 14224 if (!mounted) { 14225 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14226 Process.SYSTEM_UID); 14227 if (newMountPath != null) { 14228 setMountPath(newMountPath); 14229 } else { 14230 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14231 } 14232 } 14233 } 14234 return status; 14235 } 14236 14237 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14238 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14239 String newMountPath = null; 14240 if (PackageHelper.isContainerMounted(cid)) { 14241 // Unmount the container 14242 if (!PackageHelper.unMountSdDir(cid)) { 14243 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14244 return false; 14245 } 14246 } 14247 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14248 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14249 " which might be stale. Will try to clean up."); 14250 // Clean up the stale container and proceed to recreate. 14251 if (!PackageHelper.destroySdDir(newCacheId)) { 14252 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14253 return false; 14254 } 14255 // Successfully cleaned up stale container. Try to rename again. 14256 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14257 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14258 + " inspite of cleaning it up."); 14259 return false; 14260 } 14261 } 14262 if (!PackageHelper.isContainerMounted(newCacheId)) { 14263 Slog.w(TAG, "Mounting container " + newCacheId); 14264 newMountPath = PackageHelper.mountSdDir(newCacheId, 14265 getEncryptKey(), Process.SYSTEM_UID); 14266 } else { 14267 newMountPath = PackageHelper.getSdDir(newCacheId); 14268 } 14269 if (newMountPath == null) { 14270 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14271 return false; 14272 } 14273 Log.i(TAG, "Succesfully renamed " + cid + 14274 " to " + newCacheId + 14275 " at new path: " + newMountPath); 14276 cid = newCacheId; 14277 14278 final File beforeCodeFile = new File(packagePath); 14279 setMountPath(newMountPath); 14280 final File afterCodeFile = new File(packagePath); 14281 14282 // Reflect the rename in scanned details 14283 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14284 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14285 afterCodeFile, pkg.baseCodePath)); 14286 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14287 afterCodeFile, pkg.splitCodePaths)); 14288 14289 // Reflect the rename in app info 14290 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14291 pkg.setApplicationInfoCodePath(pkg.codePath); 14292 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14293 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14294 pkg.setApplicationInfoResourcePath(pkg.codePath); 14295 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14296 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14297 14298 return true; 14299 } 14300 14301 private void setMountPath(String mountPath) { 14302 final File mountFile = new File(mountPath); 14303 14304 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14305 if (monolithicFile.exists()) { 14306 packagePath = monolithicFile.getAbsolutePath(); 14307 if (isFwdLocked()) { 14308 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14309 } else { 14310 resourcePath = packagePath; 14311 } 14312 } else { 14313 packagePath = mountFile.getAbsolutePath(); 14314 resourcePath = packagePath; 14315 } 14316 } 14317 14318 int doPostInstall(int status, int uid) { 14319 if (status != PackageManager.INSTALL_SUCCEEDED) { 14320 cleanUp(); 14321 } else { 14322 final int groupOwner; 14323 final String protectedFile; 14324 if (isFwdLocked()) { 14325 groupOwner = UserHandle.getSharedAppGid(uid); 14326 protectedFile = RES_FILE_NAME; 14327 } else { 14328 groupOwner = -1; 14329 protectedFile = null; 14330 } 14331 14332 if (uid < Process.FIRST_APPLICATION_UID 14333 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14334 Slog.e(TAG, "Failed to finalize " + cid); 14335 PackageHelper.destroySdDir(cid); 14336 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14337 } 14338 14339 boolean mounted = PackageHelper.isContainerMounted(cid); 14340 if (!mounted) { 14341 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14342 } 14343 } 14344 return status; 14345 } 14346 14347 private void cleanUp() { 14348 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14349 14350 // Destroy secure container 14351 PackageHelper.destroySdDir(cid); 14352 } 14353 14354 private List<String> getAllCodePaths() { 14355 final File codeFile = new File(getCodePath()); 14356 if (codeFile != null && codeFile.exists()) { 14357 try { 14358 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14359 return pkg.getAllCodePaths(); 14360 } catch (PackageParserException e) { 14361 // Ignored; we tried our best 14362 } 14363 } 14364 return Collections.EMPTY_LIST; 14365 } 14366 14367 void cleanUpResourcesLI() { 14368 // Enumerate all code paths before deleting 14369 cleanUpResourcesLI(getAllCodePaths()); 14370 } 14371 14372 private void cleanUpResourcesLI(List<String> allCodePaths) { 14373 cleanUp(); 14374 removeDexFiles(allCodePaths, instructionSets); 14375 } 14376 14377 String getPackageName() { 14378 return getAsecPackageName(cid); 14379 } 14380 14381 boolean doPostDeleteLI(boolean delete) { 14382 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14383 final List<String> allCodePaths = getAllCodePaths(); 14384 boolean mounted = PackageHelper.isContainerMounted(cid); 14385 if (mounted) { 14386 // Unmount first 14387 if (PackageHelper.unMountSdDir(cid)) { 14388 mounted = false; 14389 } 14390 } 14391 if (!mounted && delete) { 14392 cleanUpResourcesLI(allCodePaths); 14393 } 14394 return !mounted; 14395 } 14396 14397 @Override 14398 int doPreCopy() { 14399 if (isFwdLocked()) { 14400 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14401 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14402 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14403 } 14404 } 14405 14406 return PackageManager.INSTALL_SUCCEEDED; 14407 } 14408 14409 @Override 14410 int doPostCopy(int uid) { 14411 if (isFwdLocked()) { 14412 if (uid < Process.FIRST_APPLICATION_UID 14413 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14414 RES_FILE_NAME)) { 14415 Slog.e(TAG, "Failed to finalize " + cid); 14416 PackageHelper.destroySdDir(cid); 14417 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14418 } 14419 } 14420 14421 return PackageManager.INSTALL_SUCCEEDED; 14422 } 14423 } 14424 14425 /** 14426 * Logic to handle movement of existing installed applications. 14427 */ 14428 class MoveInstallArgs extends InstallArgs { 14429 private File codeFile; 14430 private File resourceFile; 14431 14432 /** New install */ 14433 MoveInstallArgs(InstallParams params) { 14434 super(params.origin, params.move, params.observer, params.installFlags, 14435 params.installerPackageName, params.volumeUuid, 14436 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14437 params.grantedRuntimePermissions, 14438 params.traceMethod, params.traceCookie, params.certificates); 14439 } 14440 14441 int copyApk(IMediaContainerService imcs, boolean temp) { 14442 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14443 + move.fromUuid + " to " + move.toUuid); 14444 synchronized (mInstaller) { 14445 try { 14446 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14447 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14448 } catch (InstallerException e) { 14449 Slog.w(TAG, "Failed to move app", e); 14450 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14451 } 14452 } 14453 14454 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14455 resourceFile = codeFile; 14456 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14457 14458 return PackageManager.INSTALL_SUCCEEDED; 14459 } 14460 14461 int doPreInstall(int status) { 14462 if (status != PackageManager.INSTALL_SUCCEEDED) { 14463 cleanUp(move.toUuid); 14464 } 14465 return status; 14466 } 14467 14468 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14469 if (status != PackageManager.INSTALL_SUCCEEDED) { 14470 cleanUp(move.toUuid); 14471 return false; 14472 } 14473 14474 // Reflect the move in app info 14475 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14476 pkg.setApplicationInfoCodePath(pkg.codePath); 14477 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14478 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14479 pkg.setApplicationInfoResourcePath(pkg.codePath); 14480 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14481 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14482 14483 return true; 14484 } 14485 14486 int doPostInstall(int status, int uid) { 14487 if (status == PackageManager.INSTALL_SUCCEEDED) { 14488 cleanUp(move.fromUuid); 14489 } else { 14490 cleanUp(move.toUuid); 14491 } 14492 return status; 14493 } 14494 14495 @Override 14496 String getCodePath() { 14497 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14498 } 14499 14500 @Override 14501 String getResourcePath() { 14502 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14503 } 14504 14505 private boolean cleanUp(String volumeUuid) { 14506 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14507 move.dataAppName); 14508 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14509 final int[] userIds = sUserManager.getUserIds(); 14510 synchronized (mInstallLock) { 14511 // Clean up both app data and code 14512 // All package moves are frozen until finished 14513 for (int userId : userIds) { 14514 try { 14515 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14516 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14517 } catch (InstallerException e) { 14518 Slog.w(TAG, String.valueOf(e)); 14519 } 14520 } 14521 removeCodePathLI(codeFile); 14522 } 14523 return true; 14524 } 14525 14526 void cleanUpResourcesLI() { 14527 throw new UnsupportedOperationException(); 14528 } 14529 14530 boolean doPostDeleteLI(boolean delete) { 14531 throw new UnsupportedOperationException(); 14532 } 14533 } 14534 14535 static String getAsecPackageName(String packageCid) { 14536 int idx = packageCid.lastIndexOf("-"); 14537 if (idx == -1) { 14538 return packageCid; 14539 } 14540 return packageCid.substring(0, idx); 14541 } 14542 14543 // Utility method used to create code paths based on package name and available index. 14544 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14545 String idxStr = ""; 14546 int idx = 1; 14547 // Fall back to default value of idx=1 if prefix is not 14548 // part of oldCodePath 14549 if (oldCodePath != null) { 14550 String subStr = oldCodePath; 14551 // Drop the suffix right away 14552 if (suffix != null && subStr.endsWith(suffix)) { 14553 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14554 } 14555 // If oldCodePath already contains prefix find out the 14556 // ending index to either increment or decrement. 14557 int sidx = subStr.lastIndexOf(prefix); 14558 if (sidx != -1) { 14559 subStr = subStr.substring(sidx + prefix.length()); 14560 if (subStr != null) { 14561 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14562 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14563 } 14564 try { 14565 idx = Integer.parseInt(subStr); 14566 if (idx <= 1) { 14567 idx++; 14568 } else { 14569 idx--; 14570 } 14571 } catch(NumberFormatException e) { 14572 } 14573 } 14574 } 14575 } 14576 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14577 return prefix + idxStr; 14578 } 14579 14580 private File getNextCodePath(File targetDir, String packageName) { 14581 File result; 14582 SecureRandom random = new SecureRandom(); 14583 byte[] bytes = new byte[16]; 14584 do { 14585 random.nextBytes(bytes); 14586 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14587 result = new File(targetDir, packageName + "-" + suffix); 14588 } while (result.exists()); 14589 return result; 14590 } 14591 14592 // Utility method that returns the relative package path with respect 14593 // to the installation directory. Like say for /data/data/com.test-1.apk 14594 // string com.test-1 is returned. 14595 static String deriveCodePathName(String codePath) { 14596 if (codePath == null) { 14597 return null; 14598 } 14599 final File codeFile = new File(codePath); 14600 final String name = codeFile.getName(); 14601 if (codeFile.isDirectory()) { 14602 return name; 14603 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14604 final int lastDot = name.lastIndexOf('.'); 14605 return name.substring(0, lastDot); 14606 } else { 14607 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14608 return null; 14609 } 14610 } 14611 14612 static class PackageInstalledInfo { 14613 String name; 14614 int uid; 14615 // The set of users that originally had this package installed. 14616 int[] origUsers; 14617 // The set of users that now have this package installed. 14618 int[] newUsers; 14619 PackageParser.Package pkg; 14620 int returnCode; 14621 String returnMsg; 14622 PackageRemovedInfo removedInfo; 14623 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14624 14625 public void setError(int code, String msg) { 14626 setReturnCode(code); 14627 setReturnMessage(msg); 14628 Slog.w(TAG, msg); 14629 } 14630 14631 public void setError(String msg, PackageParserException e) { 14632 setReturnCode(e.error); 14633 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14634 Slog.w(TAG, msg, e); 14635 } 14636 14637 public void setError(String msg, PackageManagerException e) { 14638 returnCode = e.error; 14639 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14640 Slog.w(TAG, msg, e); 14641 } 14642 14643 public void setReturnCode(int returnCode) { 14644 this.returnCode = returnCode; 14645 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14646 for (int i = 0; i < childCount; i++) { 14647 addedChildPackages.valueAt(i).returnCode = returnCode; 14648 } 14649 } 14650 14651 private void setReturnMessage(String returnMsg) { 14652 this.returnMsg = returnMsg; 14653 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14654 for (int i = 0; i < childCount; i++) { 14655 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14656 } 14657 } 14658 14659 // In some error cases we want to convey more info back to the observer 14660 String origPackage; 14661 String origPermission; 14662 } 14663 14664 /* 14665 * Install a non-existing package. 14666 */ 14667 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14668 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14669 PackageInstalledInfo res) { 14670 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14671 14672 // Remember this for later, in case we need to rollback this install 14673 String pkgName = pkg.packageName; 14674 14675 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14676 14677 synchronized(mPackages) { 14678 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14679 if (renamedPackage != null) { 14680 // A package with the same name is already installed, though 14681 // it has been renamed to an older name. The package we 14682 // are trying to install should be installed as an update to 14683 // the existing one, but that has not been requested, so bail. 14684 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14685 + " without first uninstalling package running as " 14686 + renamedPackage); 14687 return; 14688 } 14689 if (mPackages.containsKey(pkgName)) { 14690 // Don't allow installation over an existing package with the same name. 14691 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14692 + " without first uninstalling."); 14693 return; 14694 } 14695 } 14696 14697 try { 14698 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14699 System.currentTimeMillis(), user); 14700 14701 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14702 14703 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14704 prepareAppDataAfterInstallLIF(newPackage); 14705 14706 } else { 14707 // Remove package from internal structures, but keep around any 14708 // data that might have already existed 14709 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14710 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14711 } 14712 } catch (PackageManagerException e) { 14713 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14714 } 14715 14716 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14717 } 14718 14719 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14720 // Can't rotate keys during boot or if sharedUser. 14721 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14722 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14723 return false; 14724 } 14725 // app is using upgradeKeySets; make sure all are valid 14726 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14727 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14728 for (int i = 0; i < upgradeKeySets.length; i++) { 14729 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14730 Slog.wtf(TAG, "Package " 14731 + (oldPs.name != null ? oldPs.name : "<null>") 14732 + " contains upgrade-key-set reference to unknown key-set: " 14733 + upgradeKeySets[i] 14734 + " reverting to signatures check."); 14735 return false; 14736 } 14737 } 14738 return true; 14739 } 14740 14741 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14742 // Upgrade keysets are being used. Determine if new package has a superset of the 14743 // required keys. 14744 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14745 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14746 for (int i = 0; i < upgradeKeySets.length; i++) { 14747 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14748 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14749 return true; 14750 } 14751 } 14752 return false; 14753 } 14754 14755 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14756 try (DigestInputStream digestStream = 14757 new DigestInputStream(new FileInputStream(file), digest)) { 14758 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14759 } 14760 } 14761 14762 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14763 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14764 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14765 14766 final PackageParser.Package oldPackage; 14767 final String pkgName = pkg.packageName; 14768 final int[] allUsers; 14769 final int[] installedUsers; 14770 14771 synchronized(mPackages) { 14772 oldPackage = mPackages.get(pkgName); 14773 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14774 14775 // don't allow upgrade to target a release SDK from a pre-release SDK 14776 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14777 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14778 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14779 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14780 if (oldTargetsPreRelease 14781 && !newTargetsPreRelease 14782 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14783 Slog.w(TAG, "Can't install package targeting released sdk"); 14784 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14785 return; 14786 } 14787 14788 // don't allow an upgrade from full to ephemeral 14789 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14790 if (isEphemeral && !oldIsEphemeral) { 14791 // can't downgrade from full to ephemeral 14792 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14793 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14794 return; 14795 } 14796 14797 // verify signatures are valid 14798 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14799 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14800 if (!checkUpgradeKeySetLP(ps, pkg)) { 14801 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14802 "New package not signed by keys specified by upgrade-keysets: " 14803 + pkgName); 14804 return; 14805 } 14806 } else { 14807 // default to original signature matching 14808 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14809 != PackageManager.SIGNATURE_MATCH) { 14810 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14811 "New package has a different signature: " + pkgName); 14812 return; 14813 } 14814 } 14815 14816 // don't allow a system upgrade unless the upgrade hash matches 14817 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14818 byte[] digestBytes = null; 14819 try { 14820 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14821 updateDigest(digest, new File(pkg.baseCodePath)); 14822 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14823 for (String path : pkg.splitCodePaths) { 14824 updateDigest(digest, new File(path)); 14825 } 14826 } 14827 digestBytes = digest.digest(); 14828 } catch (NoSuchAlgorithmException | IOException e) { 14829 res.setError(INSTALL_FAILED_INVALID_APK, 14830 "Could not compute hash: " + pkgName); 14831 return; 14832 } 14833 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14834 res.setError(INSTALL_FAILED_INVALID_APK, 14835 "New package fails restrict-update check: " + pkgName); 14836 return; 14837 } 14838 // retain upgrade restriction 14839 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14840 } 14841 14842 // Check for shared user id changes 14843 String invalidPackageName = 14844 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14845 if (invalidPackageName != null) { 14846 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14847 "Package " + invalidPackageName + " tried to change user " 14848 + oldPackage.mSharedUserId); 14849 return; 14850 } 14851 14852 // In case of rollback, remember per-user/profile install state 14853 allUsers = sUserManager.getUserIds(); 14854 installedUsers = ps.queryInstalledUsers(allUsers, true); 14855 } 14856 14857 // Update what is removed 14858 res.removedInfo = new PackageRemovedInfo(); 14859 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14860 res.removedInfo.removedPackage = oldPackage.packageName; 14861 res.removedInfo.isUpdate = true; 14862 res.removedInfo.origUsers = installedUsers; 14863 final int childCount = (oldPackage.childPackages != null) 14864 ? oldPackage.childPackages.size() : 0; 14865 for (int i = 0; i < childCount; i++) { 14866 boolean childPackageUpdated = false; 14867 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14868 if (res.addedChildPackages != null) { 14869 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14870 if (childRes != null) { 14871 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14872 childRes.removedInfo.removedPackage = childPkg.packageName; 14873 childRes.removedInfo.isUpdate = true; 14874 childPackageUpdated = true; 14875 } 14876 } 14877 if (!childPackageUpdated) { 14878 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14879 childRemovedRes.removedPackage = childPkg.packageName; 14880 childRemovedRes.isUpdate = false; 14881 childRemovedRes.dataRemoved = true; 14882 synchronized (mPackages) { 14883 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14884 if (childPs != null) { 14885 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14886 } 14887 } 14888 if (res.removedInfo.removedChildPackages == null) { 14889 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14890 } 14891 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14892 } 14893 } 14894 14895 boolean sysPkg = (isSystemApp(oldPackage)); 14896 if (sysPkg) { 14897 // Set the system/privileged flags as needed 14898 final boolean privileged = 14899 (oldPackage.applicationInfo.privateFlags 14900 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14901 final int systemPolicyFlags = policyFlags 14902 | PackageParser.PARSE_IS_SYSTEM 14903 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14904 14905 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14906 user, allUsers, installerPackageName, res); 14907 } else { 14908 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14909 user, allUsers, installerPackageName, res); 14910 } 14911 } 14912 14913 public List<String> getPreviousCodePaths(String packageName) { 14914 final PackageSetting ps = mSettings.mPackages.get(packageName); 14915 final List<String> result = new ArrayList<String>(); 14916 if (ps != null && ps.oldCodePaths != null) { 14917 result.addAll(ps.oldCodePaths); 14918 } 14919 return result; 14920 } 14921 14922 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14923 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14924 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14925 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14926 + deletedPackage); 14927 14928 String pkgName = deletedPackage.packageName; 14929 boolean deletedPkg = true; 14930 boolean addedPkg = false; 14931 boolean updatedSettings = false; 14932 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14933 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14934 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14935 14936 final long origUpdateTime = (pkg.mExtras != null) 14937 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14938 14939 // First delete the existing package while retaining the data directory 14940 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14941 res.removedInfo, true, pkg)) { 14942 // If the existing package wasn't successfully deleted 14943 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14944 deletedPkg = false; 14945 } else { 14946 // Successfully deleted the old package; proceed with replace. 14947 14948 // If deleted package lived in a container, give users a chance to 14949 // relinquish resources before killing. 14950 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14951 if (DEBUG_INSTALL) { 14952 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14953 } 14954 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14955 final ArrayList<String> pkgList = new ArrayList<String>(1); 14956 pkgList.add(deletedPackage.applicationInfo.packageName); 14957 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14958 } 14959 14960 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14961 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14962 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14963 14964 try { 14965 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14966 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14967 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14968 14969 // Update the in-memory copy of the previous code paths. 14970 PackageSetting ps = mSettings.mPackages.get(pkgName); 14971 if (!killApp) { 14972 if (ps.oldCodePaths == null) { 14973 ps.oldCodePaths = new ArraySet<>(); 14974 } 14975 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14976 if (deletedPackage.splitCodePaths != null) { 14977 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14978 } 14979 } else { 14980 ps.oldCodePaths = null; 14981 } 14982 if (ps.childPackageNames != null) { 14983 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14984 final String childPkgName = ps.childPackageNames.get(i); 14985 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14986 childPs.oldCodePaths = ps.oldCodePaths; 14987 } 14988 } 14989 prepareAppDataAfterInstallLIF(newPackage); 14990 addedPkg = true; 14991 } catch (PackageManagerException e) { 14992 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14993 } 14994 } 14995 14996 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14997 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14998 14999 // Revert all internal state mutations and added folders for the failed install 15000 if (addedPkg) { 15001 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15002 res.removedInfo, true, null); 15003 } 15004 15005 // Restore the old package 15006 if (deletedPkg) { 15007 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15008 File restoreFile = new File(deletedPackage.codePath); 15009 // Parse old package 15010 boolean oldExternal = isExternal(deletedPackage); 15011 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15012 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15013 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15014 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15015 try { 15016 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15017 null); 15018 } catch (PackageManagerException e) { 15019 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15020 + e.getMessage()); 15021 return; 15022 } 15023 15024 synchronized (mPackages) { 15025 // Ensure the installer package name up to date 15026 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15027 15028 // Update permissions for restored package 15029 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15030 15031 mSettings.writeLPr(); 15032 } 15033 15034 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15035 } 15036 } else { 15037 synchronized (mPackages) { 15038 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15039 if (ps != null) { 15040 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15041 if (res.removedInfo.removedChildPackages != null) { 15042 final int childCount = res.removedInfo.removedChildPackages.size(); 15043 // Iterate in reverse as we may modify the collection 15044 for (int i = childCount - 1; i >= 0; i--) { 15045 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15046 if (res.addedChildPackages.containsKey(childPackageName)) { 15047 res.removedInfo.removedChildPackages.removeAt(i); 15048 } else { 15049 PackageRemovedInfo childInfo = res.removedInfo 15050 .removedChildPackages.valueAt(i); 15051 childInfo.removedForAllUsers = mPackages.get( 15052 childInfo.removedPackage) == null; 15053 } 15054 } 15055 } 15056 } 15057 } 15058 } 15059 } 15060 15061 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15062 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15063 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 15064 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15065 + ", old=" + deletedPackage); 15066 15067 final boolean disabledSystem; 15068 15069 // Remove existing system package 15070 removePackageLI(deletedPackage, true); 15071 15072 synchronized (mPackages) { 15073 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15074 } 15075 if (!disabledSystem) { 15076 // We didn't need to disable the .apk as a current system package, 15077 // which means we are replacing another update that is already 15078 // installed. We need to make sure to delete the older one's .apk. 15079 res.removedInfo.args = createInstallArgsForExisting(0, 15080 deletedPackage.applicationInfo.getCodePath(), 15081 deletedPackage.applicationInfo.getResourcePath(), 15082 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15083 } else { 15084 res.removedInfo.args = null; 15085 } 15086 15087 // Successfully disabled the old package. Now proceed with re-installation 15088 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15089 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15090 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15091 15092 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15093 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15094 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15095 15096 PackageParser.Package newPackage = null; 15097 try { 15098 // Add the package to the internal data structures 15099 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 15100 15101 // Set the update and install times 15102 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15103 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15104 System.currentTimeMillis()); 15105 15106 // Update the package dynamic state if succeeded 15107 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15108 // Now that the install succeeded make sure we remove data 15109 // directories for any child package the update removed. 15110 final int deletedChildCount = (deletedPackage.childPackages != null) 15111 ? deletedPackage.childPackages.size() : 0; 15112 final int newChildCount = (newPackage.childPackages != null) 15113 ? newPackage.childPackages.size() : 0; 15114 for (int i = 0; i < deletedChildCount; i++) { 15115 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15116 boolean childPackageDeleted = true; 15117 for (int j = 0; j < newChildCount; j++) { 15118 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15119 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15120 childPackageDeleted = false; 15121 break; 15122 } 15123 } 15124 if (childPackageDeleted) { 15125 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15126 deletedChildPkg.packageName); 15127 if (ps != null && res.removedInfo.removedChildPackages != null) { 15128 PackageRemovedInfo removedChildRes = res.removedInfo 15129 .removedChildPackages.get(deletedChildPkg.packageName); 15130 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15131 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15132 } 15133 } 15134 } 15135 15136 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15137 prepareAppDataAfterInstallLIF(newPackage); 15138 } 15139 } catch (PackageManagerException e) { 15140 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15141 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15142 } 15143 15144 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15145 // Re installation failed. Restore old information 15146 // Remove new pkg information 15147 if (newPackage != null) { 15148 removeInstalledPackageLI(newPackage, true); 15149 } 15150 // Add back the old system package 15151 try { 15152 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15153 } catch (PackageManagerException e) { 15154 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15155 } 15156 15157 synchronized (mPackages) { 15158 if (disabledSystem) { 15159 enableSystemPackageLPw(deletedPackage); 15160 } 15161 15162 // Ensure the installer package name up to date 15163 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15164 15165 // Update permissions for restored package 15166 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15167 15168 mSettings.writeLPr(); 15169 } 15170 15171 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15172 + " after failed upgrade"); 15173 } 15174 } 15175 15176 /** 15177 * Checks whether the parent or any of the child packages have a change shared 15178 * user. For a package to be a valid update the shred users of the parent and 15179 * the children should match. We may later support changing child shared users. 15180 * @param oldPkg The updated package. 15181 * @param newPkg The update package. 15182 * @return The shared user that change between the versions. 15183 */ 15184 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15185 PackageParser.Package newPkg) { 15186 // Check parent shared user 15187 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15188 return newPkg.packageName; 15189 } 15190 // Check child shared users 15191 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15192 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15193 for (int i = 0; i < newChildCount; i++) { 15194 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15195 // If this child was present, did it have the same shared user? 15196 for (int j = 0; j < oldChildCount; j++) { 15197 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15198 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15199 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15200 return newChildPkg.packageName; 15201 } 15202 } 15203 } 15204 return null; 15205 } 15206 15207 private void removeNativeBinariesLI(PackageSetting ps) { 15208 // Remove the lib path for the parent package 15209 if (ps != null) { 15210 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15211 // Remove the lib path for the child packages 15212 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15213 for (int i = 0; i < childCount; i++) { 15214 PackageSetting childPs = null; 15215 synchronized (mPackages) { 15216 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15217 } 15218 if (childPs != null) { 15219 NativeLibraryHelper.removeNativeBinariesLI(childPs 15220 .legacyNativeLibraryPathString); 15221 } 15222 } 15223 } 15224 } 15225 15226 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15227 // Enable the parent package 15228 mSettings.enableSystemPackageLPw(pkg.packageName); 15229 // Enable the child packages 15230 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15231 for (int i = 0; i < childCount; i++) { 15232 PackageParser.Package childPkg = pkg.childPackages.get(i); 15233 mSettings.enableSystemPackageLPw(childPkg.packageName); 15234 } 15235 } 15236 15237 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15238 PackageParser.Package newPkg) { 15239 // Disable the parent package (parent always replaced) 15240 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15241 // Disable the child packages 15242 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15243 for (int i = 0; i < childCount; i++) { 15244 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15245 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15246 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15247 } 15248 return disabled; 15249 } 15250 15251 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15252 String installerPackageName) { 15253 // Enable the parent package 15254 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15255 // Enable the child packages 15256 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15257 for (int i = 0; i < childCount; i++) { 15258 PackageParser.Package childPkg = pkg.childPackages.get(i); 15259 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15260 } 15261 } 15262 15263 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15264 // Collect all used permissions in the UID 15265 ArraySet<String> usedPermissions = new ArraySet<>(); 15266 final int packageCount = su.packages.size(); 15267 for (int i = 0; i < packageCount; i++) { 15268 PackageSetting ps = su.packages.valueAt(i); 15269 if (ps.pkg == null) { 15270 continue; 15271 } 15272 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15273 for (int j = 0; j < requestedPermCount; j++) { 15274 String permission = ps.pkg.requestedPermissions.get(j); 15275 BasePermission bp = mSettings.mPermissions.get(permission); 15276 if (bp != null) { 15277 usedPermissions.add(permission); 15278 } 15279 } 15280 } 15281 15282 PermissionsState permissionsState = su.getPermissionsState(); 15283 // Prune install permissions 15284 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15285 final int installPermCount = installPermStates.size(); 15286 for (int i = installPermCount - 1; i >= 0; i--) { 15287 PermissionState permissionState = installPermStates.get(i); 15288 if (!usedPermissions.contains(permissionState.getName())) { 15289 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15290 if (bp != null) { 15291 permissionsState.revokeInstallPermission(bp); 15292 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15293 PackageManager.MASK_PERMISSION_FLAGS, 0); 15294 } 15295 } 15296 } 15297 15298 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15299 15300 // Prune runtime permissions 15301 for (int userId : allUserIds) { 15302 List<PermissionState> runtimePermStates = permissionsState 15303 .getRuntimePermissionStates(userId); 15304 final int runtimePermCount = runtimePermStates.size(); 15305 for (int i = runtimePermCount - 1; i >= 0; i--) { 15306 PermissionState permissionState = runtimePermStates.get(i); 15307 if (!usedPermissions.contains(permissionState.getName())) { 15308 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15309 if (bp != null) { 15310 permissionsState.revokeRuntimePermission(bp, userId); 15311 permissionsState.updatePermissionFlags(bp, userId, 15312 PackageManager.MASK_PERMISSION_FLAGS, 0); 15313 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15314 runtimePermissionChangedUserIds, userId); 15315 } 15316 } 15317 } 15318 } 15319 15320 return runtimePermissionChangedUserIds; 15321 } 15322 15323 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15324 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15325 // Update the parent package setting 15326 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15327 res, user); 15328 // Update the child packages setting 15329 final int childCount = (newPackage.childPackages != null) 15330 ? newPackage.childPackages.size() : 0; 15331 for (int i = 0; i < childCount; i++) { 15332 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15333 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15334 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15335 childRes.origUsers, childRes, user); 15336 } 15337 } 15338 15339 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15340 String installerPackageName, int[] allUsers, int[] installedForUsers, 15341 PackageInstalledInfo res, UserHandle user) { 15342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15343 15344 String pkgName = newPackage.packageName; 15345 synchronized (mPackages) { 15346 //write settings. the installStatus will be incomplete at this stage. 15347 //note that the new package setting would have already been 15348 //added to mPackages. It hasn't been persisted yet. 15349 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15350 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15351 mSettings.writeLPr(); 15352 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15353 } 15354 15355 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15356 synchronized (mPackages) { 15357 updatePermissionsLPw(newPackage.packageName, newPackage, 15358 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15359 ? UPDATE_PERMISSIONS_ALL : 0)); 15360 // For system-bundled packages, we assume that installing an upgraded version 15361 // of the package implies that the user actually wants to run that new code, 15362 // so we enable the package. 15363 PackageSetting ps = mSettings.mPackages.get(pkgName); 15364 final int userId = user.getIdentifier(); 15365 if (ps != null) { 15366 if (isSystemApp(newPackage)) { 15367 if (DEBUG_INSTALL) { 15368 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15369 } 15370 // Enable system package for requested users 15371 if (res.origUsers != null) { 15372 for (int origUserId : res.origUsers) { 15373 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15374 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15375 origUserId, installerPackageName); 15376 } 15377 } 15378 } 15379 // Also convey the prior install/uninstall state 15380 if (allUsers != null && installedForUsers != null) { 15381 for (int currentUserId : allUsers) { 15382 final boolean installed = ArrayUtils.contains( 15383 installedForUsers, currentUserId); 15384 if (DEBUG_INSTALL) { 15385 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15386 } 15387 ps.setInstalled(installed, currentUserId); 15388 } 15389 // these install state changes will be persisted in the 15390 // upcoming call to mSettings.writeLPr(). 15391 } 15392 } 15393 // It's implied that when a user requests installation, they want the app to be 15394 // installed and enabled. 15395 if (userId != UserHandle.USER_ALL) { 15396 ps.setInstalled(true, userId); 15397 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15398 } 15399 } 15400 res.name = pkgName; 15401 res.uid = newPackage.applicationInfo.uid; 15402 res.pkg = newPackage; 15403 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15404 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15405 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15406 //to update install status 15407 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15408 mSettings.writeLPr(); 15409 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15410 } 15411 15412 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15413 } 15414 15415 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15416 try { 15417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15418 installPackageLI(args, res); 15419 } finally { 15420 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15421 } 15422 } 15423 15424 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15425 final int installFlags = args.installFlags; 15426 final String installerPackageName = args.installerPackageName; 15427 final String volumeUuid = args.volumeUuid; 15428 final File tmpPackageFile = new File(args.getCodePath()); 15429 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15430 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15431 || (args.volumeUuid != null)); 15432 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15433 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15434 boolean replace = false; 15435 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15436 if (args.move != null) { 15437 // moving a complete application; perform an initial scan on the new install location 15438 scanFlags |= SCAN_INITIAL; 15439 } 15440 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15441 scanFlags |= SCAN_DONT_KILL_APP; 15442 } 15443 15444 // Result object to be returned 15445 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15446 15447 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15448 15449 // Sanity check 15450 if (ephemeral && (forwardLocked || onExternal)) { 15451 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15452 + " external=" + onExternal); 15453 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15454 return; 15455 } 15456 15457 // Retrieve PackageSettings and parse package 15458 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15459 | PackageParser.PARSE_ENFORCE_CODE 15460 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15461 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15462 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15463 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15464 PackageParser pp = new PackageParser(); 15465 pp.setSeparateProcesses(mSeparateProcesses); 15466 pp.setDisplayMetrics(mMetrics); 15467 15468 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15469 final PackageParser.Package pkg; 15470 try { 15471 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15472 } catch (PackageParserException e) { 15473 res.setError("Failed parse during installPackageLI", e); 15474 return; 15475 } finally { 15476 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15477 } 15478 15479 // If we are installing a clustered package add results for the children 15480 if (pkg.childPackages != null) { 15481 synchronized (mPackages) { 15482 final int childCount = pkg.childPackages.size(); 15483 for (int i = 0; i < childCount; i++) { 15484 PackageParser.Package childPkg = pkg.childPackages.get(i); 15485 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15486 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15487 childRes.pkg = childPkg; 15488 childRes.name = childPkg.packageName; 15489 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15490 if (childPs != null) { 15491 childRes.origUsers = childPs.queryInstalledUsers( 15492 sUserManager.getUserIds(), true); 15493 } 15494 if ((mPackages.containsKey(childPkg.packageName))) { 15495 childRes.removedInfo = new PackageRemovedInfo(); 15496 childRes.removedInfo.removedPackage = childPkg.packageName; 15497 } 15498 if (res.addedChildPackages == null) { 15499 res.addedChildPackages = new ArrayMap<>(); 15500 } 15501 res.addedChildPackages.put(childPkg.packageName, childRes); 15502 } 15503 } 15504 } 15505 15506 // If package doesn't declare API override, mark that we have an install 15507 // time CPU ABI override. 15508 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15509 pkg.cpuAbiOverride = args.abiOverride; 15510 } 15511 15512 String pkgName = res.name = pkg.packageName; 15513 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15514 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15515 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15516 return; 15517 } 15518 } 15519 15520 try { 15521 // either use what we've been given or parse directly from the APK 15522 if (args.certificates != null) { 15523 try { 15524 PackageParser.populateCertificates(pkg, args.certificates); 15525 } catch (PackageParserException e) { 15526 // there was something wrong with the certificates we were given; 15527 // try to pull them from the APK 15528 PackageParser.collectCertificates(pkg, parseFlags); 15529 } 15530 } else { 15531 PackageParser.collectCertificates(pkg, parseFlags); 15532 } 15533 } catch (PackageParserException e) { 15534 res.setError("Failed collect during installPackageLI", e); 15535 return; 15536 } 15537 15538 // Get rid of all references to package scan path via parser. 15539 pp = null; 15540 String oldCodePath = null; 15541 boolean systemApp = false; 15542 synchronized (mPackages) { 15543 // Check if installing already existing package 15544 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15545 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15546 if (pkg.mOriginalPackages != null 15547 && pkg.mOriginalPackages.contains(oldName) 15548 && mPackages.containsKey(oldName)) { 15549 // This package is derived from an original package, 15550 // and this device has been updating from that original 15551 // name. We must continue using the original name, so 15552 // rename the new package here. 15553 pkg.setPackageName(oldName); 15554 pkgName = pkg.packageName; 15555 replace = true; 15556 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15557 + oldName + " pkgName=" + pkgName); 15558 } else if (mPackages.containsKey(pkgName)) { 15559 // This package, under its official name, already exists 15560 // on the device; we should replace it. 15561 replace = true; 15562 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15563 } 15564 15565 // Child packages are installed through the parent package 15566 if (pkg.parentPackage != null) { 15567 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15568 "Package " + pkg.packageName + " is child of package " 15569 + pkg.parentPackage.parentPackage + ". Child packages " 15570 + "can be updated only through the parent package."); 15571 return; 15572 } 15573 15574 if (replace) { 15575 // Prevent apps opting out from runtime permissions 15576 PackageParser.Package oldPackage = mPackages.get(pkgName); 15577 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15578 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15579 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15580 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15581 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15582 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15583 + " doesn't support runtime permissions but the old" 15584 + " target SDK " + oldTargetSdk + " does."); 15585 return; 15586 } 15587 15588 // Prevent installing of child packages 15589 if (oldPackage.parentPackage != null) { 15590 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15591 "Package " + pkg.packageName + " is child of package " 15592 + oldPackage.parentPackage + ". Child packages " 15593 + "can be updated only through the parent package."); 15594 return; 15595 } 15596 } 15597 } 15598 15599 PackageSetting ps = mSettings.mPackages.get(pkgName); 15600 if (ps != null) { 15601 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15602 15603 // Quick sanity check that we're signed correctly if updating; 15604 // we'll check this again later when scanning, but we want to 15605 // bail early here before tripping over redefined permissions. 15606 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15607 if (!checkUpgradeKeySetLP(ps, pkg)) { 15608 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15609 + pkg.packageName + " upgrade keys do not match the " 15610 + "previously installed version"); 15611 return; 15612 } 15613 } else { 15614 try { 15615 verifySignaturesLP(ps, pkg); 15616 } catch (PackageManagerException e) { 15617 res.setError(e.error, e.getMessage()); 15618 return; 15619 } 15620 } 15621 15622 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15623 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15624 systemApp = (ps.pkg.applicationInfo.flags & 15625 ApplicationInfo.FLAG_SYSTEM) != 0; 15626 } 15627 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15628 } 15629 15630 // Check whether the newly-scanned package wants to define an already-defined perm 15631 int N = pkg.permissions.size(); 15632 for (int i = N-1; i >= 0; i--) { 15633 PackageParser.Permission perm = pkg.permissions.get(i); 15634 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15635 if (bp != null) { 15636 // If the defining package is signed with our cert, it's okay. This 15637 // also includes the "updating the same package" case, of course. 15638 // "updating same package" could also involve key-rotation. 15639 final boolean sigsOk; 15640 if (bp.sourcePackage.equals(pkg.packageName) 15641 && (bp.packageSetting instanceof PackageSetting) 15642 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15643 scanFlags))) { 15644 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15645 } else { 15646 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15647 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15648 } 15649 if (!sigsOk) { 15650 // If the owning package is the system itself, we log but allow 15651 // install to proceed; we fail the install on all other permission 15652 // redefinitions. 15653 if (!bp.sourcePackage.equals("android")) { 15654 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15655 + pkg.packageName + " attempting to redeclare permission " 15656 + perm.info.name + " already owned by " + bp.sourcePackage); 15657 res.origPermission = perm.info.name; 15658 res.origPackage = bp.sourcePackage; 15659 return; 15660 } else { 15661 Slog.w(TAG, "Package " + pkg.packageName 15662 + " attempting to redeclare system permission " 15663 + perm.info.name + "; ignoring new declaration"); 15664 pkg.permissions.remove(i); 15665 } 15666 } 15667 } 15668 } 15669 } 15670 15671 if (systemApp) { 15672 if (onExternal) { 15673 // Abort update; system app can't be replaced with app on sdcard 15674 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15675 "Cannot install updates to system apps on sdcard"); 15676 return; 15677 } else if (ephemeral) { 15678 // Abort update; system app can't be replaced with an ephemeral app 15679 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15680 "Cannot update a system app with an ephemeral app"); 15681 return; 15682 } 15683 } 15684 15685 if (args.move != null) { 15686 // We did an in-place move, so dex is ready to roll 15687 scanFlags |= SCAN_NO_DEX; 15688 scanFlags |= SCAN_MOVE; 15689 15690 synchronized (mPackages) { 15691 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15692 if (ps == null) { 15693 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15694 "Missing settings for moved package " + pkgName); 15695 } 15696 15697 // We moved the entire application as-is, so bring over the 15698 // previously derived ABI information. 15699 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15700 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15701 } 15702 15703 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15704 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15705 scanFlags |= SCAN_NO_DEX; 15706 15707 try { 15708 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15709 args.abiOverride : pkg.cpuAbiOverride); 15710 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15711 true /*extractLibs*/, mAppLib32InstallDir); 15712 } catch (PackageManagerException pme) { 15713 Slog.e(TAG, "Error deriving application ABI", pme); 15714 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15715 return; 15716 } 15717 15718 // Shared libraries for the package need to be updated. 15719 synchronized (mPackages) { 15720 try { 15721 updateSharedLibrariesLPr(pkg, null); 15722 } catch (PackageManagerException e) { 15723 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15724 } 15725 } 15726 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15727 // Do not run PackageDexOptimizer through the local performDexOpt 15728 // method because `pkg` may not be in `mPackages` yet. 15729 // 15730 // Also, don't fail application installs if the dexopt step fails. 15731 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15732 null /* instructionSets */, false /* checkProfiles */, 15733 getCompilerFilterForReason(REASON_INSTALL), 15734 getOrCreateCompilerPackageStats(pkg)); 15735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15736 15737 // Notify BackgroundDexOptService that the package has been changed. 15738 // If this is an update of a package which used to fail to compile, 15739 // BDOS will remove it from its blacklist. 15740 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15741 } 15742 15743 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15744 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15745 return; 15746 } 15747 15748 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15749 15750 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15751 "installPackageLI")) { 15752 if (replace) { 15753 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15754 installerPackageName, res); 15755 } else { 15756 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15757 args.user, installerPackageName, volumeUuid, res); 15758 } 15759 } 15760 synchronized (mPackages) { 15761 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15762 if (ps != null) { 15763 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15764 } 15765 15766 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15767 for (int i = 0; i < childCount; i++) { 15768 PackageParser.Package childPkg = pkg.childPackages.get(i); 15769 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15770 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15771 if (childPs != null) { 15772 childRes.newUsers = childPs.queryInstalledUsers( 15773 sUserManager.getUserIds(), true); 15774 } 15775 } 15776 } 15777 } 15778 15779 private void startIntentFilterVerifications(int userId, boolean replacing, 15780 PackageParser.Package pkg) { 15781 if (mIntentFilterVerifierComponent == null) { 15782 Slog.w(TAG, "No IntentFilter verification will not be done as " 15783 + "there is no IntentFilterVerifier available!"); 15784 return; 15785 } 15786 15787 final int verifierUid = getPackageUid( 15788 mIntentFilterVerifierComponent.getPackageName(), 15789 MATCH_DEBUG_TRIAGED_MISSING, 15790 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15791 15792 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15793 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15794 mHandler.sendMessage(msg); 15795 15796 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15797 for (int i = 0; i < childCount; i++) { 15798 PackageParser.Package childPkg = pkg.childPackages.get(i); 15799 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15800 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15801 mHandler.sendMessage(msg); 15802 } 15803 } 15804 15805 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15806 PackageParser.Package pkg) { 15807 int size = pkg.activities.size(); 15808 if (size == 0) { 15809 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15810 "No activity, so no need to verify any IntentFilter!"); 15811 return; 15812 } 15813 15814 final boolean hasDomainURLs = hasDomainURLs(pkg); 15815 if (!hasDomainURLs) { 15816 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15817 "No domain URLs, so no need to verify any IntentFilter!"); 15818 return; 15819 } 15820 15821 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15822 + " if any IntentFilter from the " + size 15823 + " Activities needs verification ..."); 15824 15825 int count = 0; 15826 final String packageName = pkg.packageName; 15827 15828 synchronized (mPackages) { 15829 // If this is a new install and we see that we've already run verification for this 15830 // package, we have nothing to do: it means the state was restored from backup. 15831 if (!replacing) { 15832 IntentFilterVerificationInfo ivi = 15833 mSettings.getIntentFilterVerificationLPr(packageName); 15834 if (ivi != null) { 15835 if (DEBUG_DOMAIN_VERIFICATION) { 15836 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15837 + ivi.getStatusString()); 15838 } 15839 return; 15840 } 15841 } 15842 15843 // If any filters need to be verified, then all need to be. 15844 boolean needToVerify = false; 15845 for (PackageParser.Activity a : pkg.activities) { 15846 for (ActivityIntentInfo filter : a.intents) { 15847 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15848 if (DEBUG_DOMAIN_VERIFICATION) { 15849 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15850 } 15851 needToVerify = true; 15852 break; 15853 } 15854 } 15855 } 15856 15857 if (needToVerify) { 15858 final int verificationId = mIntentFilterVerificationToken++; 15859 for (PackageParser.Activity a : pkg.activities) { 15860 for (ActivityIntentInfo filter : a.intents) { 15861 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15862 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15863 "Verification needed for IntentFilter:" + filter.toString()); 15864 mIntentFilterVerifier.addOneIntentFilterVerification( 15865 verifierUid, userId, verificationId, filter, packageName); 15866 count++; 15867 } 15868 } 15869 } 15870 } 15871 } 15872 15873 if (count > 0) { 15874 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15875 + " IntentFilter verification" + (count > 1 ? "s" : "") 15876 + " for userId:" + userId); 15877 mIntentFilterVerifier.startVerifications(userId); 15878 } else { 15879 if (DEBUG_DOMAIN_VERIFICATION) { 15880 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15881 } 15882 } 15883 } 15884 15885 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15886 final ComponentName cn = filter.activity.getComponentName(); 15887 final String packageName = cn.getPackageName(); 15888 15889 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15890 packageName); 15891 if (ivi == null) { 15892 return true; 15893 } 15894 int status = ivi.getStatus(); 15895 switch (status) { 15896 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15897 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15898 return true; 15899 15900 default: 15901 // Nothing to do 15902 return false; 15903 } 15904 } 15905 15906 private static boolean isMultiArch(ApplicationInfo info) { 15907 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15908 } 15909 15910 private static boolean isExternal(PackageParser.Package pkg) { 15911 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15912 } 15913 15914 private static boolean isExternal(PackageSetting ps) { 15915 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15916 } 15917 15918 private static boolean isEphemeral(PackageParser.Package pkg) { 15919 return pkg.applicationInfo.isEphemeralApp(); 15920 } 15921 15922 private static boolean isEphemeral(PackageSetting ps) { 15923 return ps.pkg != null && isEphemeral(ps.pkg); 15924 } 15925 15926 private static boolean isSystemApp(PackageParser.Package pkg) { 15927 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15928 } 15929 15930 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15931 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15932 } 15933 15934 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15935 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15936 } 15937 15938 private static boolean isSystemApp(PackageSetting ps) { 15939 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15940 } 15941 15942 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15943 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15944 } 15945 15946 private int packageFlagsToInstallFlags(PackageSetting ps) { 15947 int installFlags = 0; 15948 if (isEphemeral(ps)) { 15949 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15950 } 15951 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15952 // This existing package was an external ASEC install when we have 15953 // the external flag without a UUID 15954 installFlags |= PackageManager.INSTALL_EXTERNAL; 15955 } 15956 if (ps.isForwardLocked()) { 15957 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15958 } 15959 return installFlags; 15960 } 15961 15962 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15963 if (isExternal(pkg)) { 15964 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15965 return StorageManager.UUID_PRIMARY_PHYSICAL; 15966 } else { 15967 return pkg.volumeUuid; 15968 } 15969 } else { 15970 return StorageManager.UUID_PRIVATE_INTERNAL; 15971 } 15972 } 15973 15974 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15975 if (isExternal(pkg)) { 15976 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15977 return mSettings.getExternalVersion(); 15978 } else { 15979 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15980 } 15981 } else { 15982 return mSettings.getInternalVersion(); 15983 } 15984 } 15985 15986 private void deleteTempPackageFiles() { 15987 final FilenameFilter filter = new FilenameFilter() { 15988 public boolean accept(File dir, String name) { 15989 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15990 } 15991 }; 15992 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15993 file.delete(); 15994 } 15995 } 15996 15997 @Override 15998 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15999 int flags) { 16000 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 16001 flags); 16002 } 16003 16004 @Override 16005 public void deletePackage(final String packageName, 16006 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16007 mContext.enforceCallingOrSelfPermission( 16008 android.Manifest.permission.DELETE_PACKAGES, null); 16009 Preconditions.checkNotNull(packageName); 16010 Preconditions.checkNotNull(observer); 16011 final int uid = Binder.getCallingUid(); 16012 if (!isOrphaned(packageName) 16013 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 16014 try { 16015 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16016 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16017 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16018 observer.onUserActionRequired(intent); 16019 } catch (RemoteException re) { 16020 } 16021 return; 16022 } 16023 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16024 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16025 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16026 mContext.enforceCallingOrSelfPermission( 16027 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16028 "deletePackage for user " + userId); 16029 } 16030 16031 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16032 try { 16033 observer.onPackageDeleted(packageName, 16034 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16035 } catch (RemoteException re) { 16036 } 16037 return; 16038 } 16039 16040 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 16041 try { 16042 observer.onPackageDeleted(packageName, 16043 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16044 } catch (RemoteException re) { 16045 } 16046 return; 16047 } 16048 16049 if (DEBUG_REMOVE) { 16050 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 16051 + " deleteAllUsers: " + deleteAllUsers ); 16052 } 16053 // Queue up an async operation since the package deletion may take a little while. 16054 mHandler.post(new Runnable() { 16055 public void run() { 16056 mHandler.removeCallbacks(this); 16057 int returnCode; 16058 if (!deleteAllUsers) { 16059 returnCode = deletePackageX(packageName, userId, deleteFlags); 16060 } else { 16061 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 16062 // If nobody is blocking uninstall, proceed with delete for all users 16063 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16064 returnCode = deletePackageX(packageName, userId, deleteFlags); 16065 } else { 16066 // Otherwise uninstall individually for users with blockUninstalls=false 16067 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16068 for (int userId : users) { 16069 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16070 returnCode = deletePackageX(packageName, userId, userFlags); 16071 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16072 Slog.w(TAG, "Package delete failed for user " + userId 16073 + ", returnCode " + returnCode); 16074 } 16075 } 16076 } 16077 // The app has only been marked uninstalled for certain users. 16078 // We still need to report that delete was blocked 16079 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16080 } 16081 } 16082 try { 16083 observer.onPackageDeleted(packageName, returnCode, null); 16084 } catch (RemoteException e) { 16085 Log.i(TAG, "Observer no longer exists."); 16086 } //end catch 16087 } //end run 16088 }); 16089 } 16090 16091 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 16092 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 16093 || callingUid == Process.SYSTEM_UID) { 16094 return true; 16095 } 16096 final int callingUserId = UserHandle.getUserId(callingUid); 16097 // If the caller installed the pkgName, then allow it to silently uninstall. 16098 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 16099 return true; 16100 } 16101 16102 // Allow package verifier to silently uninstall. 16103 if (mRequiredVerifierPackage != null && 16104 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 16105 return true; 16106 } 16107 16108 // Allow package uninstaller to silently uninstall. 16109 if (mRequiredUninstallerPackage != null && 16110 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 16111 return true; 16112 } 16113 16114 // Allow storage manager to silently uninstall. 16115 if (mStorageManagerPackage != null && 16116 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 16117 return true; 16118 } 16119 return false; 16120 } 16121 16122 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16123 int[] result = EMPTY_INT_ARRAY; 16124 for (int userId : userIds) { 16125 if (getBlockUninstallForUser(packageName, userId)) { 16126 result = ArrayUtils.appendInt(result, userId); 16127 } 16128 } 16129 return result; 16130 } 16131 16132 @Override 16133 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16134 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16135 } 16136 16137 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16138 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16139 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16140 try { 16141 if (dpm != null) { 16142 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16143 /* callingUserOnly =*/ false); 16144 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16145 : deviceOwnerComponentName.getPackageName(); 16146 // Does the package contains the device owner? 16147 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16148 // this check is probably not needed, since DO should be registered as a device 16149 // admin on some user too. (Original bug for this: b/17657954) 16150 if (packageName.equals(deviceOwnerPackageName)) { 16151 return true; 16152 } 16153 // Does it contain a device admin for any user? 16154 int[] users; 16155 if (userId == UserHandle.USER_ALL) { 16156 users = sUserManager.getUserIds(); 16157 } else { 16158 users = new int[]{userId}; 16159 } 16160 for (int i = 0; i < users.length; ++i) { 16161 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16162 return true; 16163 } 16164 } 16165 } 16166 } catch (RemoteException e) { 16167 } 16168 return false; 16169 } 16170 16171 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16172 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16173 } 16174 16175 /** 16176 * This method is an internal method that could be get invoked either 16177 * to delete an installed package or to clean up a failed installation. 16178 * After deleting an installed package, a broadcast is sent to notify any 16179 * listeners that the package has been removed. For cleaning up a failed 16180 * installation, the broadcast is not necessary since the package's 16181 * installation wouldn't have sent the initial broadcast either 16182 * The key steps in deleting a package are 16183 * deleting the package information in internal structures like mPackages, 16184 * deleting the packages base directories through installd 16185 * updating mSettings to reflect current status 16186 * persisting settings for later use 16187 * sending a broadcast if necessary 16188 */ 16189 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16190 final PackageRemovedInfo info = new PackageRemovedInfo(); 16191 final boolean res; 16192 16193 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16194 ? UserHandle.USER_ALL : userId; 16195 16196 if (isPackageDeviceAdmin(packageName, removeUser)) { 16197 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16198 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16199 } 16200 16201 PackageSetting uninstalledPs = null; 16202 16203 // for the uninstall-updates case and restricted profiles, remember the per- 16204 // user handle installed state 16205 int[] allUsers; 16206 synchronized (mPackages) { 16207 uninstalledPs = mSettings.mPackages.get(packageName); 16208 if (uninstalledPs == null) { 16209 Slog.w(TAG, "Not removing non-existent package " + packageName); 16210 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16211 } 16212 allUsers = sUserManager.getUserIds(); 16213 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16214 } 16215 16216 final int freezeUser; 16217 if (isUpdatedSystemApp(uninstalledPs) 16218 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16219 // We're downgrading a system app, which will apply to all users, so 16220 // freeze them all during the downgrade 16221 freezeUser = UserHandle.USER_ALL; 16222 } else { 16223 freezeUser = removeUser; 16224 } 16225 16226 synchronized (mInstallLock) { 16227 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16228 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16229 deleteFlags, "deletePackageX")) { 16230 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16231 deleteFlags | REMOVE_CHATTY, info, true, null); 16232 } 16233 synchronized (mPackages) { 16234 if (res) { 16235 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16236 } 16237 } 16238 } 16239 16240 if (res) { 16241 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16242 info.sendPackageRemovedBroadcasts(killApp); 16243 info.sendSystemPackageUpdatedBroadcasts(); 16244 info.sendSystemPackageAppearedBroadcasts(); 16245 } 16246 // Force a gc here. 16247 Runtime.getRuntime().gc(); 16248 // Delete the resources here after sending the broadcast to let 16249 // other processes clean up before deleting resources. 16250 if (info.args != null) { 16251 synchronized (mInstallLock) { 16252 info.args.doPostDeleteLI(true); 16253 } 16254 } 16255 16256 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16257 } 16258 16259 class PackageRemovedInfo { 16260 String removedPackage; 16261 int uid = -1; 16262 int removedAppId = -1; 16263 int[] origUsers; 16264 int[] removedUsers = null; 16265 boolean isRemovedPackageSystemUpdate = false; 16266 boolean isUpdate; 16267 boolean dataRemoved; 16268 boolean removedForAllUsers; 16269 // Clean up resources deleted packages. 16270 InstallArgs args = null; 16271 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16272 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16273 16274 void sendPackageRemovedBroadcasts(boolean killApp) { 16275 sendPackageRemovedBroadcastInternal(killApp); 16276 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16277 for (int i = 0; i < childCount; i++) { 16278 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16279 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16280 } 16281 } 16282 16283 void sendSystemPackageUpdatedBroadcasts() { 16284 if (isRemovedPackageSystemUpdate) { 16285 sendSystemPackageUpdatedBroadcastsInternal(); 16286 final int childCount = (removedChildPackages != null) 16287 ? removedChildPackages.size() : 0; 16288 for (int i = 0; i < childCount; i++) { 16289 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16290 if (childInfo.isRemovedPackageSystemUpdate) { 16291 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16292 } 16293 } 16294 } 16295 } 16296 16297 void sendSystemPackageAppearedBroadcasts() { 16298 final int packageCount = (appearedChildPackages != null) 16299 ? appearedChildPackages.size() : 0; 16300 for (int i = 0; i < packageCount; i++) { 16301 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16302 sendPackageAddedForNewUsers(installedInfo.name, true, 16303 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16304 } 16305 } 16306 16307 private void sendSystemPackageUpdatedBroadcastsInternal() { 16308 Bundle extras = new Bundle(2); 16309 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16310 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16311 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16312 extras, 0, null, null, null); 16313 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16314 extras, 0, null, null, null); 16315 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16316 null, 0, removedPackage, null, null); 16317 } 16318 16319 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16320 Bundle extras = new Bundle(2); 16321 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16322 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16323 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16324 if (isUpdate || isRemovedPackageSystemUpdate) { 16325 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16326 } 16327 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16328 if (removedPackage != null) { 16329 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16330 extras, 0, null, null, removedUsers); 16331 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16332 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16333 removedPackage, extras, 0, null, null, removedUsers); 16334 } 16335 } 16336 if (removedAppId >= 0) { 16337 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16338 removedUsers); 16339 } 16340 } 16341 } 16342 16343 /* 16344 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16345 * flag is not set, the data directory is removed as well. 16346 * make sure this flag is set for partially installed apps. If not its meaningless to 16347 * delete a partially installed application. 16348 */ 16349 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16350 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16351 String packageName = ps.name; 16352 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16353 // Retrieve object to delete permissions for shared user later on 16354 final PackageParser.Package deletedPkg; 16355 final PackageSetting deletedPs; 16356 // reader 16357 synchronized (mPackages) { 16358 deletedPkg = mPackages.get(packageName); 16359 deletedPs = mSettings.mPackages.get(packageName); 16360 if (outInfo != null) { 16361 outInfo.removedPackage = packageName; 16362 outInfo.removedUsers = deletedPs != null 16363 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16364 : null; 16365 } 16366 } 16367 16368 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16369 16370 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16371 final PackageParser.Package resolvedPkg; 16372 if (deletedPkg != null) { 16373 resolvedPkg = deletedPkg; 16374 } else { 16375 // We don't have a parsed package when it lives on an ejected 16376 // adopted storage device, so fake something together 16377 resolvedPkg = new PackageParser.Package(ps.name); 16378 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16379 } 16380 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16381 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16382 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16383 if (outInfo != null) { 16384 outInfo.dataRemoved = true; 16385 } 16386 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16387 } 16388 16389 // writer 16390 synchronized (mPackages) { 16391 if (deletedPs != null) { 16392 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16393 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16394 clearDefaultBrowserIfNeeded(packageName); 16395 if (outInfo != null) { 16396 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16397 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16398 } 16399 updatePermissionsLPw(deletedPs.name, null, 0); 16400 if (deletedPs.sharedUser != null) { 16401 // Remove permissions associated with package. Since runtime 16402 // permissions are per user we have to kill the removed package 16403 // or packages running under the shared user of the removed 16404 // package if revoking the permissions requested only by the removed 16405 // package is successful and this causes a change in gids. 16406 for (int userId : UserManagerService.getInstance().getUserIds()) { 16407 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16408 userId); 16409 if (userIdToKill == UserHandle.USER_ALL 16410 || userIdToKill >= UserHandle.USER_SYSTEM) { 16411 // If gids changed for this user, kill all affected packages. 16412 mHandler.post(new Runnable() { 16413 @Override 16414 public void run() { 16415 // This has to happen with no lock held. 16416 killApplication(deletedPs.name, deletedPs.appId, 16417 KILL_APP_REASON_GIDS_CHANGED); 16418 } 16419 }); 16420 break; 16421 } 16422 } 16423 } 16424 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16425 } 16426 // make sure to preserve per-user disabled state if this removal was just 16427 // a downgrade of a system app to the factory package 16428 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16429 if (DEBUG_REMOVE) { 16430 Slog.d(TAG, "Propagating install state across downgrade"); 16431 } 16432 for (int userId : allUserHandles) { 16433 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16434 if (DEBUG_REMOVE) { 16435 Slog.d(TAG, " user " + userId + " => " + installed); 16436 } 16437 ps.setInstalled(installed, userId); 16438 } 16439 } 16440 } 16441 // can downgrade to reader 16442 if (writeSettings) { 16443 // Save settings now 16444 mSettings.writeLPr(); 16445 } 16446 } 16447 if (outInfo != null) { 16448 // A user ID was deleted here. Go through all users and remove it 16449 // from KeyStore. 16450 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16451 } 16452 } 16453 16454 static boolean locationIsPrivileged(File path) { 16455 try { 16456 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16457 .getCanonicalPath(); 16458 return path.getCanonicalPath().startsWith(privilegedAppDir); 16459 } catch (IOException e) { 16460 Slog.e(TAG, "Unable to access code path " + path); 16461 } 16462 return false; 16463 } 16464 16465 /* 16466 * Tries to delete system package. 16467 */ 16468 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16469 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16470 boolean writeSettings) { 16471 if (deletedPs.parentPackageName != null) { 16472 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16473 return false; 16474 } 16475 16476 final boolean applyUserRestrictions 16477 = (allUserHandles != null) && (outInfo.origUsers != null); 16478 final PackageSetting disabledPs; 16479 // Confirm if the system package has been updated 16480 // An updated system app can be deleted. This will also have to restore 16481 // the system pkg from system partition 16482 // reader 16483 synchronized (mPackages) { 16484 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16485 } 16486 16487 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16488 + " disabledPs=" + disabledPs); 16489 16490 if (disabledPs == null) { 16491 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16492 return false; 16493 } else if (DEBUG_REMOVE) { 16494 Slog.d(TAG, "Deleting system pkg from data partition"); 16495 } 16496 16497 if (DEBUG_REMOVE) { 16498 if (applyUserRestrictions) { 16499 Slog.d(TAG, "Remembering install states:"); 16500 for (int userId : allUserHandles) { 16501 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16502 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16503 } 16504 } 16505 } 16506 16507 // Delete the updated package 16508 outInfo.isRemovedPackageSystemUpdate = true; 16509 if (outInfo.removedChildPackages != null) { 16510 final int childCount = (deletedPs.childPackageNames != null) 16511 ? deletedPs.childPackageNames.size() : 0; 16512 for (int i = 0; i < childCount; i++) { 16513 String childPackageName = deletedPs.childPackageNames.get(i); 16514 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16515 .contains(childPackageName)) { 16516 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16517 childPackageName); 16518 if (childInfo != null) { 16519 childInfo.isRemovedPackageSystemUpdate = true; 16520 } 16521 } 16522 } 16523 } 16524 16525 if (disabledPs.versionCode < deletedPs.versionCode) { 16526 // Delete data for downgrades 16527 flags &= ~PackageManager.DELETE_KEEP_DATA; 16528 } else { 16529 // Preserve data by setting flag 16530 flags |= PackageManager.DELETE_KEEP_DATA; 16531 } 16532 16533 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16534 outInfo, writeSettings, disabledPs.pkg); 16535 if (!ret) { 16536 return false; 16537 } 16538 16539 // writer 16540 synchronized (mPackages) { 16541 // Reinstate the old system package 16542 enableSystemPackageLPw(disabledPs.pkg); 16543 // Remove any native libraries from the upgraded package. 16544 removeNativeBinariesLI(deletedPs); 16545 } 16546 16547 // Install the system package 16548 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16549 int parseFlags = mDefParseFlags 16550 | PackageParser.PARSE_MUST_BE_APK 16551 | PackageParser.PARSE_IS_SYSTEM 16552 | PackageParser.PARSE_IS_SYSTEM_DIR; 16553 if (locationIsPrivileged(disabledPs.codePath)) { 16554 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16555 } 16556 16557 final PackageParser.Package newPkg; 16558 try { 16559 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16560 0 /* currentTime */, null); 16561 } catch (PackageManagerException e) { 16562 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16563 + e.getMessage()); 16564 return false; 16565 } 16566 try { 16567 // update shared libraries for the newly re-installed system package 16568 updateSharedLibrariesLPr(newPkg, null); 16569 } catch (PackageManagerException e) { 16570 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16571 } 16572 16573 prepareAppDataAfterInstallLIF(newPkg); 16574 16575 // writer 16576 synchronized (mPackages) { 16577 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16578 16579 // Propagate the permissions state as we do not want to drop on the floor 16580 // runtime permissions. The update permissions method below will take 16581 // care of removing obsolete permissions and grant install permissions. 16582 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16583 updatePermissionsLPw(newPkg.packageName, newPkg, 16584 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16585 16586 if (applyUserRestrictions) { 16587 if (DEBUG_REMOVE) { 16588 Slog.d(TAG, "Propagating install state across reinstall"); 16589 } 16590 for (int userId : allUserHandles) { 16591 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16592 if (DEBUG_REMOVE) { 16593 Slog.d(TAG, " user " + userId + " => " + installed); 16594 } 16595 ps.setInstalled(installed, userId); 16596 16597 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16598 } 16599 // Regardless of writeSettings we need to ensure that this restriction 16600 // state propagation is persisted 16601 mSettings.writeAllUsersPackageRestrictionsLPr(); 16602 } 16603 // can downgrade to reader here 16604 if (writeSettings) { 16605 mSettings.writeLPr(); 16606 } 16607 } 16608 return true; 16609 } 16610 16611 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16612 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16613 PackageRemovedInfo outInfo, boolean writeSettings, 16614 PackageParser.Package replacingPackage) { 16615 synchronized (mPackages) { 16616 if (outInfo != null) { 16617 outInfo.uid = ps.appId; 16618 } 16619 16620 if (outInfo != null && outInfo.removedChildPackages != null) { 16621 final int childCount = (ps.childPackageNames != null) 16622 ? ps.childPackageNames.size() : 0; 16623 for (int i = 0; i < childCount; i++) { 16624 String childPackageName = ps.childPackageNames.get(i); 16625 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16626 if (childPs == null) { 16627 return false; 16628 } 16629 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16630 childPackageName); 16631 if (childInfo != null) { 16632 childInfo.uid = childPs.appId; 16633 } 16634 } 16635 } 16636 } 16637 16638 // Delete package data from internal structures and also remove data if flag is set 16639 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16640 16641 // Delete the child packages data 16642 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16643 for (int i = 0; i < childCount; i++) { 16644 PackageSetting childPs; 16645 synchronized (mPackages) { 16646 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16647 } 16648 if (childPs != null) { 16649 PackageRemovedInfo childOutInfo = (outInfo != null 16650 && outInfo.removedChildPackages != null) 16651 ? outInfo.removedChildPackages.get(childPs.name) : null; 16652 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16653 && (replacingPackage != null 16654 && !replacingPackage.hasChildPackage(childPs.name)) 16655 ? flags & ~DELETE_KEEP_DATA : flags; 16656 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16657 deleteFlags, writeSettings); 16658 } 16659 } 16660 16661 // Delete application code and resources only for parent packages 16662 if (ps.parentPackageName == null) { 16663 if (deleteCodeAndResources && (outInfo != null)) { 16664 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16665 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16666 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16667 } 16668 } 16669 16670 return true; 16671 } 16672 16673 @Override 16674 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16675 int userId) { 16676 mContext.enforceCallingOrSelfPermission( 16677 android.Manifest.permission.DELETE_PACKAGES, null); 16678 synchronized (mPackages) { 16679 PackageSetting ps = mSettings.mPackages.get(packageName); 16680 if (ps == null) { 16681 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16682 return false; 16683 } 16684 if (!ps.getInstalled(userId)) { 16685 // Can't block uninstall for an app that is not installed or enabled. 16686 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16687 return false; 16688 } 16689 ps.setBlockUninstall(blockUninstall, userId); 16690 mSettings.writePackageRestrictionsLPr(userId); 16691 } 16692 return true; 16693 } 16694 16695 @Override 16696 public boolean getBlockUninstallForUser(String packageName, int userId) { 16697 synchronized (mPackages) { 16698 PackageSetting ps = mSettings.mPackages.get(packageName); 16699 if (ps == null) { 16700 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16701 return false; 16702 } 16703 return ps.getBlockUninstall(userId); 16704 } 16705 } 16706 16707 @Override 16708 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16709 int callingUid = Binder.getCallingUid(); 16710 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16711 throw new SecurityException( 16712 "setRequiredForSystemUser can only be run by the system or root"); 16713 } 16714 synchronized (mPackages) { 16715 PackageSetting ps = mSettings.mPackages.get(packageName); 16716 if (ps == null) { 16717 Log.w(TAG, "Package doesn't exist: " + packageName); 16718 return false; 16719 } 16720 if (systemUserApp) { 16721 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16722 } else { 16723 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16724 } 16725 mSettings.writeLPr(); 16726 } 16727 return true; 16728 } 16729 16730 /* 16731 * This method handles package deletion in general 16732 */ 16733 private boolean deletePackageLIF(String packageName, UserHandle user, 16734 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16735 PackageRemovedInfo outInfo, boolean writeSettings, 16736 PackageParser.Package replacingPackage) { 16737 if (packageName == null) { 16738 Slog.w(TAG, "Attempt to delete null packageName."); 16739 return false; 16740 } 16741 16742 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16743 16744 PackageSetting ps; 16745 16746 synchronized (mPackages) { 16747 ps = mSettings.mPackages.get(packageName); 16748 if (ps == null) { 16749 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16750 return false; 16751 } 16752 16753 if (ps.parentPackageName != null && (!isSystemApp(ps) 16754 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16755 if (DEBUG_REMOVE) { 16756 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16757 + ((user == null) ? UserHandle.USER_ALL : user)); 16758 } 16759 final int removedUserId = (user != null) ? user.getIdentifier() 16760 : UserHandle.USER_ALL; 16761 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16762 return false; 16763 } 16764 markPackageUninstalledForUserLPw(ps, user); 16765 scheduleWritePackageRestrictionsLocked(user); 16766 return true; 16767 } 16768 } 16769 16770 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16771 && user.getIdentifier() != UserHandle.USER_ALL)) { 16772 // The caller is asking that the package only be deleted for a single 16773 // user. To do this, we just mark its uninstalled state and delete 16774 // its data. If this is a system app, we only allow this to happen if 16775 // they have set the special DELETE_SYSTEM_APP which requests different 16776 // semantics than normal for uninstalling system apps. 16777 markPackageUninstalledForUserLPw(ps, user); 16778 16779 if (!isSystemApp(ps)) { 16780 // Do not uninstall the APK if an app should be cached 16781 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16782 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16783 // Other user still have this package installed, so all 16784 // we need to do is clear this user's data and save that 16785 // it is uninstalled. 16786 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16787 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16788 return false; 16789 } 16790 scheduleWritePackageRestrictionsLocked(user); 16791 return true; 16792 } else { 16793 // We need to set it back to 'installed' so the uninstall 16794 // broadcasts will be sent correctly. 16795 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16796 ps.setInstalled(true, user.getIdentifier()); 16797 } 16798 } else { 16799 // This is a system app, so we assume that the 16800 // other users still have this package installed, so all 16801 // we need to do is clear this user's data and save that 16802 // it is uninstalled. 16803 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16804 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16805 return false; 16806 } 16807 scheduleWritePackageRestrictionsLocked(user); 16808 return true; 16809 } 16810 } 16811 16812 // If we are deleting a composite package for all users, keep track 16813 // of result for each child. 16814 if (ps.childPackageNames != null && outInfo != null) { 16815 synchronized (mPackages) { 16816 final int childCount = ps.childPackageNames.size(); 16817 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16818 for (int i = 0; i < childCount; i++) { 16819 String childPackageName = ps.childPackageNames.get(i); 16820 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16821 childInfo.removedPackage = childPackageName; 16822 outInfo.removedChildPackages.put(childPackageName, childInfo); 16823 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16824 if (childPs != null) { 16825 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16826 } 16827 } 16828 } 16829 } 16830 16831 boolean ret = false; 16832 if (isSystemApp(ps)) { 16833 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16834 // When an updated system application is deleted we delete the existing resources 16835 // as well and fall back to existing code in system partition 16836 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16837 } else { 16838 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16839 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16840 outInfo, writeSettings, replacingPackage); 16841 } 16842 16843 // Take a note whether we deleted the package for all users 16844 if (outInfo != null) { 16845 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16846 if (outInfo.removedChildPackages != null) { 16847 synchronized (mPackages) { 16848 final int childCount = outInfo.removedChildPackages.size(); 16849 for (int i = 0; i < childCount; i++) { 16850 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16851 if (childInfo != null) { 16852 childInfo.removedForAllUsers = mPackages.get( 16853 childInfo.removedPackage) == null; 16854 } 16855 } 16856 } 16857 } 16858 // If we uninstalled an update to a system app there may be some 16859 // child packages that appeared as they are declared in the system 16860 // app but were not declared in the update. 16861 if (isSystemApp(ps)) { 16862 synchronized (mPackages) { 16863 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16864 final int childCount = (updatedPs.childPackageNames != null) 16865 ? updatedPs.childPackageNames.size() : 0; 16866 for (int i = 0; i < childCount; i++) { 16867 String childPackageName = updatedPs.childPackageNames.get(i); 16868 if (outInfo.removedChildPackages == null 16869 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16870 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16871 if (childPs == null) { 16872 continue; 16873 } 16874 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16875 installRes.name = childPackageName; 16876 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16877 installRes.pkg = mPackages.get(childPackageName); 16878 installRes.uid = childPs.pkg.applicationInfo.uid; 16879 if (outInfo.appearedChildPackages == null) { 16880 outInfo.appearedChildPackages = new ArrayMap<>(); 16881 } 16882 outInfo.appearedChildPackages.put(childPackageName, installRes); 16883 } 16884 } 16885 } 16886 } 16887 } 16888 16889 return ret; 16890 } 16891 16892 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16893 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16894 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16895 for (int nextUserId : userIds) { 16896 if (DEBUG_REMOVE) { 16897 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16898 } 16899 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16900 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16901 false /*hidden*/, false /*suspended*/, null, null, null, 16902 false /*blockUninstall*/, 16903 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16904 } 16905 } 16906 16907 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16908 PackageRemovedInfo outInfo) { 16909 final PackageParser.Package pkg; 16910 synchronized (mPackages) { 16911 pkg = mPackages.get(ps.name); 16912 } 16913 16914 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16915 : new int[] {userId}; 16916 for (int nextUserId : userIds) { 16917 if (DEBUG_REMOVE) { 16918 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16919 + nextUserId); 16920 } 16921 16922 destroyAppDataLIF(pkg, userId, 16923 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16924 destroyAppProfilesLIF(pkg, userId); 16925 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16926 schedulePackageCleaning(ps.name, nextUserId, false); 16927 synchronized (mPackages) { 16928 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16929 scheduleWritePackageRestrictionsLocked(nextUserId); 16930 } 16931 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16932 } 16933 } 16934 16935 if (outInfo != null) { 16936 outInfo.removedPackage = ps.name; 16937 outInfo.removedAppId = ps.appId; 16938 outInfo.removedUsers = userIds; 16939 } 16940 16941 return true; 16942 } 16943 16944 private final class ClearStorageConnection implements ServiceConnection { 16945 IMediaContainerService mContainerService; 16946 16947 @Override 16948 public void onServiceConnected(ComponentName name, IBinder service) { 16949 synchronized (this) { 16950 mContainerService = IMediaContainerService.Stub 16951 .asInterface(Binder.allowBlocking(service)); 16952 notifyAll(); 16953 } 16954 } 16955 16956 @Override 16957 public void onServiceDisconnected(ComponentName name) { 16958 } 16959 } 16960 16961 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16962 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16963 16964 final boolean mounted; 16965 if (Environment.isExternalStorageEmulated()) { 16966 mounted = true; 16967 } else { 16968 final String status = Environment.getExternalStorageState(); 16969 16970 mounted = status.equals(Environment.MEDIA_MOUNTED) 16971 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16972 } 16973 16974 if (!mounted) { 16975 return; 16976 } 16977 16978 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16979 int[] users; 16980 if (userId == UserHandle.USER_ALL) { 16981 users = sUserManager.getUserIds(); 16982 } else { 16983 users = new int[] { userId }; 16984 } 16985 final ClearStorageConnection conn = new ClearStorageConnection(); 16986 if (mContext.bindServiceAsUser( 16987 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16988 try { 16989 for (int curUser : users) { 16990 long timeout = SystemClock.uptimeMillis() + 5000; 16991 synchronized (conn) { 16992 long now; 16993 while (conn.mContainerService == null && 16994 (now = SystemClock.uptimeMillis()) < timeout) { 16995 try { 16996 conn.wait(timeout - now); 16997 } catch (InterruptedException e) { 16998 } 16999 } 17000 } 17001 if (conn.mContainerService == null) { 17002 return; 17003 } 17004 17005 final UserEnvironment userEnv = new UserEnvironment(curUser); 17006 clearDirectory(conn.mContainerService, 17007 userEnv.buildExternalStorageAppCacheDirs(packageName)); 17008 if (allData) { 17009 clearDirectory(conn.mContainerService, 17010 userEnv.buildExternalStorageAppDataDirs(packageName)); 17011 clearDirectory(conn.mContainerService, 17012 userEnv.buildExternalStorageAppMediaDirs(packageName)); 17013 } 17014 } 17015 } finally { 17016 mContext.unbindService(conn); 17017 } 17018 } 17019 } 17020 17021 @Override 17022 public void clearApplicationProfileData(String packageName) { 17023 enforceSystemOrRoot("Only the system can clear all profile data"); 17024 17025 final PackageParser.Package pkg; 17026 synchronized (mPackages) { 17027 pkg = mPackages.get(packageName); 17028 } 17029 17030 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 17031 synchronized (mInstallLock) { 17032 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 17033 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 17034 true /* removeBaseMarker */); 17035 } 17036 } 17037 } 17038 17039 @Override 17040 public void clearApplicationUserData(final String packageName, 17041 final IPackageDataObserver observer, final int userId) { 17042 mContext.enforceCallingOrSelfPermission( 17043 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 17044 17045 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17046 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 17047 17048 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 17049 throw new SecurityException("Cannot clear data for a protected package: " 17050 + packageName); 17051 } 17052 // Queue up an async operation since the package deletion may take a little while. 17053 mHandler.post(new Runnable() { 17054 public void run() { 17055 mHandler.removeCallbacks(this); 17056 final boolean succeeded; 17057 try (PackageFreezer freezer = freezePackage(packageName, 17058 "clearApplicationUserData")) { 17059 synchronized (mInstallLock) { 17060 succeeded = clearApplicationUserDataLIF(packageName, userId); 17061 } 17062 clearExternalStorageDataSync(packageName, userId, true); 17063 } 17064 if (succeeded) { 17065 // invoke DeviceStorageMonitor's update method to clear any notifications 17066 DeviceStorageMonitorInternal dsm = LocalServices 17067 .getService(DeviceStorageMonitorInternal.class); 17068 if (dsm != null) { 17069 dsm.checkMemory(); 17070 } 17071 } 17072 if(observer != null) { 17073 try { 17074 observer.onRemoveCompleted(packageName, succeeded); 17075 } catch (RemoteException e) { 17076 Log.i(TAG, "Observer no longer exists."); 17077 } 17078 } //end if observer 17079 } //end run 17080 }); 17081 } 17082 17083 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 17084 if (packageName == null) { 17085 Slog.w(TAG, "Attempt to delete null packageName."); 17086 return false; 17087 } 17088 17089 // Try finding details about the requested package 17090 PackageParser.Package pkg; 17091 synchronized (mPackages) { 17092 pkg = mPackages.get(packageName); 17093 if (pkg == null) { 17094 final PackageSetting ps = mSettings.mPackages.get(packageName); 17095 if (ps != null) { 17096 pkg = ps.pkg; 17097 } 17098 } 17099 17100 if (pkg == null) { 17101 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17102 return false; 17103 } 17104 17105 PackageSetting ps = (PackageSetting) pkg.mExtras; 17106 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17107 } 17108 17109 clearAppDataLIF(pkg, userId, 17110 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17111 17112 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17113 removeKeystoreDataIfNeeded(userId, appId); 17114 17115 UserManagerInternal umInternal = getUserManagerInternal(); 17116 final int flags; 17117 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17118 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17119 } else if (umInternal.isUserRunning(userId)) { 17120 flags = StorageManager.FLAG_STORAGE_DE; 17121 } else { 17122 flags = 0; 17123 } 17124 prepareAppDataContentsLIF(pkg, userId, flags); 17125 17126 return true; 17127 } 17128 17129 /** 17130 * Reverts user permission state changes (permissions and flags) in 17131 * all packages for a given user. 17132 * 17133 * @param userId The device user for which to do a reset. 17134 */ 17135 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17136 final int packageCount = mPackages.size(); 17137 for (int i = 0; i < packageCount; i++) { 17138 PackageParser.Package pkg = mPackages.valueAt(i); 17139 PackageSetting ps = (PackageSetting) pkg.mExtras; 17140 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17141 } 17142 } 17143 17144 private void resetNetworkPolicies(int userId) { 17145 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17146 } 17147 17148 /** 17149 * Reverts user permission state changes (permissions and flags). 17150 * 17151 * @param ps The package for which to reset. 17152 * @param userId The device user for which to do a reset. 17153 */ 17154 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17155 final PackageSetting ps, final int userId) { 17156 if (ps.pkg == null) { 17157 return; 17158 } 17159 17160 // These are flags that can change base on user actions. 17161 final int userSettableMask = FLAG_PERMISSION_USER_SET 17162 | FLAG_PERMISSION_USER_FIXED 17163 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17164 | FLAG_PERMISSION_REVIEW_REQUIRED; 17165 17166 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17167 | FLAG_PERMISSION_POLICY_FIXED; 17168 17169 boolean writeInstallPermissions = false; 17170 boolean writeRuntimePermissions = false; 17171 17172 final int permissionCount = ps.pkg.requestedPermissions.size(); 17173 for (int i = 0; i < permissionCount; i++) { 17174 String permission = ps.pkg.requestedPermissions.get(i); 17175 17176 BasePermission bp = mSettings.mPermissions.get(permission); 17177 if (bp == null) { 17178 continue; 17179 } 17180 17181 // If shared user we just reset the state to which only this app contributed. 17182 if (ps.sharedUser != null) { 17183 boolean used = false; 17184 final int packageCount = ps.sharedUser.packages.size(); 17185 for (int j = 0; j < packageCount; j++) { 17186 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17187 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17188 && pkg.pkg.requestedPermissions.contains(permission)) { 17189 used = true; 17190 break; 17191 } 17192 } 17193 if (used) { 17194 continue; 17195 } 17196 } 17197 17198 PermissionsState permissionsState = ps.getPermissionsState(); 17199 17200 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17201 17202 // Always clear the user settable flags. 17203 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17204 bp.name) != null; 17205 // If permission review is enabled and this is a legacy app, mark the 17206 // permission as requiring a review as this is the initial state. 17207 int flags = 0; 17208 if (mPermissionReviewRequired 17209 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17210 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17211 } 17212 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17213 if (hasInstallState) { 17214 writeInstallPermissions = true; 17215 } else { 17216 writeRuntimePermissions = true; 17217 } 17218 } 17219 17220 // Below is only runtime permission handling. 17221 if (!bp.isRuntime()) { 17222 continue; 17223 } 17224 17225 // Never clobber system or policy. 17226 if ((oldFlags & policyOrSystemFlags) != 0) { 17227 continue; 17228 } 17229 17230 // If this permission was granted by default, make sure it is. 17231 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17232 if (permissionsState.grantRuntimePermission(bp, userId) 17233 != PERMISSION_OPERATION_FAILURE) { 17234 writeRuntimePermissions = true; 17235 } 17236 // If permission review is enabled the permissions for a legacy apps 17237 // are represented as constantly granted runtime ones, so don't revoke. 17238 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17239 // Otherwise, reset the permission. 17240 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17241 switch (revokeResult) { 17242 case PERMISSION_OPERATION_SUCCESS: 17243 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17244 writeRuntimePermissions = true; 17245 final int appId = ps.appId; 17246 mHandler.post(new Runnable() { 17247 @Override 17248 public void run() { 17249 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17250 } 17251 }); 17252 } break; 17253 } 17254 } 17255 } 17256 17257 // Synchronously write as we are taking permissions away. 17258 if (writeRuntimePermissions) { 17259 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17260 } 17261 17262 // Synchronously write as we are taking permissions away. 17263 if (writeInstallPermissions) { 17264 mSettings.writeLPr(); 17265 } 17266 } 17267 17268 /** 17269 * Remove entries from the keystore daemon. Will only remove it if the 17270 * {@code appId} is valid. 17271 */ 17272 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17273 if (appId < 0) { 17274 return; 17275 } 17276 17277 final KeyStore keyStore = KeyStore.getInstance(); 17278 if (keyStore != null) { 17279 if (userId == UserHandle.USER_ALL) { 17280 for (final int individual : sUserManager.getUserIds()) { 17281 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17282 } 17283 } else { 17284 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17285 } 17286 } else { 17287 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17288 } 17289 } 17290 17291 @Override 17292 public void deleteApplicationCacheFiles(final String packageName, 17293 final IPackageDataObserver observer) { 17294 final int userId = UserHandle.getCallingUserId(); 17295 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17296 } 17297 17298 @Override 17299 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17300 final IPackageDataObserver observer) { 17301 mContext.enforceCallingOrSelfPermission( 17302 android.Manifest.permission.DELETE_CACHE_FILES, null); 17303 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17304 /* requireFullPermission= */ true, /* checkShell= */ false, 17305 "delete application cache files"); 17306 17307 final PackageParser.Package pkg; 17308 synchronized (mPackages) { 17309 pkg = mPackages.get(packageName); 17310 } 17311 17312 // Queue up an async operation since the package deletion may take a little while. 17313 mHandler.post(new Runnable() { 17314 public void run() { 17315 synchronized (mInstallLock) { 17316 final int flags = StorageManager.FLAG_STORAGE_DE 17317 | StorageManager.FLAG_STORAGE_CE; 17318 // We're only clearing cache files, so we don't care if the 17319 // app is unfrozen and still able to run 17320 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17321 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17322 } 17323 clearExternalStorageDataSync(packageName, userId, false); 17324 if (observer != null) { 17325 try { 17326 observer.onRemoveCompleted(packageName, true); 17327 } catch (RemoteException e) { 17328 Log.i(TAG, "Observer no longer exists."); 17329 } 17330 } 17331 } 17332 }); 17333 } 17334 17335 @Override 17336 public void getPackageSizeInfo(final String packageName, int userHandle, 17337 final IPackageStatsObserver observer) { 17338 mContext.enforceCallingOrSelfPermission( 17339 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17340 if (packageName == null) { 17341 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17342 } 17343 17344 PackageStats stats = new PackageStats(packageName, userHandle); 17345 17346 /* 17347 * Queue up an async operation since the package measurement may take a 17348 * little while. 17349 */ 17350 Message msg = mHandler.obtainMessage(INIT_COPY); 17351 msg.obj = new MeasureParams(stats, observer); 17352 mHandler.sendMessage(msg); 17353 } 17354 17355 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17356 final PackageSetting ps; 17357 synchronized (mPackages) { 17358 ps = mSettings.mPackages.get(packageName); 17359 if (ps == null) { 17360 Slog.w(TAG, "Failed to find settings for " + packageName); 17361 return false; 17362 } 17363 } 17364 try { 17365 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17366 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17367 ps.getCeDataInode(userId), ps.codePathString, stats); 17368 } catch (InstallerException e) { 17369 Slog.w(TAG, String.valueOf(e)); 17370 return false; 17371 } 17372 17373 // For now, ignore code size of packages on system partition 17374 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17375 stats.codeSize = 0; 17376 } 17377 17378 return true; 17379 } 17380 17381 private int getUidTargetSdkVersionLockedLPr(int uid) { 17382 Object obj = mSettings.getUserIdLPr(uid); 17383 if (obj instanceof SharedUserSetting) { 17384 final SharedUserSetting sus = (SharedUserSetting) obj; 17385 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17386 final Iterator<PackageSetting> it = sus.packages.iterator(); 17387 while (it.hasNext()) { 17388 final PackageSetting ps = it.next(); 17389 if (ps.pkg != null) { 17390 int v = ps.pkg.applicationInfo.targetSdkVersion; 17391 if (v < vers) vers = v; 17392 } 17393 } 17394 return vers; 17395 } else if (obj instanceof PackageSetting) { 17396 final PackageSetting ps = (PackageSetting) obj; 17397 if (ps.pkg != null) { 17398 return ps.pkg.applicationInfo.targetSdkVersion; 17399 } 17400 } 17401 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17402 } 17403 17404 @Override 17405 public void addPreferredActivity(IntentFilter filter, int match, 17406 ComponentName[] set, ComponentName activity, int userId) { 17407 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17408 "Adding preferred"); 17409 } 17410 17411 private void addPreferredActivityInternal(IntentFilter filter, int match, 17412 ComponentName[] set, ComponentName activity, boolean always, int userId, 17413 String opname) { 17414 // writer 17415 int callingUid = Binder.getCallingUid(); 17416 enforceCrossUserPermission(callingUid, userId, 17417 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17418 if (filter.countActions() == 0) { 17419 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17420 return; 17421 } 17422 synchronized (mPackages) { 17423 if (mContext.checkCallingOrSelfPermission( 17424 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17425 != PackageManager.PERMISSION_GRANTED) { 17426 if (getUidTargetSdkVersionLockedLPr(callingUid) 17427 < Build.VERSION_CODES.FROYO) { 17428 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17429 + callingUid); 17430 return; 17431 } 17432 mContext.enforceCallingOrSelfPermission( 17433 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17434 } 17435 17436 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17437 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17438 + userId + ":"); 17439 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17440 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17441 scheduleWritePackageRestrictionsLocked(userId); 17442 postPreferredActivityChangedBroadcast(userId); 17443 } 17444 } 17445 17446 private void postPreferredActivityChangedBroadcast(int userId) { 17447 mHandler.post(() -> { 17448 final IActivityManager am = ActivityManager.getService(); 17449 if (am == null) { 17450 return; 17451 } 17452 17453 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17454 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17455 try { 17456 am.broadcastIntent(null, intent, null, null, 17457 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17458 null, false, false, userId); 17459 } catch (RemoteException e) { 17460 } 17461 }); 17462 } 17463 17464 @Override 17465 public void replacePreferredActivity(IntentFilter filter, int match, 17466 ComponentName[] set, ComponentName activity, int userId) { 17467 if (filter.countActions() != 1) { 17468 throw new IllegalArgumentException( 17469 "replacePreferredActivity expects filter to have only 1 action."); 17470 } 17471 if (filter.countDataAuthorities() != 0 17472 || filter.countDataPaths() != 0 17473 || filter.countDataSchemes() > 1 17474 || filter.countDataTypes() != 0) { 17475 throw new IllegalArgumentException( 17476 "replacePreferredActivity expects filter to have no data authorities, " + 17477 "paths, or types; and at most one scheme."); 17478 } 17479 17480 final int callingUid = Binder.getCallingUid(); 17481 enforceCrossUserPermission(callingUid, userId, 17482 true /* requireFullPermission */, false /* checkShell */, 17483 "replace preferred activity"); 17484 synchronized (mPackages) { 17485 if (mContext.checkCallingOrSelfPermission( 17486 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17487 != PackageManager.PERMISSION_GRANTED) { 17488 if (getUidTargetSdkVersionLockedLPr(callingUid) 17489 < Build.VERSION_CODES.FROYO) { 17490 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17491 + Binder.getCallingUid()); 17492 return; 17493 } 17494 mContext.enforceCallingOrSelfPermission( 17495 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17496 } 17497 17498 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17499 if (pir != null) { 17500 // Get all of the existing entries that exactly match this filter. 17501 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17502 if (existing != null && existing.size() == 1) { 17503 PreferredActivity cur = existing.get(0); 17504 if (DEBUG_PREFERRED) { 17505 Slog.i(TAG, "Checking replace of preferred:"); 17506 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17507 if (!cur.mPref.mAlways) { 17508 Slog.i(TAG, " -- CUR; not mAlways!"); 17509 } else { 17510 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17511 Slog.i(TAG, " -- CUR: mSet=" 17512 + Arrays.toString(cur.mPref.mSetComponents)); 17513 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17514 Slog.i(TAG, " -- NEW: mMatch=" 17515 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17516 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17517 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17518 } 17519 } 17520 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17521 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17522 && cur.mPref.sameSet(set)) { 17523 // Setting the preferred activity to what it happens to be already 17524 if (DEBUG_PREFERRED) { 17525 Slog.i(TAG, "Replacing with same preferred activity " 17526 + cur.mPref.mShortComponent + " for user " 17527 + userId + ":"); 17528 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17529 } 17530 return; 17531 } 17532 } 17533 17534 if (existing != null) { 17535 if (DEBUG_PREFERRED) { 17536 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17537 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17538 } 17539 for (int i = 0; i < existing.size(); i++) { 17540 PreferredActivity pa = existing.get(i); 17541 if (DEBUG_PREFERRED) { 17542 Slog.i(TAG, "Removing existing preferred activity " 17543 + pa.mPref.mComponent + ":"); 17544 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17545 } 17546 pir.removeFilter(pa); 17547 } 17548 } 17549 } 17550 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17551 "Replacing preferred"); 17552 } 17553 } 17554 17555 @Override 17556 public void clearPackagePreferredActivities(String packageName) { 17557 final int uid = Binder.getCallingUid(); 17558 // writer 17559 synchronized (mPackages) { 17560 PackageParser.Package pkg = mPackages.get(packageName); 17561 if (pkg == null || pkg.applicationInfo.uid != uid) { 17562 if (mContext.checkCallingOrSelfPermission( 17563 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17564 != PackageManager.PERMISSION_GRANTED) { 17565 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17566 < Build.VERSION_CODES.FROYO) { 17567 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17568 + Binder.getCallingUid()); 17569 return; 17570 } 17571 mContext.enforceCallingOrSelfPermission( 17572 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17573 } 17574 } 17575 17576 int user = UserHandle.getCallingUserId(); 17577 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17578 scheduleWritePackageRestrictionsLocked(user); 17579 } 17580 } 17581 } 17582 17583 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17584 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17585 ArrayList<PreferredActivity> removed = null; 17586 boolean changed = false; 17587 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17588 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17589 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17590 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17591 continue; 17592 } 17593 Iterator<PreferredActivity> it = pir.filterIterator(); 17594 while (it.hasNext()) { 17595 PreferredActivity pa = it.next(); 17596 // Mark entry for removal only if it matches the package name 17597 // and the entry is of type "always". 17598 if (packageName == null || 17599 (pa.mPref.mComponent.getPackageName().equals(packageName) 17600 && pa.mPref.mAlways)) { 17601 if (removed == null) { 17602 removed = new ArrayList<PreferredActivity>(); 17603 } 17604 removed.add(pa); 17605 } 17606 } 17607 if (removed != null) { 17608 for (int j=0; j<removed.size(); j++) { 17609 PreferredActivity pa = removed.get(j); 17610 pir.removeFilter(pa); 17611 } 17612 changed = true; 17613 } 17614 } 17615 if (changed) { 17616 postPreferredActivityChangedBroadcast(userId); 17617 } 17618 return changed; 17619 } 17620 17621 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17622 private void clearIntentFilterVerificationsLPw(int userId) { 17623 final int packageCount = mPackages.size(); 17624 for (int i = 0; i < packageCount; i++) { 17625 PackageParser.Package pkg = mPackages.valueAt(i); 17626 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17627 } 17628 } 17629 17630 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17631 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17632 if (userId == UserHandle.USER_ALL) { 17633 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17634 sUserManager.getUserIds())) { 17635 for (int oneUserId : sUserManager.getUserIds()) { 17636 scheduleWritePackageRestrictionsLocked(oneUserId); 17637 } 17638 } 17639 } else { 17640 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17641 scheduleWritePackageRestrictionsLocked(userId); 17642 } 17643 } 17644 } 17645 17646 void clearDefaultBrowserIfNeeded(String packageName) { 17647 for (int oneUserId : sUserManager.getUserIds()) { 17648 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17649 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17650 if (packageName.equals(defaultBrowserPackageName)) { 17651 setDefaultBrowserPackageName(null, oneUserId); 17652 } 17653 } 17654 } 17655 17656 @Override 17657 public void resetApplicationPreferences(int userId) { 17658 mContext.enforceCallingOrSelfPermission( 17659 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17660 final long identity = Binder.clearCallingIdentity(); 17661 // writer 17662 try { 17663 synchronized (mPackages) { 17664 clearPackagePreferredActivitiesLPw(null, userId); 17665 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17666 // TODO: We have to reset the default SMS and Phone. This requires 17667 // significant refactoring to keep all default apps in the package 17668 // manager (cleaner but more work) or have the services provide 17669 // callbacks to the package manager to request a default app reset. 17670 applyFactoryDefaultBrowserLPw(userId); 17671 clearIntentFilterVerificationsLPw(userId); 17672 primeDomainVerificationsLPw(userId); 17673 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17674 scheduleWritePackageRestrictionsLocked(userId); 17675 } 17676 resetNetworkPolicies(userId); 17677 } finally { 17678 Binder.restoreCallingIdentity(identity); 17679 } 17680 } 17681 17682 @Override 17683 public int getPreferredActivities(List<IntentFilter> outFilters, 17684 List<ComponentName> outActivities, String packageName) { 17685 17686 int num = 0; 17687 final int userId = UserHandle.getCallingUserId(); 17688 // reader 17689 synchronized (mPackages) { 17690 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17691 if (pir != null) { 17692 final Iterator<PreferredActivity> it = pir.filterIterator(); 17693 while (it.hasNext()) { 17694 final PreferredActivity pa = it.next(); 17695 if (packageName == null 17696 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17697 && pa.mPref.mAlways)) { 17698 if (outFilters != null) { 17699 outFilters.add(new IntentFilter(pa)); 17700 } 17701 if (outActivities != null) { 17702 outActivities.add(pa.mPref.mComponent); 17703 } 17704 } 17705 } 17706 } 17707 } 17708 17709 return num; 17710 } 17711 17712 @Override 17713 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17714 int userId) { 17715 int callingUid = Binder.getCallingUid(); 17716 if (callingUid != Process.SYSTEM_UID) { 17717 throw new SecurityException( 17718 "addPersistentPreferredActivity can only be run by the system"); 17719 } 17720 if (filter.countActions() == 0) { 17721 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17722 return; 17723 } 17724 synchronized (mPackages) { 17725 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17726 ":"); 17727 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17728 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17729 new PersistentPreferredActivity(filter, activity)); 17730 scheduleWritePackageRestrictionsLocked(userId); 17731 postPreferredActivityChangedBroadcast(userId); 17732 } 17733 } 17734 17735 @Override 17736 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17737 int callingUid = Binder.getCallingUid(); 17738 if (callingUid != Process.SYSTEM_UID) { 17739 throw new SecurityException( 17740 "clearPackagePersistentPreferredActivities can only be run by the system"); 17741 } 17742 ArrayList<PersistentPreferredActivity> removed = null; 17743 boolean changed = false; 17744 synchronized (mPackages) { 17745 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17746 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17747 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17748 .valueAt(i); 17749 if (userId != thisUserId) { 17750 continue; 17751 } 17752 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17753 while (it.hasNext()) { 17754 PersistentPreferredActivity ppa = it.next(); 17755 // Mark entry for removal only if it matches the package name. 17756 if (ppa.mComponent.getPackageName().equals(packageName)) { 17757 if (removed == null) { 17758 removed = new ArrayList<PersistentPreferredActivity>(); 17759 } 17760 removed.add(ppa); 17761 } 17762 } 17763 if (removed != null) { 17764 for (int j=0; j<removed.size(); j++) { 17765 PersistentPreferredActivity ppa = removed.get(j); 17766 ppir.removeFilter(ppa); 17767 } 17768 changed = true; 17769 } 17770 } 17771 17772 if (changed) { 17773 scheduleWritePackageRestrictionsLocked(userId); 17774 postPreferredActivityChangedBroadcast(userId); 17775 } 17776 } 17777 } 17778 17779 /** 17780 * Common machinery for picking apart a restored XML blob and passing 17781 * it to a caller-supplied functor to be applied to the running system. 17782 */ 17783 private void restoreFromXml(XmlPullParser parser, int userId, 17784 String expectedStartTag, BlobXmlRestorer functor) 17785 throws IOException, XmlPullParserException { 17786 int type; 17787 while ((type = parser.next()) != XmlPullParser.START_TAG 17788 && type != XmlPullParser.END_DOCUMENT) { 17789 } 17790 if (type != XmlPullParser.START_TAG) { 17791 // oops didn't find a start tag?! 17792 if (DEBUG_BACKUP) { 17793 Slog.e(TAG, "Didn't find start tag during restore"); 17794 } 17795 return; 17796 } 17797Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17798 // this is supposed to be TAG_PREFERRED_BACKUP 17799 if (!expectedStartTag.equals(parser.getName())) { 17800 if (DEBUG_BACKUP) { 17801 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17802 } 17803 return; 17804 } 17805 17806 // skip interfering stuff, then we're aligned with the backing implementation 17807 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17808Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17809 functor.apply(parser, userId); 17810 } 17811 17812 private interface BlobXmlRestorer { 17813 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17814 } 17815 17816 /** 17817 * Non-Binder method, support for the backup/restore mechanism: write the 17818 * full set of preferred activities in its canonical XML format. Returns the 17819 * XML output as a byte array, or null if there is none. 17820 */ 17821 @Override 17822 public byte[] getPreferredActivityBackup(int userId) { 17823 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17824 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17825 } 17826 17827 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17828 try { 17829 final XmlSerializer serializer = new FastXmlSerializer(); 17830 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17831 serializer.startDocument(null, true); 17832 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17833 17834 synchronized (mPackages) { 17835 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17836 } 17837 17838 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17839 serializer.endDocument(); 17840 serializer.flush(); 17841 } catch (Exception e) { 17842 if (DEBUG_BACKUP) { 17843 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17844 } 17845 return null; 17846 } 17847 17848 return dataStream.toByteArray(); 17849 } 17850 17851 @Override 17852 public void restorePreferredActivities(byte[] backup, int userId) { 17853 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17854 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17855 } 17856 17857 try { 17858 final XmlPullParser parser = Xml.newPullParser(); 17859 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17860 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17861 new BlobXmlRestorer() { 17862 @Override 17863 public void apply(XmlPullParser parser, int userId) 17864 throws XmlPullParserException, IOException { 17865 synchronized (mPackages) { 17866 mSettings.readPreferredActivitiesLPw(parser, userId); 17867 } 17868 } 17869 } ); 17870 } catch (Exception e) { 17871 if (DEBUG_BACKUP) { 17872 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17873 } 17874 } 17875 } 17876 17877 /** 17878 * Non-Binder method, support for the backup/restore mechanism: write the 17879 * default browser (etc) settings in its canonical XML format. Returns the default 17880 * browser XML representation as a byte array, or null if there is none. 17881 */ 17882 @Override 17883 public byte[] getDefaultAppsBackup(int userId) { 17884 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17885 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17886 } 17887 17888 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17889 try { 17890 final XmlSerializer serializer = new FastXmlSerializer(); 17891 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17892 serializer.startDocument(null, true); 17893 serializer.startTag(null, TAG_DEFAULT_APPS); 17894 17895 synchronized (mPackages) { 17896 mSettings.writeDefaultAppsLPr(serializer, userId); 17897 } 17898 17899 serializer.endTag(null, TAG_DEFAULT_APPS); 17900 serializer.endDocument(); 17901 serializer.flush(); 17902 } catch (Exception e) { 17903 if (DEBUG_BACKUP) { 17904 Slog.e(TAG, "Unable to write default apps for backup", e); 17905 } 17906 return null; 17907 } 17908 17909 return dataStream.toByteArray(); 17910 } 17911 17912 @Override 17913 public void restoreDefaultApps(byte[] backup, int userId) { 17914 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17915 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17916 } 17917 17918 try { 17919 final XmlPullParser parser = Xml.newPullParser(); 17920 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17921 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17922 new BlobXmlRestorer() { 17923 @Override 17924 public void apply(XmlPullParser parser, int userId) 17925 throws XmlPullParserException, IOException { 17926 synchronized (mPackages) { 17927 mSettings.readDefaultAppsLPw(parser, userId); 17928 } 17929 } 17930 } ); 17931 } catch (Exception e) { 17932 if (DEBUG_BACKUP) { 17933 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17934 } 17935 } 17936 } 17937 17938 @Override 17939 public byte[] getIntentFilterVerificationBackup(int userId) { 17940 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17941 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17942 } 17943 17944 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17945 try { 17946 final XmlSerializer serializer = new FastXmlSerializer(); 17947 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17948 serializer.startDocument(null, true); 17949 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17950 17951 synchronized (mPackages) { 17952 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17953 } 17954 17955 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17956 serializer.endDocument(); 17957 serializer.flush(); 17958 } catch (Exception e) { 17959 if (DEBUG_BACKUP) { 17960 Slog.e(TAG, "Unable to write default apps for backup", e); 17961 } 17962 return null; 17963 } 17964 17965 return dataStream.toByteArray(); 17966 } 17967 17968 @Override 17969 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17970 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17971 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17972 } 17973 17974 try { 17975 final XmlPullParser parser = Xml.newPullParser(); 17976 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17977 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17978 new BlobXmlRestorer() { 17979 @Override 17980 public void apply(XmlPullParser parser, int userId) 17981 throws XmlPullParserException, IOException { 17982 synchronized (mPackages) { 17983 mSettings.readAllDomainVerificationsLPr(parser, userId); 17984 mSettings.writeLPr(); 17985 } 17986 } 17987 } ); 17988 } catch (Exception e) { 17989 if (DEBUG_BACKUP) { 17990 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17991 } 17992 } 17993 } 17994 17995 @Override 17996 public byte[] getPermissionGrantBackup(int userId) { 17997 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17998 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17999 } 18000 18001 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18002 try { 18003 final XmlSerializer serializer = new FastXmlSerializer(); 18004 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18005 serializer.startDocument(null, true); 18006 serializer.startTag(null, TAG_PERMISSION_BACKUP); 18007 18008 synchronized (mPackages) { 18009 serializeRuntimePermissionGrantsLPr(serializer, userId); 18010 } 18011 18012 serializer.endTag(null, TAG_PERMISSION_BACKUP); 18013 serializer.endDocument(); 18014 serializer.flush(); 18015 } catch (Exception e) { 18016 if (DEBUG_BACKUP) { 18017 Slog.e(TAG, "Unable to write default apps for backup", e); 18018 } 18019 return null; 18020 } 18021 18022 return dataStream.toByteArray(); 18023 } 18024 18025 @Override 18026 public void restorePermissionGrants(byte[] backup, int userId) { 18027 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18028 throw new SecurityException("Only the system may call restorePermissionGrants()"); 18029 } 18030 18031 try { 18032 final XmlPullParser parser = Xml.newPullParser(); 18033 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18034 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 18035 new BlobXmlRestorer() { 18036 @Override 18037 public void apply(XmlPullParser parser, int userId) 18038 throws XmlPullParserException, IOException { 18039 synchronized (mPackages) { 18040 processRestoredPermissionGrantsLPr(parser, userId); 18041 } 18042 } 18043 } ); 18044 } catch (Exception e) { 18045 if (DEBUG_BACKUP) { 18046 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18047 } 18048 } 18049 } 18050 18051 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 18052 throws IOException { 18053 serializer.startTag(null, TAG_ALL_GRANTS); 18054 18055 final int N = mSettings.mPackages.size(); 18056 for (int i = 0; i < N; i++) { 18057 final PackageSetting ps = mSettings.mPackages.valueAt(i); 18058 boolean pkgGrantsKnown = false; 18059 18060 PermissionsState packagePerms = ps.getPermissionsState(); 18061 18062 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 18063 final int grantFlags = state.getFlags(); 18064 // only look at grants that are not system/policy fixed 18065 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 18066 final boolean isGranted = state.isGranted(); 18067 // And only back up the user-twiddled state bits 18068 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 18069 final String packageName = mSettings.mPackages.keyAt(i); 18070 if (!pkgGrantsKnown) { 18071 serializer.startTag(null, TAG_GRANT); 18072 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 18073 pkgGrantsKnown = true; 18074 } 18075 18076 final boolean userSet = 18077 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 18078 final boolean userFixed = 18079 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 18080 final boolean revoke = 18081 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 18082 18083 serializer.startTag(null, TAG_PERMISSION); 18084 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 18085 if (isGranted) { 18086 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 18087 } 18088 if (userSet) { 18089 serializer.attribute(null, ATTR_USER_SET, "true"); 18090 } 18091 if (userFixed) { 18092 serializer.attribute(null, ATTR_USER_FIXED, "true"); 18093 } 18094 if (revoke) { 18095 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 18096 } 18097 serializer.endTag(null, TAG_PERMISSION); 18098 } 18099 } 18100 } 18101 18102 if (pkgGrantsKnown) { 18103 serializer.endTag(null, TAG_GRANT); 18104 } 18105 } 18106 18107 serializer.endTag(null, TAG_ALL_GRANTS); 18108 } 18109 18110 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 18111 throws XmlPullParserException, IOException { 18112 String pkgName = null; 18113 int outerDepth = parser.getDepth(); 18114 int type; 18115 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 18116 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 18117 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18118 continue; 18119 } 18120 18121 final String tagName = parser.getName(); 18122 if (tagName.equals(TAG_GRANT)) { 18123 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18124 if (DEBUG_BACKUP) { 18125 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18126 } 18127 } else if (tagName.equals(TAG_PERMISSION)) { 18128 18129 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18130 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18131 18132 int newFlagSet = 0; 18133 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18134 newFlagSet |= FLAG_PERMISSION_USER_SET; 18135 } 18136 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18137 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18138 } 18139 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18140 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18141 } 18142 if (DEBUG_BACKUP) { 18143 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18144 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18145 } 18146 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18147 if (ps != null) { 18148 // Already installed so we apply the grant immediately 18149 if (DEBUG_BACKUP) { 18150 Slog.v(TAG, " + already installed; applying"); 18151 } 18152 PermissionsState perms = ps.getPermissionsState(); 18153 BasePermission bp = mSettings.mPermissions.get(permName); 18154 if (bp != null) { 18155 if (isGranted) { 18156 perms.grantRuntimePermission(bp, userId); 18157 } 18158 if (newFlagSet != 0) { 18159 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18160 } 18161 } 18162 } else { 18163 // Need to wait for post-restore install to apply the grant 18164 if (DEBUG_BACKUP) { 18165 Slog.v(TAG, " - not yet installed; saving for later"); 18166 } 18167 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18168 isGranted, newFlagSet, userId); 18169 } 18170 } else { 18171 PackageManagerService.reportSettingsProblem(Log.WARN, 18172 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18173 XmlUtils.skipCurrentTag(parser); 18174 } 18175 } 18176 18177 scheduleWriteSettingsLocked(); 18178 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18179 } 18180 18181 @Override 18182 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18183 int sourceUserId, int targetUserId, int flags) { 18184 mContext.enforceCallingOrSelfPermission( 18185 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18186 int callingUid = Binder.getCallingUid(); 18187 enforceOwnerRights(ownerPackage, callingUid); 18188 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18189 if (intentFilter.countActions() == 0) { 18190 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18191 return; 18192 } 18193 synchronized (mPackages) { 18194 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18195 ownerPackage, targetUserId, flags); 18196 CrossProfileIntentResolver resolver = 18197 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18198 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18199 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18200 if (existing != null) { 18201 int size = existing.size(); 18202 for (int i = 0; i < size; i++) { 18203 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18204 return; 18205 } 18206 } 18207 } 18208 resolver.addFilter(newFilter); 18209 scheduleWritePackageRestrictionsLocked(sourceUserId); 18210 } 18211 } 18212 18213 @Override 18214 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18215 mContext.enforceCallingOrSelfPermission( 18216 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18217 int callingUid = Binder.getCallingUid(); 18218 enforceOwnerRights(ownerPackage, callingUid); 18219 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18220 synchronized (mPackages) { 18221 CrossProfileIntentResolver resolver = 18222 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18223 ArraySet<CrossProfileIntentFilter> set = 18224 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18225 for (CrossProfileIntentFilter filter : set) { 18226 if (filter.getOwnerPackage().equals(ownerPackage)) { 18227 resolver.removeFilter(filter); 18228 } 18229 } 18230 scheduleWritePackageRestrictionsLocked(sourceUserId); 18231 } 18232 } 18233 18234 // Enforcing that callingUid is owning pkg on userId 18235 private void enforceOwnerRights(String pkg, int callingUid) { 18236 // The system owns everything. 18237 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18238 return; 18239 } 18240 int callingUserId = UserHandle.getUserId(callingUid); 18241 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18242 if (pi == null) { 18243 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18244 + callingUserId); 18245 } 18246 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18247 throw new SecurityException("Calling uid " + callingUid 18248 + " does not own package " + pkg); 18249 } 18250 } 18251 18252 @Override 18253 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18254 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18255 } 18256 18257 private Intent getHomeIntent() { 18258 Intent intent = new Intent(Intent.ACTION_MAIN); 18259 intent.addCategory(Intent.CATEGORY_HOME); 18260 intent.addCategory(Intent.CATEGORY_DEFAULT); 18261 return intent; 18262 } 18263 18264 private IntentFilter getHomeFilter() { 18265 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18266 filter.addCategory(Intent.CATEGORY_HOME); 18267 filter.addCategory(Intent.CATEGORY_DEFAULT); 18268 return filter; 18269 } 18270 18271 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18272 int userId) { 18273 Intent intent = getHomeIntent(); 18274 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18275 PackageManager.GET_META_DATA, userId); 18276 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18277 true, false, false, userId); 18278 18279 allHomeCandidates.clear(); 18280 if (list != null) { 18281 for (ResolveInfo ri : list) { 18282 allHomeCandidates.add(ri); 18283 } 18284 } 18285 return (preferred == null || preferred.activityInfo == null) 18286 ? null 18287 : new ComponentName(preferred.activityInfo.packageName, 18288 preferred.activityInfo.name); 18289 } 18290 18291 @Override 18292 public void setHomeActivity(ComponentName comp, int userId) { 18293 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18294 getHomeActivitiesAsUser(homeActivities, userId); 18295 18296 boolean found = false; 18297 18298 final int size = homeActivities.size(); 18299 final ComponentName[] set = new ComponentName[size]; 18300 for (int i = 0; i < size; i++) { 18301 final ResolveInfo candidate = homeActivities.get(i); 18302 final ActivityInfo info = candidate.activityInfo; 18303 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18304 set[i] = activityName; 18305 if (!found && activityName.equals(comp)) { 18306 found = true; 18307 } 18308 } 18309 if (!found) { 18310 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18311 + userId); 18312 } 18313 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18314 set, comp, userId); 18315 } 18316 18317 private @Nullable String getSetupWizardPackageName() { 18318 final Intent intent = new Intent(Intent.ACTION_MAIN); 18319 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18320 18321 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18322 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18323 | MATCH_DISABLED_COMPONENTS, 18324 UserHandle.myUserId()); 18325 if (matches.size() == 1) { 18326 return matches.get(0).getComponentInfo().packageName; 18327 } else { 18328 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18329 + ": matches=" + matches); 18330 return null; 18331 } 18332 } 18333 18334 private @Nullable String getStorageManagerPackageName() { 18335 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18336 18337 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18338 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18339 | MATCH_DISABLED_COMPONENTS, 18340 UserHandle.myUserId()); 18341 if (matches.size() == 1) { 18342 return matches.get(0).getComponentInfo().packageName; 18343 } else { 18344 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18345 + matches.size() + ": matches=" + matches); 18346 return null; 18347 } 18348 } 18349 18350 @Override 18351 public void setApplicationEnabledSetting(String appPackageName, 18352 int newState, int flags, int userId, String callingPackage) { 18353 if (!sUserManager.exists(userId)) return; 18354 if (callingPackage == null) { 18355 callingPackage = Integer.toString(Binder.getCallingUid()); 18356 } 18357 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18358 } 18359 18360 @Override 18361 public void setComponentEnabledSetting(ComponentName componentName, 18362 int newState, int flags, int userId) { 18363 if (!sUserManager.exists(userId)) return; 18364 setEnabledSetting(componentName.getPackageName(), 18365 componentName.getClassName(), newState, flags, userId, null); 18366 } 18367 18368 private void setEnabledSetting(final String packageName, String className, int newState, 18369 final int flags, int userId, String callingPackage) { 18370 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18371 || newState == COMPONENT_ENABLED_STATE_ENABLED 18372 || newState == COMPONENT_ENABLED_STATE_DISABLED 18373 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18374 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18375 throw new IllegalArgumentException("Invalid new component state: " 18376 + newState); 18377 } 18378 PackageSetting pkgSetting; 18379 final int uid = Binder.getCallingUid(); 18380 final int permission; 18381 if (uid == Process.SYSTEM_UID) { 18382 permission = PackageManager.PERMISSION_GRANTED; 18383 } else { 18384 permission = mContext.checkCallingOrSelfPermission( 18385 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18386 } 18387 enforceCrossUserPermission(uid, userId, 18388 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18389 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18390 boolean sendNow = false; 18391 boolean isApp = (className == null); 18392 String componentName = isApp ? packageName : className; 18393 int packageUid = -1; 18394 ArrayList<String> components; 18395 18396 // writer 18397 synchronized (mPackages) { 18398 pkgSetting = mSettings.mPackages.get(packageName); 18399 if (pkgSetting == null) { 18400 if (className == null) { 18401 throw new IllegalArgumentException("Unknown package: " + packageName); 18402 } 18403 throw new IllegalArgumentException( 18404 "Unknown component: " + packageName + "/" + className); 18405 } 18406 } 18407 18408 // Limit who can change which apps 18409 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18410 // Don't allow apps that don't have permission to modify other apps 18411 if (!allowedByPermission) { 18412 throw new SecurityException( 18413 "Permission Denial: attempt to change component state from pid=" 18414 + Binder.getCallingPid() 18415 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18416 } 18417 // Don't allow changing protected packages. 18418 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18419 throw new SecurityException("Cannot disable a protected package: " + packageName); 18420 } 18421 } 18422 18423 synchronized (mPackages) { 18424 if (uid == Process.SHELL_UID 18425 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18426 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18427 // unless it is a test package. 18428 int oldState = pkgSetting.getEnabled(userId); 18429 if (className == null 18430 && 18431 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18432 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18433 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18434 && 18435 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18436 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18437 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18438 // ok 18439 } else { 18440 throw new SecurityException( 18441 "Shell cannot change component state for " + packageName + "/" 18442 + className + " to " + newState); 18443 } 18444 } 18445 if (className == null) { 18446 // We're dealing with an application/package level state change 18447 if (pkgSetting.getEnabled(userId) == newState) { 18448 // Nothing to do 18449 return; 18450 } 18451 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18452 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18453 // Don't care about who enables an app. 18454 callingPackage = null; 18455 } 18456 pkgSetting.setEnabled(newState, userId, callingPackage); 18457 // pkgSetting.pkg.mSetEnabled = newState; 18458 } else { 18459 // We're dealing with a component level state change 18460 // First, verify that this is a valid class name. 18461 PackageParser.Package pkg = pkgSetting.pkg; 18462 if (pkg == null || !pkg.hasComponentClassName(className)) { 18463 if (pkg != null && 18464 pkg.applicationInfo.targetSdkVersion >= 18465 Build.VERSION_CODES.JELLY_BEAN) { 18466 throw new IllegalArgumentException("Component class " + className 18467 + " does not exist in " + packageName); 18468 } else { 18469 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18470 + className + " does not exist in " + packageName); 18471 } 18472 } 18473 switch (newState) { 18474 case COMPONENT_ENABLED_STATE_ENABLED: 18475 if (!pkgSetting.enableComponentLPw(className, userId)) { 18476 return; 18477 } 18478 break; 18479 case COMPONENT_ENABLED_STATE_DISABLED: 18480 if (!pkgSetting.disableComponentLPw(className, userId)) { 18481 return; 18482 } 18483 break; 18484 case COMPONENT_ENABLED_STATE_DEFAULT: 18485 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18486 return; 18487 } 18488 break; 18489 default: 18490 Slog.e(TAG, "Invalid new component state: " + newState); 18491 return; 18492 } 18493 } 18494 scheduleWritePackageRestrictionsLocked(userId); 18495 components = mPendingBroadcasts.get(userId, packageName); 18496 final boolean newPackage = components == null; 18497 if (newPackage) { 18498 components = new ArrayList<String>(); 18499 } 18500 if (!components.contains(componentName)) { 18501 components.add(componentName); 18502 } 18503 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18504 sendNow = true; 18505 // Purge entry from pending broadcast list if another one exists already 18506 // since we are sending one right away. 18507 mPendingBroadcasts.remove(userId, packageName); 18508 } else { 18509 if (newPackage) { 18510 mPendingBroadcasts.put(userId, packageName, components); 18511 } 18512 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18513 // Schedule a message 18514 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18515 } 18516 } 18517 } 18518 18519 long callingId = Binder.clearCallingIdentity(); 18520 try { 18521 if (sendNow) { 18522 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18523 sendPackageChangedBroadcast(packageName, 18524 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18525 } 18526 } finally { 18527 Binder.restoreCallingIdentity(callingId); 18528 } 18529 } 18530 18531 @Override 18532 public void flushPackageRestrictionsAsUser(int userId) { 18533 if (!sUserManager.exists(userId)) { 18534 return; 18535 } 18536 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18537 false /* checkShell */, "flushPackageRestrictions"); 18538 synchronized (mPackages) { 18539 mSettings.writePackageRestrictionsLPr(userId); 18540 mDirtyUsers.remove(userId); 18541 if (mDirtyUsers.isEmpty()) { 18542 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18543 } 18544 } 18545 } 18546 18547 private void sendPackageChangedBroadcast(String packageName, 18548 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18549 if (DEBUG_INSTALL) 18550 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18551 + componentNames); 18552 Bundle extras = new Bundle(4); 18553 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18554 String nameList[] = new String[componentNames.size()]; 18555 componentNames.toArray(nameList); 18556 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18557 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18558 extras.putInt(Intent.EXTRA_UID, packageUid); 18559 // If this is not reporting a change of the overall package, then only send it 18560 // to registered receivers. We don't want to launch a swath of apps for every 18561 // little component state change. 18562 final int flags = !componentNames.contains(packageName) 18563 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18564 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18565 new int[] {UserHandle.getUserId(packageUid)}); 18566 } 18567 18568 @Override 18569 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18570 if (!sUserManager.exists(userId)) return; 18571 final int uid = Binder.getCallingUid(); 18572 final int permission = mContext.checkCallingOrSelfPermission( 18573 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18574 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18575 enforceCrossUserPermission(uid, userId, 18576 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18577 // writer 18578 synchronized (mPackages) { 18579 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18580 allowedByPermission, uid, userId)) { 18581 scheduleWritePackageRestrictionsLocked(userId); 18582 } 18583 } 18584 } 18585 18586 @Override 18587 public String getInstallerPackageName(String packageName) { 18588 // reader 18589 synchronized (mPackages) { 18590 return mSettings.getInstallerPackageNameLPr(packageName); 18591 } 18592 } 18593 18594 public boolean isOrphaned(String packageName) { 18595 // reader 18596 synchronized (mPackages) { 18597 return mSettings.isOrphaned(packageName); 18598 } 18599 } 18600 18601 @Override 18602 public int getApplicationEnabledSetting(String packageName, int userId) { 18603 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18604 int uid = Binder.getCallingUid(); 18605 enforceCrossUserPermission(uid, userId, 18606 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18607 // reader 18608 synchronized (mPackages) { 18609 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18610 } 18611 } 18612 18613 @Override 18614 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18615 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18616 int uid = Binder.getCallingUid(); 18617 enforceCrossUserPermission(uid, userId, 18618 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18619 // reader 18620 synchronized (mPackages) { 18621 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18622 } 18623 } 18624 18625 @Override 18626 public void enterSafeMode() { 18627 enforceSystemOrRoot("Only the system can request entering safe mode"); 18628 18629 if (!mSystemReady) { 18630 mSafeMode = true; 18631 } 18632 } 18633 18634 @Override 18635 public void systemReady() { 18636 mSystemReady = true; 18637 18638 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18639 // disabled after already being started. 18640 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18641 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18642 18643 // Read the compatibilty setting when the system is ready. 18644 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18645 mContext.getContentResolver(), 18646 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18647 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18648 if (DEBUG_SETTINGS) { 18649 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18650 } 18651 18652 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18653 18654 synchronized (mPackages) { 18655 // Verify that all of the preferred activity components actually 18656 // exist. It is possible for applications to be updated and at 18657 // that point remove a previously declared activity component that 18658 // had been set as a preferred activity. We try to clean this up 18659 // the next time we encounter that preferred activity, but it is 18660 // possible for the user flow to never be able to return to that 18661 // situation so here we do a sanity check to make sure we haven't 18662 // left any junk around. 18663 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18664 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18665 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18666 removed.clear(); 18667 for (PreferredActivity pa : pir.filterSet()) { 18668 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18669 removed.add(pa); 18670 } 18671 } 18672 if (removed.size() > 0) { 18673 for (int r=0; r<removed.size(); r++) { 18674 PreferredActivity pa = removed.get(r); 18675 Slog.w(TAG, "Removing dangling preferred activity: " 18676 + pa.mPref.mComponent); 18677 pir.removeFilter(pa); 18678 } 18679 mSettings.writePackageRestrictionsLPr( 18680 mSettings.mPreferredActivities.keyAt(i)); 18681 } 18682 } 18683 18684 for (int userId : UserManagerService.getInstance().getUserIds()) { 18685 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18686 grantPermissionsUserIds = ArrayUtils.appendInt( 18687 grantPermissionsUserIds, userId); 18688 } 18689 } 18690 } 18691 sUserManager.systemReady(); 18692 18693 // If we upgraded grant all default permissions before kicking off. 18694 for (int userId : grantPermissionsUserIds) { 18695 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18696 } 18697 18698 // If we did not grant default permissions, we preload from this the 18699 // default permission exceptions lazily to ensure we don't hit the 18700 // disk on a new user creation. 18701 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18702 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18703 } 18704 18705 // Kick off any messages waiting for system ready 18706 if (mPostSystemReadyMessages != null) { 18707 for (Message msg : mPostSystemReadyMessages) { 18708 msg.sendToTarget(); 18709 } 18710 mPostSystemReadyMessages = null; 18711 } 18712 18713 // Watch for external volumes that come and go over time 18714 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18715 storage.registerListener(mStorageListener); 18716 18717 mInstallerService.systemReady(); 18718 mPackageDexOptimizer.systemReady(); 18719 18720 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18721 StorageManagerInternal.class); 18722 StorageManagerInternal.addExternalStoragePolicy( 18723 new StorageManagerInternal.ExternalStorageMountPolicy() { 18724 @Override 18725 public int getMountMode(int uid, String packageName) { 18726 if (Process.isIsolated(uid)) { 18727 return Zygote.MOUNT_EXTERNAL_NONE; 18728 } 18729 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18730 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18731 } 18732 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18733 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18734 } 18735 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18736 return Zygote.MOUNT_EXTERNAL_READ; 18737 } 18738 return Zygote.MOUNT_EXTERNAL_WRITE; 18739 } 18740 18741 @Override 18742 public boolean hasExternalStorage(int uid, String packageName) { 18743 return true; 18744 } 18745 }); 18746 18747 // Now that we're mostly running, clean up stale users and apps 18748 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18749 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18750 } 18751 18752 @Override 18753 public boolean isSafeMode() { 18754 return mSafeMode; 18755 } 18756 18757 @Override 18758 public boolean hasSystemUidErrors() { 18759 return mHasSystemUidErrors; 18760 } 18761 18762 static String arrayToString(int[] array) { 18763 StringBuffer buf = new StringBuffer(128); 18764 buf.append('['); 18765 if (array != null) { 18766 for (int i=0; i<array.length; i++) { 18767 if (i > 0) buf.append(", "); 18768 buf.append(array[i]); 18769 } 18770 } 18771 buf.append(']'); 18772 return buf.toString(); 18773 } 18774 18775 static class DumpState { 18776 public static final int DUMP_LIBS = 1 << 0; 18777 public static final int DUMP_FEATURES = 1 << 1; 18778 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18779 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18780 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18781 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18782 public static final int DUMP_PERMISSIONS = 1 << 6; 18783 public static final int DUMP_PACKAGES = 1 << 7; 18784 public static final int DUMP_SHARED_USERS = 1 << 8; 18785 public static final int DUMP_MESSAGES = 1 << 9; 18786 public static final int DUMP_PROVIDERS = 1 << 10; 18787 public static final int DUMP_VERIFIERS = 1 << 11; 18788 public static final int DUMP_PREFERRED = 1 << 12; 18789 public static final int DUMP_PREFERRED_XML = 1 << 13; 18790 public static final int DUMP_KEYSETS = 1 << 14; 18791 public static final int DUMP_VERSION = 1 << 15; 18792 public static final int DUMP_INSTALLS = 1 << 16; 18793 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18794 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18795 public static final int DUMP_FROZEN = 1 << 19; 18796 public static final int DUMP_DEXOPT = 1 << 20; 18797 public static final int DUMP_COMPILER_STATS = 1 << 21; 18798 18799 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18800 18801 private int mTypes; 18802 18803 private int mOptions; 18804 18805 private boolean mTitlePrinted; 18806 18807 private SharedUserSetting mSharedUser; 18808 18809 public boolean isDumping(int type) { 18810 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18811 return true; 18812 } 18813 18814 return (mTypes & type) != 0; 18815 } 18816 18817 public void setDump(int type) { 18818 mTypes |= type; 18819 } 18820 18821 public boolean isOptionEnabled(int option) { 18822 return (mOptions & option) != 0; 18823 } 18824 18825 public void setOptionEnabled(int option) { 18826 mOptions |= option; 18827 } 18828 18829 public boolean onTitlePrinted() { 18830 final boolean printed = mTitlePrinted; 18831 mTitlePrinted = true; 18832 return printed; 18833 } 18834 18835 public boolean getTitlePrinted() { 18836 return mTitlePrinted; 18837 } 18838 18839 public void setTitlePrinted(boolean enabled) { 18840 mTitlePrinted = enabled; 18841 } 18842 18843 public SharedUserSetting getSharedUser() { 18844 return mSharedUser; 18845 } 18846 18847 public void setSharedUser(SharedUserSetting user) { 18848 mSharedUser = user; 18849 } 18850 } 18851 18852 @Override 18853 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18854 FileDescriptor err, String[] args, ShellCallback callback, 18855 ResultReceiver resultReceiver) { 18856 (new PackageManagerShellCommand(this)).exec( 18857 this, in, out, err, args, callback, resultReceiver); 18858 } 18859 18860 @Override 18861 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18862 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18863 != PackageManager.PERMISSION_GRANTED) { 18864 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18865 + Binder.getCallingPid() 18866 + ", uid=" + Binder.getCallingUid() 18867 + " without permission " 18868 + android.Manifest.permission.DUMP); 18869 return; 18870 } 18871 18872 DumpState dumpState = new DumpState(); 18873 boolean fullPreferred = false; 18874 boolean checkin = false; 18875 18876 String packageName = null; 18877 ArraySet<String> permissionNames = null; 18878 18879 int opti = 0; 18880 while (opti < args.length) { 18881 String opt = args[opti]; 18882 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18883 break; 18884 } 18885 opti++; 18886 18887 if ("-a".equals(opt)) { 18888 // Right now we only know how to print all. 18889 } else if ("-h".equals(opt)) { 18890 pw.println("Package manager dump options:"); 18891 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18892 pw.println(" --checkin: dump for a checkin"); 18893 pw.println(" -f: print details of intent filters"); 18894 pw.println(" -h: print this help"); 18895 pw.println(" cmd may be one of:"); 18896 pw.println(" l[ibraries]: list known shared libraries"); 18897 pw.println(" f[eatures]: list device features"); 18898 pw.println(" k[eysets]: print known keysets"); 18899 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18900 pw.println(" perm[issions]: dump permissions"); 18901 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18902 pw.println(" pref[erred]: print preferred package settings"); 18903 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18904 pw.println(" prov[iders]: dump content providers"); 18905 pw.println(" p[ackages]: dump installed packages"); 18906 pw.println(" s[hared-users]: dump shared user IDs"); 18907 pw.println(" m[essages]: print collected runtime messages"); 18908 pw.println(" v[erifiers]: print package verifier info"); 18909 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18910 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18911 pw.println(" version: print database version info"); 18912 pw.println(" write: write current settings now"); 18913 pw.println(" installs: details about install sessions"); 18914 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18915 pw.println(" dexopt: dump dexopt state"); 18916 pw.println(" compiler-stats: dump compiler statistics"); 18917 pw.println(" <package.name>: info about given package"); 18918 return; 18919 } else if ("--checkin".equals(opt)) { 18920 checkin = true; 18921 } else if ("-f".equals(opt)) { 18922 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18923 } else { 18924 pw.println("Unknown argument: " + opt + "; use -h for help"); 18925 } 18926 } 18927 18928 // Is the caller requesting to dump a particular piece of data? 18929 if (opti < args.length) { 18930 String cmd = args[opti]; 18931 opti++; 18932 // Is this a package name? 18933 if ("android".equals(cmd) || cmd.contains(".")) { 18934 packageName = cmd; 18935 // When dumping a single package, we always dump all of its 18936 // filter information since the amount of data will be reasonable. 18937 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18938 } else if ("check-permission".equals(cmd)) { 18939 if (opti >= args.length) { 18940 pw.println("Error: check-permission missing permission argument"); 18941 return; 18942 } 18943 String perm = args[opti]; 18944 opti++; 18945 if (opti >= args.length) { 18946 pw.println("Error: check-permission missing package argument"); 18947 return; 18948 } 18949 String pkg = args[opti]; 18950 opti++; 18951 int user = UserHandle.getUserId(Binder.getCallingUid()); 18952 if (opti < args.length) { 18953 try { 18954 user = Integer.parseInt(args[opti]); 18955 } catch (NumberFormatException e) { 18956 pw.println("Error: check-permission user argument is not a number: " 18957 + args[opti]); 18958 return; 18959 } 18960 } 18961 pw.println(checkPermission(perm, pkg, user)); 18962 return; 18963 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18964 dumpState.setDump(DumpState.DUMP_LIBS); 18965 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18966 dumpState.setDump(DumpState.DUMP_FEATURES); 18967 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18968 if (opti >= args.length) { 18969 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18970 | DumpState.DUMP_SERVICE_RESOLVERS 18971 | DumpState.DUMP_RECEIVER_RESOLVERS 18972 | DumpState.DUMP_CONTENT_RESOLVERS); 18973 } else { 18974 while (opti < args.length) { 18975 String name = args[opti]; 18976 if ("a".equals(name) || "activity".equals(name)) { 18977 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18978 } else if ("s".equals(name) || "service".equals(name)) { 18979 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18980 } else if ("r".equals(name) || "receiver".equals(name)) { 18981 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18982 } else if ("c".equals(name) || "content".equals(name)) { 18983 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18984 } else { 18985 pw.println("Error: unknown resolver table type: " + name); 18986 return; 18987 } 18988 opti++; 18989 } 18990 } 18991 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18992 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18993 } else if ("permission".equals(cmd)) { 18994 if (opti >= args.length) { 18995 pw.println("Error: permission requires permission name"); 18996 return; 18997 } 18998 permissionNames = new ArraySet<>(); 18999 while (opti < args.length) { 19000 permissionNames.add(args[opti]); 19001 opti++; 19002 } 19003 dumpState.setDump(DumpState.DUMP_PERMISSIONS 19004 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 19005 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 19006 dumpState.setDump(DumpState.DUMP_PREFERRED); 19007 } else if ("preferred-xml".equals(cmd)) { 19008 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 19009 if (opti < args.length && "--full".equals(args[opti])) { 19010 fullPreferred = true; 19011 opti++; 19012 } 19013 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 19014 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 19015 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 19016 dumpState.setDump(DumpState.DUMP_PACKAGES); 19017 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 19018 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 19019 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 19020 dumpState.setDump(DumpState.DUMP_PROVIDERS); 19021 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 19022 dumpState.setDump(DumpState.DUMP_MESSAGES); 19023 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 19024 dumpState.setDump(DumpState.DUMP_VERIFIERS); 19025 } else if ("i".equals(cmd) || "ifv".equals(cmd) 19026 || "intent-filter-verifiers".equals(cmd)) { 19027 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 19028 } else if ("version".equals(cmd)) { 19029 dumpState.setDump(DumpState.DUMP_VERSION); 19030 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 19031 dumpState.setDump(DumpState.DUMP_KEYSETS); 19032 } else if ("installs".equals(cmd)) { 19033 dumpState.setDump(DumpState.DUMP_INSTALLS); 19034 } else if ("frozen".equals(cmd)) { 19035 dumpState.setDump(DumpState.DUMP_FROZEN); 19036 } else if ("dexopt".equals(cmd)) { 19037 dumpState.setDump(DumpState.DUMP_DEXOPT); 19038 } else if ("compiler-stats".equals(cmd)) { 19039 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 19040 } else if ("write".equals(cmd)) { 19041 synchronized (mPackages) { 19042 mSettings.writeLPr(); 19043 pw.println("Settings written."); 19044 return; 19045 } 19046 } 19047 } 19048 19049 if (checkin) { 19050 pw.println("vers,1"); 19051 } 19052 19053 // reader 19054 synchronized (mPackages) { 19055 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 19056 if (!checkin) { 19057 if (dumpState.onTitlePrinted()) 19058 pw.println(); 19059 pw.println("Database versions:"); 19060 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 19061 } 19062 } 19063 19064 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 19065 if (!checkin) { 19066 if (dumpState.onTitlePrinted()) 19067 pw.println(); 19068 pw.println("Verifiers:"); 19069 pw.print(" Required: "); 19070 pw.print(mRequiredVerifierPackage); 19071 pw.print(" (uid="); 19072 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19073 UserHandle.USER_SYSTEM)); 19074 pw.println(")"); 19075 } else if (mRequiredVerifierPackage != null) { 19076 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 19077 pw.print(","); 19078 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19079 UserHandle.USER_SYSTEM)); 19080 } 19081 } 19082 19083 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 19084 packageName == null) { 19085 if (mIntentFilterVerifierComponent != null) { 19086 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 19087 if (!checkin) { 19088 if (dumpState.onTitlePrinted()) 19089 pw.println(); 19090 pw.println("Intent Filter Verifier:"); 19091 pw.print(" Using: "); 19092 pw.print(verifierPackageName); 19093 pw.print(" (uid="); 19094 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19095 UserHandle.USER_SYSTEM)); 19096 pw.println(")"); 19097 } else if (verifierPackageName != null) { 19098 pw.print("ifv,"); pw.print(verifierPackageName); 19099 pw.print(","); 19100 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19101 UserHandle.USER_SYSTEM)); 19102 } 19103 } else { 19104 pw.println(); 19105 pw.println("No Intent Filter Verifier available!"); 19106 } 19107 } 19108 19109 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 19110 boolean printedHeader = false; 19111 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 19112 while (it.hasNext()) { 19113 String name = it.next(); 19114 SharedLibraryEntry ent = mSharedLibraries.get(name); 19115 if (!checkin) { 19116 if (!printedHeader) { 19117 if (dumpState.onTitlePrinted()) 19118 pw.println(); 19119 pw.println("Libraries:"); 19120 printedHeader = true; 19121 } 19122 pw.print(" "); 19123 } else { 19124 pw.print("lib,"); 19125 } 19126 pw.print(name); 19127 if (!checkin) { 19128 pw.print(" -> "); 19129 } 19130 if (ent.path != null) { 19131 if (!checkin) { 19132 pw.print("(jar) "); 19133 pw.print(ent.path); 19134 } else { 19135 pw.print(",jar,"); 19136 pw.print(ent.path); 19137 } 19138 } else { 19139 if (!checkin) { 19140 pw.print("(apk) "); 19141 pw.print(ent.apk); 19142 } else { 19143 pw.print(",apk,"); 19144 pw.print(ent.apk); 19145 } 19146 } 19147 pw.println(); 19148 } 19149 } 19150 19151 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19152 if (dumpState.onTitlePrinted()) 19153 pw.println(); 19154 if (!checkin) { 19155 pw.println("Features:"); 19156 } 19157 19158 for (FeatureInfo feat : mAvailableFeatures.values()) { 19159 if (checkin) { 19160 pw.print("feat,"); 19161 pw.print(feat.name); 19162 pw.print(","); 19163 pw.println(feat.version); 19164 } else { 19165 pw.print(" "); 19166 pw.print(feat.name); 19167 if (feat.version > 0) { 19168 pw.print(" version="); 19169 pw.print(feat.version); 19170 } 19171 pw.println(); 19172 } 19173 } 19174 } 19175 19176 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19177 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19178 : "Activity Resolver Table:", " ", packageName, 19179 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19180 dumpState.setTitlePrinted(true); 19181 } 19182 } 19183 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19184 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19185 : "Receiver Resolver Table:", " ", packageName, 19186 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19187 dumpState.setTitlePrinted(true); 19188 } 19189 } 19190 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19191 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19192 : "Service Resolver Table:", " ", packageName, 19193 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19194 dumpState.setTitlePrinted(true); 19195 } 19196 } 19197 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19198 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19199 : "Provider Resolver Table:", " ", packageName, 19200 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19201 dumpState.setTitlePrinted(true); 19202 } 19203 } 19204 19205 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19206 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19207 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19208 int user = mSettings.mPreferredActivities.keyAt(i); 19209 if (pir.dump(pw, 19210 dumpState.getTitlePrinted() 19211 ? "\nPreferred Activities User " + user + ":" 19212 : "Preferred Activities User " + user + ":", " ", 19213 packageName, true, false)) { 19214 dumpState.setTitlePrinted(true); 19215 } 19216 } 19217 } 19218 19219 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19220 pw.flush(); 19221 FileOutputStream fout = new FileOutputStream(fd); 19222 BufferedOutputStream str = new BufferedOutputStream(fout); 19223 XmlSerializer serializer = new FastXmlSerializer(); 19224 try { 19225 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19226 serializer.startDocument(null, true); 19227 serializer.setFeature( 19228 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19229 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19230 serializer.endDocument(); 19231 serializer.flush(); 19232 } catch (IllegalArgumentException e) { 19233 pw.println("Failed writing: " + e); 19234 } catch (IllegalStateException e) { 19235 pw.println("Failed writing: " + e); 19236 } catch (IOException e) { 19237 pw.println("Failed writing: " + e); 19238 } 19239 } 19240 19241 if (!checkin 19242 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19243 && packageName == null) { 19244 pw.println(); 19245 int count = mSettings.mPackages.size(); 19246 if (count == 0) { 19247 pw.println("No applications!"); 19248 pw.println(); 19249 } else { 19250 final String prefix = " "; 19251 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19252 if (allPackageSettings.size() == 0) { 19253 pw.println("No domain preferred apps!"); 19254 pw.println(); 19255 } else { 19256 pw.println("App verification status:"); 19257 pw.println(); 19258 count = 0; 19259 for (PackageSetting ps : allPackageSettings) { 19260 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19261 if (ivi == null || ivi.getPackageName() == null) continue; 19262 pw.println(prefix + "Package: " + ivi.getPackageName()); 19263 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19264 pw.println(prefix + "Status: " + ivi.getStatusString()); 19265 pw.println(); 19266 count++; 19267 } 19268 if (count == 0) { 19269 pw.println(prefix + "No app verification established."); 19270 pw.println(); 19271 } 19272 for (int userId : sUserManager.getUserIds()) { 19273 pw.println("App linkages for user " + userId + ":"); 19274 pw.println(); 19275 count = 0; 19276 for (PackageSetting ps : allPackageSettings) { 19277 final long status = ps.getDomainVerificationStatusForUser(userId); 19278 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19279 continue; 19280 } 19281 pw.println(prefix + "Package: " + ps.name); 19282 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19283 String statusStr = IntentFilterVerificationInfo. 19284 getStatusStringFromValue(status); 19285 pw.println(prefix + "Status: " + statusStr); 19286 pw.println(); 19287 count++; 19288 } 19289 if (count == 0) { 19290 pw.println(prefix + "No configured app linkages."); 19291 pw.println(); 19292 } 19293 } 19294 } 19295 } 19296 } 19297 19298 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19299 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19300 if (packageName == null && permissionNames == null) { 19301 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19302 if (iperm == 0) { 19303 if (dumpState.onTitlePrinted()) 19304 pw.println(); 19305 pw.println("AppOp Permissions:"); 19306 } 19307 pw.print(" AppOp Permission "); 19308 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19309 pw.println(":"); 19310 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19311 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19312 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19313 } 19314 } 19315 } 19316 } 19317 19318 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19319 boolean printedSomething = false; 19320 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19321 if (packageName != null && !packageName.equals(p.info.packageName)) { 19322 continue; 19323 } 19324 if (!printedSomething) { 19325 if (dumpState.onTitlePrinted()) 19326 pw.println(); 19327 pw.println("Registered ContentProviders:"); 19328 printedSomething = true; 19329 } 19330 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19331 pw.print(" "); pw.println(p.toString()); 19332 } 19333 printedSomething = false; 19334 for (Map.Entry<String, PackageParser.Provider> entry : 19335 mProvidersByAuthority.entrySet()) { 19336 PackageParser.Provider p = entry.getValue(); 19337 if (packageName != null && !packageName.equals(p.info.packageName)) { 19338 continue; 19339 } 19340 if (!printedSomething) { 19341 if (dumpState.onTitlePrinted()) 19342 pw.println(); 19343 pw.println("ContentProvider Authorities:"); 19344 printedSomething = true; 19345 } 19346 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19347 pw.print(" "); pw.println(p.toString()); 19348 if (p.info != null && p.info.applicationInfo != null) { 19349 final String appInfo = p.info.applicationInfo.toString(); 19350 pw.print(" applicationInfo="); pw.println(appInfo); 19351 } 19352 } 19353 } 19354 19355 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19356 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19357 } 19358 19359 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19360 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19361 } 19362 19363 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19364 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19365 } 19366 19367 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19368 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19369 } 19370 19371 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19372 // XXX should handle packageName != null by dumping only install data that 19373 // the given package is involved with. 19374 if (dumpState.onTitlePrinted()) pw.println(); 19375 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19376 } 19377 19378 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19379 // XXX should handle packageName != null by dumping only install data that 19380 // the given package is involved with. 19381 if (dumpState.onTitlePrinted()) pw.println(); 19382 19383 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19384 ipw.println(); 19385 ipw.println("Frozen packages:"); 19386 ipw.increaseIndent(); 19387 if (mFrozenPackages.size() == 0) { 19388 ipw.println("(none)"); 19389 } else { 19390 for (int i = 0; i < mFrozenPackages.size(); i++) { 19391 ipw.println(mFrozenPackages.valueAt(i)); 19392 } 19393 } 19394 ipw.decreaseIndent(); 19395 } 19396 19397 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19398 if (dumpState.onTitlePrinted()) pw.println(); 19399 dumpDexoptStateLPr(pw, packageName); 19400 } 19401 19402 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19403 if (dumpState.onTitlePrinted()) pw.println(); 19404 dumpCompilerStatsLPr(pw, packageName); 19405 } 19406 19407 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19408 if (dumpState.onTitlePrinted()) pw.println(); 19409 mSettings.dumpReadMessagesLPr(pw, dumpState); 19410 19411 pw.println(); 19412 pw.println("Package warning messages:"); 19413 BufferedReader in = null; 19414 String line = null; 19415 try { 19416 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19417 while ((line = in.readLine()) != null) { 19418 if (line.contains("ignored: updated version")) continue; 19419 pw.println(line); 19420 } 19421 } catch (IOException ignored) { 19422 } finally { 19423 IoUtils.closeQuietly(in); 19424 } 19425 } 19426 19427 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19428 BufferedReader in = null; 19429 String line = null; 19430 try { 19431 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19432 while ((line = in.readLine()) != null) { 19433 if (line.contains("ignored: updated version")) continue; 19434 pw.print("msg,"); 19435 pw.println(line); 19436 } 19437 } catch (IOException ignored) { 19438 } finally { 19439 IoUtils.closeQuietly(in); 19440 } 19441 } 19442 } 19443 } 19444 19445 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19446 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19447 ipw.println(); 19448 ipw.println("Dexopt state:"); 19449 ipw.increaseIndent(); 19450 Collection<PackageParser.Package> packages = null; 19451 if (packageName != null) { 19452 PackageParser.Package targetPackage = mPackages.get(packageName); 19453 if (targetPackage != null) { 19454 packages = Collections.singletonList(targetPackage); 19455 } else { 19456 ipw.println("Unable to find package: " + packageName); 19457 return; 19458 } 19459 } else { 19460 packages = mPackages.values(); 19461 } 19462 19463 for (PackageParser.Package pkg : packages) { 19464 ipw.println("[" + pkg.packageName + "]"); 19465 ipw.increaseIndent(); 19466 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19467 ipw.decreaseIndent(); 19468 } 19469 } 19470 19471 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19472 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19473 ipw.println(); 19474 ipw.println("Compiler stats:"); 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 19493 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19494 if (stats == null) { 19495 ipw.println("(No recorded stats)"); 19496 } else { 19497 stats.dump(ipw); 19498 } 19499 ipw.decreaseIndent(); 19500 } 19501 } 19502 19503 private String dumpDomainString(String packageName) { 19504 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19505 .getList(); 19506 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19507 19508 ArraySet<String> result = new ArraySet<>(); 19509 if (iviList.size() > 0) { 19510 for (IntentFilterVerificationInfo ivi : iviList) { 19511 for (String host : ivi.getDomains()) { 19512 result.add(host); 19513 } 19514 } 19515 } 19516 if (filters != null && filters.size() > 0) { 19517 for (IntentFilter filter : filters) { 19518 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19519 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19520 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19521 result.addAll(filter.getHostsList()); 19522 } 19523 } 19524 } 19525 19526 StringBuilder sb = new StringBuilder(result.size() * 16); 19527 for (String domain : result) { 19528 if (sb.length() > 0) sb.append(" "); 19529 sb.append(domain); 19530 } 19531 return sb.toString(); 19532 } 19533 19534 // ------- apps on sdcard specific code ------- 19535 static final boolean DEBUG_SD_INSTALL = false; 19536 19537 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19538 19539 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19540 19541 private boolean mMediaMounted = false; 19542 19543 static String getEncryptKey() { 19544 try { 19545 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19546 SD_ENCRYPTION_KEYSTORE_NAME); 19547 if (sdEncKey == null) { 19548 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19549 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19550 if (sdEncKey == null) { 19551 Slog.e(TAG, "Failed to create encryption keys"); 19552 return null; 19553 } 19554 } 19555 return sdEncKey; 19556 } catch (NoSuchAlgorithmException nsae) { 19557 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19558 return null; 19559 } catch (IOException ioe) { 19560 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19561 return null; 19562 } 19563 } 19564 19565 /* 19566 * Update media status on PackageManager. 19567 */ 19568 @Override 19569 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19570 int callingUid = Binder.getCallingUid(); 19571 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19572 throw new SecurityException("Media status can only be updated by the system"); 19573 } 19574 // reader; this apparently protects mMediaMounted, but should probably 19575 // be a different lock in that case. 19576 synchronized (mPackages) { 19577 Log.i(TAG, "Updating external media status from " 19578 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19579 + (mediaStatus ? "mounted" : "unmounted")); 19580 if (DEBUG_SD_INSTALL) 19581 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19582 + ", mMediaMounted=" + mMediaMounted); 19583 if (mediaStatus == mMediaMounted) { 19584 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19585 : 0, -1); 19586 mHandler.sendMessage(msg); 19587 return; 19588 } 19589 mMediaMounted = mediaStatus; 19590 } 19591 // Queue up an async operation since the package installation may take a 19592 // little while. 19593 mHandler.post(new Runnable() { 19594 public void run() { 19595 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19596 } 19597 }); 19598 } 19599 19600 /** 19601 * Called by StorageManagerService when the initial ASECs to scan are available. 19602 * Should block until all the ASEC containers are finished being scanned. 19603 */ 19604 public void scanAvailableAsecs() { 19605 updateExternalMediaStatusInner(true, false, false); 19606 } 19607 19608 /* 19609 * Collect information of applications on external media, map them against 19610 * existing containers and update information based on current mount status. 19611 * Please note that we always have to report status if reportStatus has been 19612 * set to true especially when unloading packages. 19613 */ 19614 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19615 boolean externalStorage) { 19616 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19617 int[] uidArr = EmptyArray.INT; 19618 19619 final String[] list = PackageHelper.getSecureContainerList(); 19620 if (ArrayUtils.isEmpty(list)) { 19621 Log.i(TAG, "No secure containers found"); 19622 } else { 19623 // Process list of secure containers and categorize them 19624 // as active or stale based on their package internal state. 19625 19626 // reader 19627 synchronized (mPackages) { 19628 for (String cid : list) { 19629 // Leave stages untouched for now; installer service owns them 19630 if (PackageInstallerService.isStageName(cid)) continue; 19631 19632 if (DEBUG_SD_INSTALL) 19633 Log.i(TAG, "Processing container " + cid); 19634 String pkgName = getAsecPackageName(cid); 19635 if (pkgName == null) { 19636 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19637 continue; 19638 } 19639 if (DEBUG_SD_INSTALL) 19640 Log.i(TAG, "Looking for pkg : " + pkgName); 19641 19642 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19643 if (ps == null) { 19644 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19645 continue; 19646 } 19647 19648 /* 19649 * Skip packages that are not external if we're unmounting 19650 * external storage. 19651 */ 19652 if (externalStorage && !isMounted && !isExternal(ps)) { 19653 continue; 19654 } 19655 19656 final AsecInstallArgs args = new AsecInstallArgs(cid, 19657 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19658 // The package status is changed only if the code path 19659 // matches between settings and the container id. 19660 if (ps.codePathString != null 19661 && ps.codePathString.startsWith(args.getCodePath())) { 19662 if (DEBUG_SD_INSTALL) { 19663 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19664 + " at code path: " + ps.codePathString); 19665 } 19666 19667 // We do have a valid package installed on sdcard 19668 processCids.put(args, ps.codePathString); 19669 final int uid = ps.appId; 19670 if (uid != -1) { 19671 uidArr = ArrayUtils.appendInt(uidArr, uid); 19672 } 19673 } else { 19674 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19675 + ps.codePathString); 19676 } 19677 } 19678 } 19679 19680 Arrays.sort(uidArr); 19681 } 19682 19683 // Process packages with valid entries. 19684 if (isMounted) { 19685 if (DEBUG_SD_INSTALL) 19686 Log.i(TAG, "Loading packages"); 19687 loadMediaPackages(processCids, uidArr, externalStorage); 19688 startCleaningPackages(); 19689 mInstallerService.onSecureContainersAvailable(); 19690 } else { 19691 if (DEBUG_SD_INSTALL) 19692 Log.i(TAG, "Unloading packages"); 19693 unloadMediaPackages(processCids, uidArr, reportStatus); 19694 } 19695 } 19696 19697 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19698 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19699 final int size = infos.size(); 19700 final String[] packageNames = new String[size]; 19701 final int[] packageUids = new int[size]; 19702 for (int i = 0; i < size; i++) { 19703 final ApplicationInfo info = infos.get(i); 19704 packageNames[i] = info.packageName; 19705 packageUids[i] = info.uid; 19706 } 19707 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19708 finishedReceiver); 19709 } 19710 19711 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19712 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19713 sendResourcesChangedBroadcast(mediaStatus, replacing, 19714 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19715 } 19716 19717 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19718 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19719 int size = pkgList.length; 19720 if (size > 0) { 19721 // Send broadcasts here 19722 Bundle extras = new Bundle(); 19723 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19724 if (uidArr != null) { 19725 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19726 } 19727 if (replacing) { 19728 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19729 } 19730 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19731 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19732 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19733 } 19734 } 19735 19736 /* 19737 * Look at potentially valid container ids from processCids If package 19738 * information doesn't match the one on record or package scanning fails, 19739 * the cid is added to list of removeCids. We currently don't delete stale 19740 * containers. 19741 */ 19742 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19743 boolean externalStorage) { 19744 ArrayList<String> pkgList = new ArrayList<String>(); 19745 Set<AsecInstallArgs> keys = processCids.keySet(); 19746 19747 for (AsecInstallArgs args : keys) { 19748 String codePath = processCids.get(args); 19749 if (DEBUG_SD_INSTALL) 19750 Log.i(TAG, "Loading container : " + args.cid); 19751 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19752 try { 19753 // Make sure there are no container errors first. 19754 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19755 Slog.e(TAG, "Failed to mount cid : " + args.cid 19756 + " when installing from sdcard"); 19757 continue; 19758 } 19759 // Check code path here. 19760 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19761 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19762 + " does not match one in settings " + codePath); 19763 continue; 19764 } 19765 // Parse package 19766 int parseFlags = mDefParseFlags; 19767 if (args.isExternalAsec()) { 19768 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19769 } 19770 if (args.isFwdLocked()) { 19771 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19772 } 19773 19774 synchronized (mInstallLock) { 19775 PackageParser.Package pkg = null; 19776 try { 19777 // Sadly we don't know the package name yet to freeze it 19778 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19779 SCAN_IGNORE_FROZEN, 0, null); 19780 } catch (PackageManagerException e) { 19781 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19782 } 19783 // Scan the package 19784 if (pkg != null) { 19785 /* 19786 * TODO why is the lock being held? doPostInstall is 19787 * called in other places without the lock. This needs 19788 * to be straightened out. 19789 */ 19790 // writer 19791 synchronized (mPackages) { 19792 retCode = PackageManager.INSTALL_SUCCEEDED; 19793 pkgList.add(pkg.packageName); 19794 // Post process args 19795 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19796 pkg.applicationInfo.uid); 19797 } 19798 } else { 19799 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19800 } 19801 } 19802 19803 } finally { 19804 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19805 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19806 } 19807 } 19808 } 19809 // writer 19810 synchronized (mPackages) { 19811 // If the platform SDK has changed since the last time we booted, 19812 // we need to re-grant app permission to catch any new ones that 19813 // appear. This is really a hack, and means that apps can in some 19814 // cases get permissions that the user didn't initially explicitly 19815 // allow... it would be nice to have some better way to handle 19816 // this situation. 19817 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19818 : mSettings.getInternalVersion(); 19819 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19820 : StorageManager.UUID_PRIVATE_INTERNAL; 19821 19822 int updateFlags = UPDATE_PERMISSIONS_ALL; 19823 if (ver.sdkVersion != mSdkVersion) { 19824 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19825 + mSdkVersion + "; regranting permissions for external"); 19826 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19827 } 19828 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19829 19830 // Yay, everything is now upgraded 19831 ver.forceCurrent(); 19832 19833 // can downgrade to reader 19834 // Persist settings 19835 mSettings.writeLPr(); 19836 } 19837 // Send a broadcast to let everyone know we are done processing 19838 if (pkgList.size() > 0) { 19839 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19840 } 19841 } 19842 19843 /* 19844 * Utility method to unload a list of specified containers 19845 */ 19846 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19847 // Just unmount all valid containers. 19848 for (AsecInstallArgs arg : cidArgs) { 19849 synchronized (mInstallLock) { 19850 arg.doPostDeleteLI(false); 19851 } 19852 } 19853 } 19854 19855 /* 19856 * Unload packages mounted on external media. This involves deleting package 19857 * data from internal structures, sending broadcasts about disabled packages, 19858 * gc'ing to free up references, unmounting all secure containers 19859 * corresponding to packages on external media, and posting a 19860 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19861 * that we always have to post this message if status has been requested no 19862 * matter what. 19863 */ 19864 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19865 final boolean reportStatus) { 19866 if (DEBUG_SD_INSTALL) 19867 Log.i(TAG, "unloading media packages"); 19868 ArrayList<String> pkgList = new ArrayList<String>(); 19869 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19870 final Set<AsecInstallArgs> keys = processCids.keySet(); 19871 for (AsecInstallArgs args : keys) { 19872 String pkgName = args.getPackageName(); 19873 if (DEBUG_SD_INSTALL) 19874 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19875 // Delete package internally 19876 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19877 synchronized (mInstallLock) { 19878 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19879 final boolean res; 19880 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19881 "unloadMediaPackages")) { 19882 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19883 null); 19884 } 19885 if (res) { 19886 pkgList.add(pkgName); 19887 } else { 19888 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19889 failedList.add(args); 19890 } 19891 } 19892 } 19893 19894 // reader 19895 synchronized (mPackages) { 19896 // We didn't update the settings after removing each package; 19897 // write them now for all packages. 19898 mSettings.writeLPr(); 19899 } 19900 19901 // We have to absolutely send UPDATED_MEDIA_STATUS only 19902 // after confirming that all the receivers processed the ordered 19903 // broadcast when packages get disabled, force a gc to clean things up. 19904 // and unload all the containers. 19905 if (pkgList.size() > 0) { 19906 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19907 new IIntentReceiver.Stub() { 19908 public void performReceive(Intent intent, int resultCode, String data, 19909 Bundle extras, boolean ordered, boolean sticky, 19910 int sendingUser) throws RemoteException { 19911 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19912 reportStatus ? 1 : 0, 1, keys); 19913 mHandler.sendMessage(msg); 19914 } 19915 }); 19916 } else { 19917 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19918 keys); 19919 mHandler.sendMessage(msg); 19920 } 19921 } 19922 19923 private void loadPrivatePackages(final VolumeInfo vol) { 19924 mHandler.post(new Runnable() { 19925 @Override 19926 public void run() { 19927 loadPrivatePackagesInner(vol); 19928 } 19929 }); 19930 } 19931 19932 private void loadPrivatePackagesInner(VolumeInfo vol) { 19933 final String volumeUuid = vol.fsUuid; 19934 if (TextUtils.isEmpty(volumeUuid)) { 19935 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19936 return; 19937 } 19938 19939 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19940 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19941 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19942 19943 final VersionInfo ver; 19944 final List<PackageSetting> packages; 19945 synchronized (mPackages) { 19946 ver = mSettings.findOrCreateVersion(volumeUuid); 19947 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19948 } 19949 19950 for (PackageSetting ps : packages) { 19951 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19952 synchronized (mInstallLock) { 19953 final PackageParser.Package pkg; 19954 try { 19955 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19956 loaded.add(pkg.applicationInfo); 19957 19958 } catch (PackageManagerException e) { 19959 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19960 } 19961 19962 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19963 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19964 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19965 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19966 } 19967 } 19968 } 19969 19970 // Reconcile app data for all started/unlocked users 19971 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19972 final UserManager um = mContext.getSystemService(UserManager.class); 19973 UserManagerInternal umInternal = getUserManagerInternal(); 19974 for (UserInfo user : um.getUsers()) { 19975 final int flags; 19976 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19977 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19978 } else if (umInternal.isUserRunning(user.id)) { 19979 flags = StorageManager.FLAG_STORAGE_DE; 19980 } else { 19981 continue; 19982 } 19983 19984 try { 19985 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19986 synchronized (mInstallLock) { 19987 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 19988 } 19989 } catch (IllegalStateException e) { 19990 // Device was probably ejected, and we'll process that event momentarily 19991 Slog.w(TAG, "Failed to prepare storage: " + e); 19992 } 19993 } 19994 19995 synchronized (mPackages) { 19996 int updateFlags = UPDATE_PERMISSIONS_ALL; 19997 if (ver.sdkVersion != mSdkVersion) { 19998 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19999 + mSdkVersion + "; regranting permissions for " + volumeUuid); 20000 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20001 } 20002 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20003 20004 // Yay, everything is now upgraded 20005 ver.forceCurrent(); 20006 20007 mSettings.writeLPr(); 20008 } 20009 20010 for (PackageFreezer freezer : freezers) { 20011 freezer.close(); 20012 } 20013 20014 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 20015 sendResourcesChangedBroadcast(true, false, loaded, null); 20016 } 20017 20018 private void unloadPrivatePackages(final VolumeInfo vol) { 20019 mHandler.post(new Runnable() { 20020 @Override 20021 public void run() { 20022 unloadPrivatePackagesInner(vol); 20023 } 20024 }); 20025 } 20026 20027 private void unloadPrivatePackagesInner(VolumeInfo vol) { 20028 final String volumeUuid = vol.fsUuid; 20029 if (TextUtils.isEmpty(volumeUuid)) { 20030 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 20031 return; 20032 } 20033 20034 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 20035 synchronized (mInstallLock) { 20036 synchronized (mPackages) { 20037 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 20038 for (PackageSetting ps : packages) { 20039 if (ps.pkg == null) continue; 20040 20041 final ApplicationInfo info = ps.pkg.applicationInfo; 20042 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20043 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20044 20045 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 20046 "unloadPrivatePackagesInner")) { 20047 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 20048 false, null)) { 20049 unloaded.add(info); 20050 } else { 20051 Slog.w(TAG, "Failed to unload " + ps.codePath); 20052 } 20053 } 20054 20055 // Try very hard to release any references to this package 20056 // so we don't risk the system server being killed due to 20057 // open FDs 20058 AttributeCache.instance().removePackage(ps.name); 20059 } 20060 20061 mSettings.writeLPr(); 20062 } 20063 } 20064 20065 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 20066 sendResourcesChangedBroadcast(false, false, unloaded, null); 20067 20068 // Try very hard to release any references to this path so we don't risk 20069 // the system server being killed due to open FDs 20070 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 20071 20072 for (int i = 0; i < 3; i++) { 20073 System.gc(); 20074 System.runFinalization(); 20075 } 20076 } 20077 20078 /** 20079 * Prepare storage areas for given user on all mounted devices. 20080 */ 20081 void prepareUserData(int userId, int userSerial, int flags) { 20082 synchronized (mInstallLock) { 20083 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20084 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20085 final String volumeUuid = vol.getFsUuid(); 20086 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 20087 } 20088 } 20089 } 20090 20091 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 20092 boolean allowRecover) { 20093 // Prepare storage and verify that serial numbers are consistent; if 20094 // there's a mismatch we need to destroy to avoid leaking data 20095 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20096 try { 20097 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 20098 20099 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 20100 UserManagerService.enforceSerialNumber( 20101 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 20102 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20103 UserManagerService.enforceSerialNumber( 20104 Environment.getDataSystemDeDirectory(userId), userSerial); 20105 } 20106 } 20107 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 20108 UserManagerService.enforceSerialNumber( 20109 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 20110 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20111 UserManagerService.enforceSerialNumber( 20112 Environment.getDataSystemCeDirectory(userId), userSerial); 20113 } 20114 } 20115 20116 synchronized (mInstallLock) { 20117 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20118 } 20119 } catch (Exception e) { 20120 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20121 + " because we failed to prepare: " + e); 20122 destroyUserDataLI(volumeUuid, userId, 20123 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20124 20125 if (allowRecover) { 20126 // Try one last time; if we fail again we're really in trouble 20127 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20128 } 20129 } 20130 } 20131 20132 /** 20133 * Destroy storage areas for given user on all mounted devices. 20134 */ 20135 void destroyUserData(int userId, int flags) { 20136 synchronized (mInstallLock) { 20137 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20138 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20139 final String volumeUuid = vol.getFsUuid(); 20140 destroyUserDataLI(volumeUuid, userId, flags); 20141 } 20142 } 20143 } 20144 20145 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20146 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20147 try { 20148 // Clean up app data, profile data, and media data 20149 mInstaller.destroyUserData(volumeUuid, userId, flags); 20150 20151 // Clean up system data 20152 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20153 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20154 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20155 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20156 } 20157 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20158 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20159 } 20160 } 20161 20162 // Data with special labels is now gone, so finish the job 20163 storage.destroyUserStorage(volumeUuid, userId, flags); 20164 20165 } catch (Exception e) { 20166 logCriticalInfo(Log.WARN, 20167 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20168 } 20169 } 20170 20171 /** 20172 * Examine all users present on given mounted volume, and destroy data 20173 * belonging to users that are no longer valid, or whose user ID has been 20174 * recycled. 20175 */ 20176 private void reconcileUsers(String volumeUuid) { 20177 final List<File> files = new ArrayList<>(); 20178 Collections.addAll(files, FileUtils 20179 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20180 Collections.addAll(files, FileUtils 20181 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20182 Collections.addAll(files, FileUtils 20183 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20184 Collections.addAll(files, FileUtils 20185 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20186 for (File file : files) { 20187 if (!file.isDirectory()) continue; 20188 20189 final int userId; 20190 final UserInfo info; 20191 try { 20192 userId = Integer.parseInt(file.getName()); 20193 info = sUserManager.getUserInfo(userId); 20194 } catch (NumberFormatException e) { 20195 Slog.w(TAG, "Invalid user directory " + file); 20196 continue; 20197 } 20198 20199 boolean destroyUser = false; 20200 if (info == null) { 20201 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20202 + " because no matching user was found"); 20203 destroyUser = true; 20204 } else if (!mOnlyCore) { 20205 try { 20206 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20207 } catch (IOException e) { 20208 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20209 + " because we failed to enforce serial number: " + e); 20210 destroyUser = true; 20211 } 20212 } 20213 20214 if (destroyUser) { 20215 synchronized (mInstallLock) { 20216 destroyUserDataLI(volumeUuid, userId, 20217 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20218 } 20219 } 20220 } 20221 } 20222 20223 private void assertPackageKnown(String volumeUuid, String packageName) 20224 throws PackageManagerException { 20225 synchronized (mPackages) { 20226 // Normalize package name to handle renamed packages 20227 packageName = normalizePackageNameLPr(packageName); 20228 20229 final PackageSetting ps = mSettings.mPackages.get(packageName); 20230 if (ps == null) { 20231 throw new PackageManagerException("Package " + packageName + " is unknown"); 20232 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20233 throw new PackageManagerException( 20234 "Package " + packageName + " found on unknown volume " + volumeUuid 20235 + "; expected volume " + ps.volumeUuid); 20236 } 20237 } 20238 } 20239 20240 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20241 throws PackageManagerException { 20242 synchronized (mPackages) { 20243 // Normalize package name to handle renamed packages 20244 packageName = normalizePackageNameLPr(packageName); 20245 20246 final PackageSetting ps = mSettings.mPackages.get(packageName); 20247 if (ps == null) { 20248 throw new PackageManagerException("Package " + packageName + " is unknown"); 20249 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20250 throw new PackageManagerException( 20251 "Package " + packageName + " found on unknown volume " + volumeUuid 20252 + "; expected volume " + ps.volumeUuid); 20253 } else if (!ps.getInstalled(userId)) { 20254 throw new PackageManagerException( 20255 "Package " + packageName + " not installed for user " + userId); 20256 } 20257 } 20258 } 20259 20260 /** 20261 * Examine all apps present on given mounted volume, and destroy apps that 20262 * aren't expected, either due to uninstallation or reinstallation on 20263 * another volume. 20264 */ 20265 private void reconcileApps(String volumeUuid) { 20266 final File[] files = FileUtils 20267 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20268 for (File file : files) { 20269 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20270 && !PackageInstallerService.isStageName(file.getName()); 20271 if (!isPackage) { 20272 // Ignore entries which are not packages 20273 continue; 20274 } 20275 20276 try { 20277 final PackageLite pkg = PackageParser.parsePackageLite(file, 20278 PackageParser.PARSE_MUST_BE_APK); 20279 assertPackageKnown(volumeUuid, pkg.packageName); 20280 20281 } catch (PackageParserException | PackageManagerException e) { 20282 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20283 synchronized (mInstallLock) { 20284 removeCodePathLI(file); 20285 } 20286 } 20287 } 20288 } 20289 20290 /** 20291 * Reconcile all app data for the given user. 20292 * <p> 20293 * Verifies that directories exist and that ownership and labeling is 20294 * correct for all installed apps on all mounted volumes. 20295 */ 20296 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20297 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20298 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20299 final String volumeUuid = vol.getFsUuid(); 20300 synchronized (mInstallLock) { 20301 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20302 } 20303 } 20304 } 20305 20306 /** 20307 * Reconcile all app data on given mounted volume. 20308 * <p> 20309 * Destroys app data that isn't expected, either due to uninstallation or 20310 * reinstallation on another volume. 20311 * <p> 20312 * Verifies that directories exist and that ownership and labeling is 20313 * correct for all installed apps. 20314 */ 20315 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20316 boolean migrateAppData) { 20317 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20318 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20319 20320 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20321 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20322 20323 // First look for stale data that doesn't belong, and check if things 20324 // have changed since we did our last restorecon 20325 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20326 if (StorageManager.isFileEncryptedNativeOrEmulated() 20327 && !StorageManager.isUserKeyUnlocked(userId)) { 20328 throw new RuntimeException( 20329 "Yikes, someone asked us to reconcile CE storage while " + userId 20330 + " was still locked; this would have caused massive data loss!"); 20331 } 20332 20333 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20334 for (File file : files) { 20335 final String packageName = file.getName(); 20336 try { 20337 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20338 } catch (PackageManagerException e) { 20339 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20340 try { 20341 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20342 StorageManager.FLAG_STORAGE_CE, 0); 20343 } catch (InstallerException e2) { 20344 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20345 } 20346 } 20347 } 20348 } 20349 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20350 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20351 for (File file : files) { 20352 final String packageName = file.getName(); 20353 try { 20354 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20355 } catch (PackageManagerException e) { 20356 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20357 try { 20358 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20359 StorageManager.FLAG_STORAGE_DE, 0); 20360 } catch (InstallerException e2) { 20361 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20362 } 20363 } 20364 } 20365 } 20366 20367 // Ensure that data directories are ready to roll for all packages 20368 // installed for this volume and user 20369 final List<PackageSetting> packages; 20370 synchronized (mPackages) { 20371 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20372 } 20373 int preparedCount = 0; 20374 for (PackageSetting ps : packages) { 20375 final String packageName = ps.name; 20376 if (ps.pkg == null) { 20377 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20378 // TODO: might be due to legacy ASEC apps; we should circle back 20379 // and reconcile again once they're scanned 20380 continue; 20381 } 20382 20383 if (ps.getInstalled(userId)) { 20384 prepareAppDataLIF(ps.pkg, userId, flags); 20385 20386 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20387 // We may have just shuffled around app data directories, so 20388 // prepare them one more time 20389 prepareAppDataLIF(ps.pkg, userId, flags); 20390 } 20391 20392 preparedCount++; 20393 } 20394 } 20395 20396 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20397 } 20398 20399 /** 20400 * Prepare app data for the given app just after it was installed or 20401 * upgraded. This method carefully only touches users that it's installed 20402 * for, and it forces a restorecon to handle any seinfo changes. 20403 * <p> 20404 * Verifies that directories exist and that ownership and labeling is 20405 * correct for all installed apps. If there is an ownership mismatch, it 20406 * will try recovering system apps by wiping data; third-party app data is 20407 * left intact. 20408 * <p> 20409 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20410 */ 20411 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20412 final PackageSetting ps; 20413 synchronized (mPackages) { 20414 ps = mSettings.mPackages.get(pkg.packageName); 20415 mSettings.writeKernelMappingLPr(ps); 20416 } 20417 20418 final UserManager um = mContext.getSystemService(UserManager.class); 20419 UserManagerInternal umInternal = getUserManagerInternal(); 20420 for (UserInfo user : um.getUsers()) { 20421 final int flags; 20422 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20423 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20424 } else if (umInternal.isUserRunning(user.id)) { 20425 flags = StorageManager.FLAG_STORAGE_DE; 20426 } else { 20427 continue; 20428 } 20429 20430 if (ps.getInstalled(user.id)) { 20431 // TODO: when user data is locked, mark that we're still dirty 20432 prepareAppDataLIF(pkg, user.id, flags); 20433 } 20434 } 20435 } 20436 20437 /** 20438 * Prepare app data for the given app. 20439 * <p> 20440 * Verifies that directories exist and that ownership and labeling is 20441 * correct for all installed apps. If there is an ownership mismatch, this 20442 * will try recovering system apps by wiping data; third-party app data is 20443 * left intact. 20444 */ 20445 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20446 if (pkg == null) { 20447 Slog.wtf(TAG, "Package was null!", new Throwable()); 20448 return; 20449 } 20450 prepareAppDataLeafLIF(pkg, userId, flags); 20451 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20452 for (int i = 0; i < childCount; i++) { 20453 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20454 } 20455 } 20456 20457 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20458 if (DEBUG_APP_DATA) { 20459 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20460 + Integer.toHexString(flags)); 20461 } 20462 20463 final String volumeUuid = pkg.volumeUuid; 20464 final String packageName = pkg.packageName; 20465 final ApplicationInfo app = pkg.applicationInfo; 20466 final int appId = UserHandle.getAppId(app.uid); 20467 20468 Preconditions.checkNotNull(app.seinfo); 20469 20470 try { 20471 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20472 appId, app.seinfo, app.targetSdkVersion); 20473 } catch (InstallerException e) { 20474 if (app.isSystemApp()) { 20475 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20476 + ", but trying to recover: " + e); 20477 destroyAppDataLeafLIF(pkg, userId, flags); 20478 try { 20479 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20480 appId, app.seinfo, app.targetSdkVersion); 20481 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20482 } catch (InstallerException e2) { 20483 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20484 } 20485 } else { 20486 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20487 } 20488 } 20489 20490 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20491 try { 20492 // CE storage is unlocked right now, so read out the inode and 20493 // remember for use later when it's locked 20494 // TODO: mark this structure as dirty so we persist it! 20495 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20496 StorageManager.FLAG_STORAGE_CE); 20497 synchronized (mPackages) { 20498 final PackageSetting ps = mSettings.mPackages.get(packageName); 20499 if (ps != null) { 20500 ps.setCeDataInode(ceDataInode, userId); 20501 } 20502 } 20503 } catch (InstallerException e) { 20504 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20505 } 20506 } 20507 20508 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20509 } 20510 20511 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20512 if (pkg == null) { 20513 Slog.wtf(TAG, "Package was null!", new Throwable()); 20514 return; 20515 } 20516 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20517 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20518 for (int i = 0; i < childCount; i++) { 20519 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20520 } 20521 } 20522 20523 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20524 final String volumeUuid = pkg.volumeUuid; 20525 final String packageName = pkg.packageName; 20526 final ApplicationInfo app = pkg.applicationInfo; 20527 20528 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20529 // Create a native library symlink only if we have native libraries 20530 // and if the native libraries are 32 bit libraries. We do not provide 20531 // this symlink for 64 bit libraries. 20532 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20533 final String nativeLibPath = app.nativeLibraryDir; 20534 try { 20535 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20536 nativeLibPath, userId); 20537 } catch (InstallerException e) { 20538 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20539 } 20540 } 20541 } 20542 } 20543 20544 /** 20545 * For system apps on non-FBE devices, this method migrates any existing 20546 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20547 * requested by the app. 20548 */ 20549 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20550 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20551 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20552 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20553 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20554 try { 20555 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20556 storageTarget); 20557 } catch (InstallerException e) { 20558 logCriticalInfo(Log.WARN, 20559 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20560 } 20561 return true; 20562 } else { 20563 return false; 20564 } 20565 } 20566 20567 public PackageFreezer freezePackage(String packageName, String killReason) { 20568 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20569 } 20570 20571 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20572 return new PackageFreezer(packageName, userId, killReason); 20573 } 20574 20575 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20576 String killReason) { 20577 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20578 } 20579 20580 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20581 String killReason) { 20582 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20583 return new PackageFreezer(); 20584 } else { 20585 return freezePackage(packageName, userId, killReason); 20586 } 20587 } 20588 20589 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20590 String killReason) { 20591 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20592 } 20593 20594 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20595 String killReason) { 20596 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20597 return new PackageFreezer(); 20598 } else { 20599 return freezePackage(packageName, userId, killReason); 20600 } 20601 } 20602 20603 /** 20604 * Class that freezes and kills the given package upon creation, and 20605 * unfreezes it upon closing. This is typically used when doing surgery on 20606 * app code/data to prevent the app from running while you're working. 20607 */ 20608 private class PackageFreezer implements AutoCloseable { 20609 private final String mPackageName; 20610 private final PackageFreezer[] mChildren; 20611 20612 private final boolean mWeFroze; 20613 20614 private final AtomicBoolean mClosed = new AtomicBoolean(); 20615 private final CloseGuard mCloseGuard = CloseGuard.get(); 20616 20617 /** 20618 * Create and return a stub freezer that doesn't actually do anything, 20619 * typically used when someone requested 20620 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20621 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20622 */ 20623 public PackageFreezer() { 20624 mPackageName = null; 20625 mChildren = null; 20626 mWeFroze = false; 20627 mCloseGuard.open("close"); 20628 } 20629 20630 public PackageFreezer(String packageName, int userId, String killReason) { 20631 synchronized (mPackages) { 20632 mPackageName = packageName; 20633 mWeFroze = mFrozenPackages.add(mPackageName); 20634 20635 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20636 if (ps != null) { 20637 killApplication(ps.name, ps.appId, userId, killReason); 20638 } 20639 20640 final PackageParser.Package p = mPackages.get(packageName); 20641 if (p != null && p.childPackages != null) { 20642 final int N = p.childPackages.size(); 20643 mChildren = new PackageFreezer[N]; 20644 for (int i = 0; i < N; i++) { 20645 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20646 userId, killReason); 20647 } 20648 } else { 20649 mChildren = null; 20650 } 20651 } 20652 mCloseGuard.open("close"); 20653 } 20654 20655 @Override 20656 protected void finalize() throws Throwable { 20657 try { 20658 mCloseGuard.warnIfOpen(); 20659 close(); 20660 } finally { 20661 super.finalize(); 20662 } 20663 } 20664 20665 @Override 20666 public void close() { 20667 mCloseGuard.close(); 20668 if (mClosed.compareAndSet(false, true)) { 20669 synchronized (mPackages) { 20670 if (mWeFroze) { 20671 mFrozenPackages.remove(mPackageName); 20672 } 20673 20674 if (mChildren != null) { 20675 for (PackageFreezer freezer : mChildren) { 20676 freezer.close(); 20677 } 20678 } 20679 } 20680 } 20681 } 20682 } 20683 20684 /** 20685 * Verify that given package is currently frozen. 20686 */ 20687 private void checkPackageFrozen(String packageName) { 20688 synchronized (mPackages) { 20689 if (!mFrozenPackages.contains(packageName)) { 20690 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20691 } 20692 } 20693 } 20694 20695 @Override 20696 public int movePackage(final String packageName, final String volumeUuid) { 20697 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20698 20699 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20700 final int moveId = mNextMoveId.getAndIncrement(); 20701 mHandler.post(new Runnable() { 20702 @Override 20703 public void run() { 20704 try { 20705 movePackageInternal(packageName, volumeUuid, moveId, user); 20706 } catch (PackageManagerException e) { 20707 Slog.w(TAG, "Failed to move " + packageName, e); 20708 mMoveCallbacks.notifyStatusChanged(moveId, 20709 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20710 } 20711 } 20712 }); 20713 return moveId; 20714 } 20715 20716 private void movePackageInternal(final String packageName, final String volumeUuid, 20717 final int moveId, UserHandle user) throws PackageManagerException { 20718 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20719 final PackageManager pm = mContext.getPackageManager(); 20720 20721 final boolean currentAsec; 20722 final String currentVolumeUuid; 20723 final File codeFile; 20724 final String installerPackageName; 20725 final String packageAbiOverride; 20726 final int appId; 20727 final String seinfo; 20728 final String label; 20729 final int targetSdkVersion; 20730 final PackageFreezer freezer; 20731 final int[] installedUserIds; 20732 20733 // reader 20734 synchronized (mPackages) { 20735 final PackageParser.Package pkg = mPackages.get(packageName); 20736 final PackageSetting ps = mSettings.mPackages.get(packageName); 20737 if (pkg == null || ps == null) { 20738 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20739 } 20740 20741 if (pkg.applicationInfo.isSystemApp()) { 20742 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20743 "Cannot move system application"); 20744 } 20745 20746 if (pkg.applicationInfo.isExternalAsec()) { 20747 currentAsec = true; 20748 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20749 } else if (pkg.applicationInfo.isForwardLocked()) { 20750 currentAsec = true; 20751 currentVolumeUuid = "forward_locked"; 20752 } else { 20753 currentAsec = false; 20754 currentVolumeUuid = ps.volumeUuid; 20755 20756 final File probe = new File(pkg.codePath); 20757 final File probeOat = new File(probe, "oat"); 20758 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20759 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20760 "Move only supported for modern cluster style installs"); 20761 } 20762 } 20763 20764 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20765 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20766 "Package already moved to " + volumeUuid); 20767 } 20768 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20769 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20770 "Device admin cannot be moved"); 20771 } 20772 20773 if (mFrozenPackages.contains(packageName)) { 20774 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20775 "Failed to move already frozen package"); 20776 } 20777 20778 codeFile = new File(pkg.codePath); 20779 installerPackageName = ps.installerPackageName; 20780 packageAbiOverride = ps.cpuAbiOverrideString; 20781 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20782 seinfo = pkg.applicationInfo.seinfo; 20783 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20784 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20785 freezer = freezePackage(packageName, "movePackageInternal"); 20786 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20787 } 20788 20789 final Bundle extras = new Bundle(); 20790 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20791 extras.putString(Intent.EXTRA_TITLE, label); 20792 mMoveCallbacks.notifyCreated(moveId, extras); 20793 20794 int installFlags; 20795 final boolean moveCompleteApp; 20796 final File measurePath; 20797 20798 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20799 installFlags = INSTALL_INTERNAL; 20800 moveCompleteApp = !currentAsec; 20801 measurePath = Environment.getDataAppDirectory(volumeUuid); 20802 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20803 installFlags = INSTALL_EXTERNAL; 20804 moveCompleteApp = false; 20805 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20806 } else { 20807 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20808 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20809 || !volume.isMountedWritable()) { 20810 freezer.close(); 20811 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20812 "Move location not mounted private volume"); 20813 } 20814 20815 Preconditions.checkState(!currentAsec); 20816 20817 installFlags = INSTALL_INTERNAL; 20818 moveCompleteApp = true; 20819 measurePath = Environment.getDataAppDirectory(volumeUuid); 20820 } 20821 20822 final PackageStats stats = new PackageStats(null, -1); 20823 synchronized (mInstaller) { 20824 for (int userId : installedUserIds) { 20825 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20826 freezer.close(); 20827 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20828 "Failed to measure package size"); 20829 } 20830 } 20831 } 20832 20833 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20834 + stats.dataSize); 20835 20836 final long startFreeBytes = measurePath.getFreeSpace(); 20837 final long sizeBytes; 20838 if (moveCompleteApp) { 20839 sizeBytes = stats.codeSize + stats.dataSize; 20840 } else { 20841 sizeBytes = stats.codeSize; 20842 } 20843 20844 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20845 freezer.close(); 20846 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20847 "Not enough free space to move"); 20848 } 20849 20850 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20851 20852 final CountDownLatch installedLatch = new CountDownLatch(1); 20853 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20854 @Override 20855 public void onUserActionRequired(Intent intent) throws RemoteException { 20856 throw new IllegalStateException(); 20857 } 20858 20859 @Override 20860 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20861 Bundle extras) throws RemoteException { 20862 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20863 + PackageManager.installStatusToString(returnCode, msg)); 20864 20865 installedLatch.countDown(); 20866 freezer.close(); 20867 20868 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20869 switch (status) { 20870 case PackageInstaller.STATUS_SUCCESS: 20871 mMoveCallbacks.notifyStatusChanged(moveId, 20872 PackageManager.MOVE_SUCCEEDED); 20873 break; 20874 case PackageInstaller.STATUS_FAILURE_STORAGE: 20875 mMoveCallbacks.notifyStatusChanged(moveId, 20876 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20877 break; 20878 default: 20879 mMoveCallbacks.notifyStatusChanged(moveId, 20880 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20881 break; 20882 } 20883 } 20884 }; 20885 20886 final MoveInfo move; 20887 if (moveCompleteApp) { 20888 // Kick off a thread to report progress estimates 20889 new Thread() { 20890 @Override 20891 public void run() { 20892 while (true) { 20893 try { 20894 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20895 break; 20896 } 20897 } catch (InterruptedException ignored) { 20898 } 20899 20900 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20901 final int progress = 10 + (int) MathUtils.constrain( 20902 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20903 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20904 } 20905 } 20906 }.start(); 20907 20908 final String dataAppName = codeFile.getName(); 20909 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20910 dataAppName, appId, seinfo, targetSdkVersion); 20911 } else { 20912 move = null; 20913 } 20914 20915 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20916 20917 final Message msg = mHandler.obtainMessage(INIT_COPY); 20918 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20919 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20920 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20921 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20922 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20923 msg.obj = params; 20924 20925 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20926 System.identityHashCode(msg.obj)); 20927 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20928 System.identityHashCode(msg.obj)); 20929 20930 mHandler.sendMessage(msg); 20931 } 20932 20933 @Override 20934 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20935 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20936 20937 final int realMoveId = mNextMoveId.getAndIncrement(); 20938 final Bundle extras = new Bundle(); 20939 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20940 mMoveCallbacks.notifyCreated(realMoveId, extras); 20941 20942 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20943 @Override 20944 public void onCreated(int moveId, Bundle extras) { 20945 // Ignored 20946 } 20947 20948 @Override 20949 public void onStatusChanged(int moveId, int status, long estMillis) { 20950 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20951 } 20952 }; 20953 20954 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20955 storage.setPrimaryStorageUuid(volumeUuid, callback); 20956 return realMoveId; 20957 } 20958 20959 @Override 20960 public int getMoveStatus(int moveId) { 20961 mContext.enforceCallingOrSelfPermission( 20962 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20963 return mMoveCallbacks.mLastStatus.get(moveId); 20964 } 20965 20966 @Override 20967 public void registerMoveCallback(IPackageMoveObserver callback) { 20968 mContext.enforceCallingOrSelfPermission( 20969 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20970 mMoveCallbacks.register(callback); 20971 } 20972 20973 @Override 20974 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20975 mContext.enforceCallingOrSelfPermission( 20976 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20977 mMoveCallbacks.unregister(callback); 20978 } 20979 20980 @Override 20981 public boolean setInstallLocation(int loc) { 20982 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20983 null); 20984 if (getInstallLocation() == loc) { 20985 return true; 20986 } 20987 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20988 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20989 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20990 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20991 return true; 20992 } 20993 return false; 20994 } 20995 20996 @Override 20997 public int getInstallLocation() { 20998 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20999 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 21000 PackageHelper.APP_INSTALL_AUTO); 21001 } 21002 21003 /** Called by UserManagerService */ 21004 void cleanUpUser(UserManagerService userManager, int userHandle) { 21005 synchronized (mPackages) { 21006 mDirtyUsers.remove(userHandle); 21007 mUserNeedsBadging.delete(userHandle); 21008 mSettings.removeUserLPw(userHandle); 21009 mPendingBroadcasts.remove(userHandle); 21010 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 21011 removeUnusedPackagesLPw(userManager, userHandle); 21012 } 21013 } 21014 21015 /** 21016 * We're removing userHandle and would like to remove any downloaded packages 21017 * that are no longer in use by any other user. 21018 * @param userHandle the user being removed 21019 */ 21020 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 21021 final boolean DEBUG_CLEAN_APKS = false; 21022 int [] users = userManager.getUserIds(); 21023 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 21024 while (psit.hasNext()) { 21025 PackageSetting ps = psit.next(); 21026 if (ps.pkg == null) { 21027 continue; 21028 } 21029 final String packageName = ps.pkg.packageName; 21030 // Skip over if system app 21031 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 21032 continue; 21033 } 21034 if (DEBUG_CLEAN_APKS) { 21035 Slog.i(TAG, "Checking package " + packageName); 21036 } 21037 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 21038 if (keep) { 21039 if (DEBUG_CLEAN_APKS) { 21040 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 21041 } 21042 } else { 21043 for (int i = 0; i < users.length; i++) { 21044 if (users[i] != userHandle && ps.getInstalled(users[i])) { 21045 keep = true; 21046 if (DEBUG_CLEAN_APKS) { 21047 Slog.i(TAG, " Keeping package " + packageName + " for user " 21048 + users[i]); 21049 } 21050 break; 21051 } 21052 } 21053 } 21054 if (!keep) { 21055 if (DEBUG_CLEAN_APKS) { 21056 Slog.i(TAG, " Removing package " + packageName); 21057 } 21058 mHandler.post(new Runnable() { 21059 public void run() { 21060 deletePackageX(packageName, userHandle, 0); 21061 } //end run 21062 }); 21063 } 21064 } 21065 } 21066 21067 /** Called by UserManagerService */ 21068 void createNewUser(int userId, String[] disallowedPackages) { 21069 synchronized (mInstallLock) { 21070 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 21071 } 21072 synchronized (mPackages) { 21073 scheduleWritePackageRestrictionsLocked(userId); 21074 scheduleWritePackageListLocked(userId); 21075 applyFactoryDefaultBrowserLPw(userId); 21076 primeDomainVerificationsLPw(userId); 21077 } 21078 } 21079 21080 void onNewUserCreated(final int userId) { 21081 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21082 // If permission review for legacy apps is required, we represent 21083 // dagerous permissions for such apps as always granted runtime 21084 // permissions to keep per user flag state whether review is needed. 21085 // Hence, if a new user is added we have to propagate dangerous 21086 // permission grants for these legacy apps. 21087 if (mPermissionReviewRequired) { 21088 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 21089 | UPDATE_PERMISSIONS_REPLACE_ALL); 21090 } 21091 } 21092 21093 @Override 21094 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 21095 mContext.enforceCallingOrSelfPermission( 21096 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 21097 "Only package verification agents can read the verifier device identity"); 21098 21099 synchronized (mPackages) { 21100 return mSettings.getVerifierDeviceIdentityLPw(); 21101 } 21102 } 21103 21104 @Override 21105 public void setPermissionEnforced(String permission, boolean enforced) { 21106 // TODO: Now that we no longer change GID for storage, this should to away. 21107 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 21108 "setPermissionEnforced"); 21109 if (READ_EXTERNAL_STORAGE.equals(permission)) { 21110 synchronized (mPackages) { 21111 if (mSettings.mReadExternalStorageEnforced == null 21112 || mSettings.mReadExternalStorageEnforced != enforced) { 21113 mSettings.mReadExternalStorageEnforced = enforced; 21114 mSettings.writeLPr(); 21115 } 21116 } 21117 // kill any non-foreground processes so we restart them and 21118 // grant/revoke the GID. 21119 final IActivityManager am = ActivityManager.getService(); 21120 if (am != null) { 21121 final long token = Binder.clearCallingIdentity(); 21122 try { 21123 am.killProcessesBelowForeground("setPermissionEnforcement"); 21124 } catch (RemoteException e) { 21125 } finally { 21126 Binder.restoreCallingIdentity(token); 21127 } 21128 } 21129 } else { 21130 throw new IllegalArgumentException("No selective enforcement for " + permission); 21131 } 21132 } 21133 21134 @Override 21135 @Deprecated 21136 public boolean isPermissionEnforced(String permission) { 21137 return true; 21138 } 21139 21140 @Override 21141 public boolean isStorageLow() { 21142 final long token = Binder.clearCallingIdentity(); 21143 try { 21144 final DeviceStorageMonitorInternal 21145 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21146 if (dsm != null) { 21147 return dsm.isMemoryLow(); 21148 } else { 21149 return false; 21150 } 21151 } finally { 21152 Binder.restoreCallingIdentity(token); 21153 } 21154 } 21155 21156 @Override 21157 public IPackageInstaller getPackageInstaller() { 21158 return mInstallerService; 21159 } 21160 21161 private boolean userNeedsBadging(int userId) { 21162 int index = mUserNeedsBadging.indexOfKey(userId); 21163 if (index < 0) { 21164 final UserInfo userInfo; 21165 final long token = Binder.clearCallingIdentity(); 21166 try { 21167 userInfo = sUserManager.getUserInfo(userId); 21168 } finally { 21169 Binder.restoreCallingIdentity(token); 21170 } 21171 final boolean b; 21172 if (userInfo != null && userInfo.isManagedProfile()) { 21173 b = true; 21174 } else { 21175 b = false; 21176 } 21177 mUserNeedsBadging.put(userId, b); 21178 return b; 21179 } 21180 return mUserNeedsBadging.valueAt(index); 21181 } 21182 21183 @Override 21184 public KeySet getKeySetByAlias(String packageName, String alias) { 21185 if (packageName == null || alias == null) { 21186 return null; 21187 } 21188 synchronized(mPackages) { 21189 final PackageParser.Package pkg = mPackages.get(packageName); 21190 if (pkg == null) { 21191 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21192 throw new IllegalArgumentException("Unknown package: " + packageName); 21193 } 21194 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21195 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21196 } 21197 } 21198 21199 @Override 21200 public KeySet getSigningKeySet(String packageName) { 21201 if (packageName == null) { 21202 return null; 21203 } 21204 synchronized(mPackages) { 21205 final PackageParser.Package pkg = mPackages.get(packageName); 21206 if (pkg == null) { 21207 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21208 throw new IllegalArgumentException("Unknown package: " + packageName); 21209 } 21210 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21211 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21212 throw new SecurityException("May not access signing KeySet of other apps."); 21213 } 21214 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21215 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21216 } 21217 } 21218 21219 @Override 21220 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21221 if (packageName == null || ks == null) { 21222 return false; 21223 } 21224 synchronized(mPackages) { 21225 final PackageParser.Package pkg = mPackages.get(packageName); 21226 if (pkg == null) { 21227 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21228 throw new IllegalArgumentException("Unknown package: " + packageName); 21229 } 21230 IBinder ksh = ks.getToken(); 21231 if (ksh instanceof KeySetHandle) { 21232 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21233 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21234 } 21235 return false; 21236 } 21237 } 21238 21239 @Override 21240 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21241 if (packageName == null || ks == null) { 21242 return false; 21243 } 21244 synchronized(mPackages) { 21245 final PackageParser.Package pkg = mPackages.get(packageName); 21246 if (pkg == null) { 21247 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21248 throw new IllegalArgumentException("Unknown package: " + packageName); 21249 } 21250 IBinder ksh = ks.getToken(); 21251 if (ksh instanceof KeySetHandle) { 21252 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21253 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21254 } 21255 return false; 21256 } 21257 } 21258 21259 private void deletePackageIfUnusedLPr(final String packageName) { 21260 PackageSetting ps = mSettings.mPackages.get(packageName); 21261 if (ps == null) { 21262 return; 21263 } 21264 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21265 // TODO Implement atomic delete if package is unused 21266 // It is currently possible that the package will be deleted even if it is installed 21267 // after this method returns. 21268 mHandler.post(new Runnable() { 21269 public void run() { 21270 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21271 } 21272 }); 21273 } 21274 } 21275 21276 /** 21277 * Check and throw if the given before/after packages would be considered a 21278 * downgrade. 21279 */ 21280 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21281 throws PackageManagerException { 21282 if (after.versionCode < before.mVersionCode) { 21283 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21284 "Update version code " + after.versionCode + " is older than current " 21285 + before.mVersionCode); 21286 } else if (after.versionCode == before.mVersionCode) { 21287 if (after.baseRevisionCode < before.baseRevisionCode) { 21288 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21289 "Update base revision code " + after.baseRevisionCode 21290 + " is older than current " + before.baseRevisionCode); 21291 } 21292 21293 if (!ArrayUtils.isEmpty(after.splitNames)) { 21294 for (int i = 0; i < after.splitNames.length; i++) { 21295 final String splitName = after.splitNames[i]; 21296 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21297 if (j != -1) { 21298 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21299 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21300 "Update split " + splitName + " revision code " 21301 + after.splitRevisionCodes[i] + " is older than current " 21302 + before.splitRevisionCodes[j]); 21303 } 21304 } 21305 } 21306 } 21307 } 21308 } 21309 21310 private static class MoveCallbacks extends Handler { 21311 private static final int MSG_CREATED = 1; 21312 private static final int MSG_STATUS_CHANGED = 2; 21313 21314 private final RemoteCallbackList<IPackageMoveObserver> 21315 mCallbacks = new RemoteCallbackList<>(); 21316 21317 private final SparseIntArray mLastStatus = new SparseIntArray(); 21318 21319 public MoveCallbacks(Looper looper) { 21320 super(looper); 21321 } 21322 21323 public void register(IPackageMoveObserver callback) { 21324 mCallbacks.register(callback); 21325 } 21326 21327 public void unregister(IPackageMoveObserver callback) { 21328 mCallbacks.unregister(callback); 21329 } 21330 21331 @Override 21332 public void handleMessage(Message msg) { 21333 final SomeArgs args = (SomeArgs) msg.obj; 21334 final int n = mCallbacks.beginBroadcast(); 21335 for (int i = 0; i < n; i++) { 21336 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21337 try { 21338 invokeCallback(callback, msg.what, args); 21339 } catch (RemoteException ignored) { 21340 } 21341 } 21342 mCallbacks.finishBroadcast(); 21343 args.recycle(); 21344 } 21345 21346 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21347 throws RemoteException { 21348 switch (what) { 21349 case MSG_CREATED: { 21350 callback.onCreated(args.argi1, (Bundle) args.arg2); 21351 break; 21352 } 21353 case MSG_STATUS_CHANGED: { 21354 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21355 break; 21356 } 21357 } 21358 } 21359 21360 private void notifyCreated(int moveId, Bundle extras) { 21361 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21362 21363 final SomeArgs args = SomeArgs.obtain(); 21364 args.argi1 = moveId; 21365 args.arg2 = extras; 21366 obtainMessage(MSG_CREATED, args).sendToTarget(); 21367 } 21368 21369 private void notifyStatusChanged(int moveId, int status) { 21370 notifyStatusChanged(moveId, status, -1); 21371 } 21372 21373 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21374 Slog.v(TAG, "Move " + moveId + " status " + status); 21375 21376 final SomeArgs args = SomeArgs.obtain(); 21377 args.argi1 = moveId; 21378 args.argi2 = status; 21379 args.arg3 = estMillis; 21380 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21381 21382 synchronized (mLastStatus) { 21383 mLastStatus.put(moveId, status); 21384 } 21385 } 21386 } 21387 21388 private final static class OnPermissionChangeListeners extends Handler { 21389 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21390 21391 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21392 new RemoteCallbackList<>(); 21393 21394 public OnPermissionChangeListeners(Looper looper) { 21395 super(looper); 21396 } 21397 21398 @Override 21399 public void handleMessage(Message msg) { 21400 switch (msg.what) { 21401 case MSG_ON_PERMISSIONS_CHANGED: { 21402 final int uid = msg.arg1; 21403 handleOnPermissionsChanged(uid); 21404 } break; 21405 } 21406 } 21407 21408 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21409 mPermissionListeners.register(listener); 21410 21411 } 21412 21413 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21414 mPermissionListeners.unregister(listener); 21415 } 21416 21417 public void onPermissionsChanged(int uid) { 21418 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21419 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21420 } 21421 } 21422 21423 private void handleOnPermissionsChanged(int uid) { 21424 final int count = mPermissionListeners.beginBroadcast(); 21425 try { 21426 for (int i = 0; i < count; i++) { 21427 IOnPermissionsChangeListener callback = mPermissionListeners 21428 .getBroadcastItem(i); 21429 try { 21430 callback.onPermissionsChanged(uid); 21431 } catch (RemoteException e) { 21432 Log.e(TAG, "Permission listener is dead", e); 21433 } 21434 } 21435 } finally { 21436 mPermissionListeners.finishBroadcast(); 21437 } 21438 } 21439 } 21440 21441 private class PackageManagerInternalImpl extends PackageManagerInternal { 21442 @Override 21443 public void setLocationPackagesProvider(PackagesProvider provider) { 21444 synchronized (mPackages) { 21445 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21446 } 21447 } 21448 21449 @Override 21450 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21451 synchronized (mPackages) { 21452 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21453 } 21454 } 21455 21456 @Override 21457 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21458 synchronized (mPackages) { 21459 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21460 } 21461 } 21462 21463 @Override 21464 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21465 synchronized (mPackages) { 21466 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21467 } 21468 } 21469 21470 @Override 21471 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21472 synchronized (mPackages) { 21473 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21474 } 21475 } 21476 21477 @Override 21478 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21479 synchronized (mPackages) { 21480 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21481 } 21482 } 21483 21484 @Override 21485 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21486 synchronized (mPackages) { 21487 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21488 packageName, userId); 21489 } 21490 } 21491 21492 @Override 21493 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21494 synchronized (mPackages) { 21495 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21496 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21497 packageName, userId); 21498 } 21499 } 21500 21501 @Override 21502 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21503 synchronized (mPackages) { 21504 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21505 packageName, userId); 21506 } 21507 } 21508 21509 @Override 21510 public void setKeepUninstalledPackages(final List<String> packageList) { 21511 Preconditions.checkNotNull(packageList); 21512 List<String> removedFromList = null; 21513 synchronized (mPackages) { 21514 if (mKeepUninstalledPackages != null) { 21515 final int packagesCount = mKeepUninstalledPackages.size(); 21516 for (int i = 0; i < packagesCount; i++) { 21517 String oldPackage = mKeepUninstalledPackages.get(i); 21518 if (packageList != null && packageList.contains(oldPackage)) { 21519 continue; 21520 } 21521 if (removedFromList == null) { 21522 removedFromList = new ArrayList<>(); 21523 } 21524 removedFromList.add(oldPackage); 21525 } 21526 } 21527 mKeepUninstalledPackages = new ArrayList<>(packageList); 21528 if (removedFromList != null) { 21529 final int removedCount = removedFromList.size(); 21530 for (int i = 0; i < removedCount; i++) { 21531 deletePackageIfUnusedLPr(removedFromList.get(i)); 21532 } 21533 } 21534 } 21535 } 21536 21537 @Override 21538 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21539 synchronized (mPackages) { 21540 // If we do not support permission review, done. 21541 if (!mPermissionReviewRequired) { 21542 return false; 21543 } 21544 21545 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21546 if (packageSetting == null) { 21547 return false; 21548 } 21549 21550 // Permission review applies only to apps not supporting the new permission model. 21551 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21552 return false; 21553 } 21554 21555 // Legacy apps have the permission and get user consent on launch. 21556 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21557 return permissionsState.isPermissionReviewRequired(userId); 21558 } 21559 } 21560 21561 @Override 21562 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21563 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21564 } 21565 21566 @Override 21567 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21568 int userId) { 21569 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21570 } 21571 21572 @Override 21573 public void setDeviceAndProfileOwnerPackages( 21574 int deviceOwnerUserId, String deviceOwnerPackage, 21575 SparseArray<String> profileOwnerPackages) { 21576 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21577 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21578 } 21579 21580 @Override 21581 public boolean isPackageDataProtected(int userId, String packageName) { 21582 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21583 } 21584 21585 @Override 21586 public boolean isPackageEphemeral(int userId, String packageName) { 21587 synchronized (mPackages) { 21588 PackageParser.Package p = mPackages.get(packageName); 21589 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21590 } 21591 } 21592 21593 @Override 21594 public boolean wasPackageEverLaunched(String packageName, int userId) { 21595 synchronized (mPackages) { 21596 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21597 } 21598 } 21599 21600 @Override 21601 public void grantRuntimePermission(String packageName, String name, int userId, 21602 boolean overridePolicy) { 21603 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21604 overridePolicy); 21605 } 21606 21607 @Override 21608 public void revokeRuntimePermission(String packageName, String name, int userId, 21609 boolean overridePolicy) { 21610 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21611 overridePolicy); 21612 } 21613 21614 @Override 21615 public String getNameForUid(int uid) { 21616 return PackageManagerService.this.getNameForUid(uid); 21617 } 21618 21619 @Override 21620 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21621 Intent origIntent, String resolvedType, Intent launchIntent, 21622 String callingPackage, int userId) { 21623 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21624 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21625 } 21626 } 21627 21628 @Override 21629 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21630 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21631 synchronized (mPackages) { 21632 final long identity = Binder.clearCallingIdentity(); 21633 try { 21634 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21635 packageNames, userId); 21636 } finally { 21637 Binder.restoreCallingIdentity(identity); 21638 } 21639 } 21640 } 21641 21642 private static void enforceSystemOrPhoneCaller(String tag) { 21643 int callingUid = Binder.getCallingUid(); 21644 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21645 throw new SecurityException( 21646 "Cannot call " + tag + " from UID " + callingUid); 21647 } 21648 } 21649 21650 boolean isHistoricalPackageUsageAvailable() { 21651 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21652 } 21653 21654 /** 21655 * Return a <b>copy</b> of the collection of packages known to the package manager. 21656 * @return A copy of the values of mPackages. 21657 */ 21658 Collection<PackageParser.Package> getPackages() { 21659 synchronized (mPackages) { 21660 return new ArrayList<>(mPackages.values()); 21661 } 21662 } 21663 21664 /** 21665 * Logs process start information (including base APK hash) to the security log. 21666 * @hide 21667 */ 21668 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21669 String apkFile, int pid) { 21670 if (!SecurityLog.isLoggingEnabled()) { 21671 return; 21672 } 21673 Bundle data = new Bundle(); 21674 data.putLong("startTimestamp", System.currentTimeMillis()); 21675 data.putString("processName", processName); 21676 data.putInt("uid", uid); 21677 data.putString("seinfo", seinfo); 21678 data.putString("apkFile", apkFile); 21679 data.putInt("pid", pid); 21680 Message msg = mProcessLoggingHandler.obtainMessage( 21681 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21682 msg.setData(data); 21683 mProcessLoggingHandler.sendMessage(msg); 21684 } 21685 21686 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21687 return mCompilerStats.getPackageStats(pkgName); 21688 } 21689 21690 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21691 return getOrCreateCompilerPackageStats(pkg.packageName); 21692 } 21693 21694 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21695 return mCompilerStats.getOrCreatePackageStats(pkgName); 21696 } 21697 21698 public void deleteCompilerPackageStats(String pkgName) { 21699 mCompilerStats.deletePackageStats(pkgName); 21700 } 21701} 21702