PackageManagerService.java revision 6453db68ca47cd9c686142b8eab3c98f51fd19b4
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.app.ActivityManager; 106import android.app.AppOpsManager; 107import android.app.IActivityManager; 108import android.app.ResourcesManager; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.ContentResolver; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralRequest; 128import android.content.pm.EphemeralResolveInfo; 129import android.content.pm.EphemeralResponse; 130import android.content.pm.FeatureInfo; 131import android.content.pm.IOnPermissionsChangeListener; 132import android.content.pm.IPackageDataObserver; 133import android.content.pm.IPackageDeleteObserver; 134import android.content.pm.IPackageDeleteObserver2; 135import android.content.pm.IPackageInstallObserver2; 136import android.content.pm.IPackageInstaller; 137import android.content.pm.IPackageManager; 138import android.content.pm.IPackageMoveObserver; 139import android.content.pm.IPackageStatsObserver; 140import android.content.pm.InstrumentationInfo; 141import android.content.pm.IntentFilterVerificationInfo; 142import android.content.pm.KeySet; 143import android.content.pm.PackageCleanItem; 144import android.content.pm.PackageInfo; 145import android.content.pm.PackageInfoLite; 146import android.content.pm.PackageInstaller; 147import android.content.pm.PackageManager; 148import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 149import android.content.pm.PackageManagerInternal; 150import android.content.pm.PackageParser; 151import android.content.pm.PackageParser.ActivityIntentInfo; 152import android.content.pm.PackageParser.PackageLite; 153import android.content.pm.PackageParser.PackageParserException; 154import android.content.pm.PackageStats; 155import android.content.pm.PackageUserState; 156import android.content.pm.ParceledListSlice; 157import android.content.pm.PermissionGroupInfo; 158import android.content.pm.PermissionInfo; 159import android.content.pm.ProviderInfo; 160import android.content.pm.ResolveInfo; 161import android.content.pm.ServiceInfo; 162import android.content.pm.Signature; 163import android.content.pm.UserInfo; 164import android.content.pm.VerifierDeviceIdentity; 165import android.content.pm.VerifierInfo; 166import android.content.res.Resources; 167import android.graphics.Bitmap; 168import android.hardware.display.DisplayManager; 169import android.net.Uri; 170import android.os.Binder; 171import android.os.Build; 172import android.os.Bundle; 173import android.os.Debug; 174import android.os.Environment; 175import android.os.Environment.UserEnvironment; 176import android.os.FileUtils; 177import android.os.Handler; 178import android.os.IBinder; 179import android.os.Looper; 180import android.os.Message; 181import android.os.Parcel; 182import android.os.ParcelFileDescriptor; 183import android.os.PatternMatcher; 184import android.os.Process; 185import android.os.RemoteCallbackList; 186import android.os.RemoteException; 187import android.os.ResultReceiver; 188import android.os.SELinux; 189import android.os.ServiceManager; 190import android.os.ShellCallback; 191import android.os.SystemClock; 192import android.os.SystemProperties; 193import android.os.Trace; 194import android.os.UserHandle; 195import android.os.UserManager; 196import android.os.UserManagerInternal; 197import android.os.storage.IStorageManager; 198import android.os.storage.StorageManagerInternal; 199import android.os.storage.StorageEventListener; 200import android.os.storage.StorageManager; 201import android.os.storage.VolumeInfo; 202import android.os.storage.VolumeRecord; 203import android.provider.Settings.Global; 204import android.provider.Settings.Secure; 205import android.security.KeyStore; 206import android.security.SystemKeyStore; 207import android.system.ErrnoException; 208import android.system.Os; 209import android.text.TextUtils; 210import android.text.format.DateUtils; 211import android.util.ArrayMap; 212import android.util.ArraySet; 213import android.util.Base64; 214import android.util.DisplayMetrics; 215import android.util.EventLog; 216import android.util.ExceptionUtils; 217import android.util.Log; 218import android.util.LogPrinter; 219import android.util.MathUtils; 220import android.util.Pair; 221import android.util.PrintStreamPrinter; 222import android.util.Slog; 223import android.util.SparseArray; 224import android.util.SparseBooleanArray; 225import android.util.SparseIntArray; 226import android.util.Xml; 227import android.util.jar.StrictJarFile; 228import android.view.Display; 229 230import com.android.internal.R; 231import com.android.internal.annotations.GuardedBy; 232import com.android.internal.app.IMediaContainerService; 233import com.android.internal.app.ResolverActivity; 234import com.android.internal.content.NativeLibraryHelper; 235import com.android.internal.content.PackageHelper; 236import com.android.internal.logging.MetricsLogger; 237import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 238import com.android.internal.os.IParcelFileDescriptorFactory; 239import com.android.internal.os.RoSystemProperties; 240import com.android.internal.os.SomeArgs; 241import com.android.internal.os.Zygote; 242import com.android.internal.telephony.CarrierAppUtils; 243import com.android.internal.util.ArrayUtils; 244import com.android.internal.util.FastPrintWriter; 245import com.android.internal.util.FastXmlSerializer; 246import com.android.internal.util.IndentingPrintWriter; 247import com.android.internal.util.Preconditions; 248import com.android.internal.util.XmlUtils; 249import com.android.server.AttributeCache; 250import com.android.server.EventLogTags; 251import com.android.server.FgThread; 252import com.android.server.IntentResolver; 253import com.android.server.LocalServices; 254import com.android.server.ServiceThread; 255import com.android.server.SystemConfig; 256import com.android.server.Watchdog; 257import com.android.server.net.NetworkPolicyManagerInternal; 258import com.android.server.pm.Installer.InstallerException; 259import com.android.server.pm.PermissionsState.PermissionState; 260import com.android.server.pm.Settings.DatabaseVersion; 261import com.android.server.pm.Settings.VersionInfo; 262import com.android.server.pm.dex.DexManager; 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.HashMap; 307import java.util.Iterator; 308import java.util.List; 309import java.util.Map; 310import java.util.Objects; 311import java.util.Set; 312import java.util.concurrent.CountDownLatch; 313import java.util.concurrent.TimeUnit; 314import java.util.concurrent.atomic.AtomicBoolean; 315import java.util.concurrent.atomic.AtomicInteger; 316 317/** 318 * Keep track of all those APKs everywhere. 319 * <p> 320 * Internally there are two important locks: 321 * <ul> 322 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 323 * and other related state. It is a fine-grained lock that should only be held 324 * momentarily, as it's one of the most contended locks in the system. 325 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 326 * operations typically involve heavy lifting of application data on disk. Since 327 * {@code installd} is single-threaded, and it's operations can often be slow, 328 * this lock should never be acquired while already holding {@link #mPackages}. 329 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 330 * holding {@link #mInstallLock}. 331 * </ul> 332 * Many internal methods rely on the caller to hold the appropriate locks, and 333 * this contract is expressed through method name suffixes: 334 * <ul> 335 * <li>fooLI(): the caller must hold {@link #mInstallLock} 336 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 337 * being modified must be frozen 338 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 339 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 340 * </ul> 341 * <p> 342 * Because this class is very central to the platform's security; please run all 343 * CTS and unit tests whenever making modifications: 344 * 345 * <pre> 346 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 347 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 348 * </pre> 349 */ 350public class PackageManagerService extends IPackageManager.Stub { 351 static final String TAG = "PackageManager"; 352 static final boolean DEBUG_SETTINGS = false; 353 static final boolean DEBUG_PREFERRED = false; 354 static final boolean DEBUG_UPGRADE = false; 355 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 356 private static final boolean DEBUG_BACKUP = false; 357 private static final boolean DEBUG_INSTALL = false; 358 private static final boolean DEBUG_REMOVE = false; 359 private static final boolean DEBUG_BROADCASTS = false; 360 private static final boolean DEBUG_SHOW_INFO = false; 361 private static final boolean DEBUG_PACKAGE_INFO = false; 362 private static final boolean DEBUG_INTENT_MATCHING = false; 363 private static final boolean DEBUG_PACKAGE_SCANNING = false; 364 private static final boolean DEBUG_VERIFY = false; 365 private static final boolean DEBUG_FILTERS = false; 366 367 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 368 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 369 // user, but by default initialize to this. 370 static final boolean DEBUG_DEXOPT = false; 371 372 private static final boolean DEBUG_ABI_SELECTION = false; 373 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 374 private static final boolean DEBUG_TRIAGED_MISSING = false; 375 private static final boolean DEBUG_APP_DATA = false; 376 377 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 378 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 379 380 private static final boolean DISABLE_EPHEMERAL_APPS = false; 381 private static final boolean HIDE_EPHEMERAL_APIS = true; 382 383 private static final boolean ENABLE_QUOTA = 384 SystemProperties.getBoolean("persist.fw.quota", false); 385 386 private static final int RADIO_UID = Process.PHONE_UID; 387 private static final int LOG_UID = Process.LOG_UID; 388 private static final int NFC_UID = Process.NFC_UID; 389 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 390 private static final int SHELL_UID = Process.SHELL_UID; 391 392 // Cap the size of permission trees that 3rd party apps can define 393 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 394 395 // Suffix used during package installation when copying/moving 396 // package apks to install directory. 397 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 398 399 static final int SCAN_NO_DEX = 1<<1; 400 static final int SCAN_FORCE_DEX = 1<<2; 401 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 402 static final int SCAN_NEW_INSTALL = 1<<4; 403 static final int SCAN_UPDATE_TIME = 1<<5; 404 static final int SCAN_BOOTING = 1<<6; 405 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 406 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 407 static final int SCAN_REPLACING = 1<<9; 408 static final int SCAN_REQUIRE_KNOWN = 1<<10; 409 static final int SCAN_MOVE = 1<<11; 410 static final int SCAN_INITIAL = 1<<12; 411 static final int SCAN_CHECK_ONLY = 1<<13; 412 static final int SCAN_DONT_KILL_APP = 1<<14; 413 static final int SCAN_IGNORE_FROZEN = 1<<15; 414 static final int REMOVE_CHATTY = 1<<16; 415 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 416 417 private static final int[] EMPTY_INT_ARRAY = new int[0]; 418 419 /** 420 * Timeout (in milliseconds) after which the watchdog should declare that 421 * our handler thread is wedged. The usual default for such things is one 422 * minute but we sometimes do very lengthy I/O operations on this thread, 423 * such as installing multi-gigabyte applications, so ours needs to be longer. 424 */ 425 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 426 427 /** 428 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 429 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 430 * settings entry if available, otherwise we use the hardcoded default. If it's been 431 * more than this long since the last fstrim, we force one during the boot sequence. 432 * 433 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 434 * one gets run at the next available charging+idle time. This final mandatory 435 * no-fstrim check kicks in only of the other scheduling criteria is never met. 436 */ 437 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 438 439 /** 440 * Whether verification is enabled by default. 441 */ 442 private static final boolean DEFAULT_VERIFY_ENABLE = true; 443 444 /** 445 * The default maximum time to wait for the verification agent to return in 446 * milliseconds. 447 */ 448 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 449 450 /** 451 * The default response for package verification timeout. 452 * 453 * This can be either PackageManager.VERIFICATION_ALLOW or 454 * PackageManager.VERIFICATION_REJECT. 455 */ 456 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 457 458 static final String PLATFORM_PACKAGE_NAME = "android"; 459 460 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 461 462 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 463 DEFAULT_CONTAINER_PACKAGE, 464 "com.android.defcontainer.DefaultContainerService"); 465 466 private static final String KILL_APP_REASON_GIDS_CHANGED = 467 "permission grant or revoke changed gids"; 468 469 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 470 "permissions revoked"; 471 472 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 473 474 private static final String PACKAGE_SCHEME = "package"; 475 476 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 477 /** 478 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 479 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 480 * VENDOR_OVERLAY_DIR. 481 */ 482 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 483 /** 484 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 485 * is in VENDOR_OVERLAY_THEME_PROPERTY. 486 */ 487 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 488 = "persist.vendor.overlay.theme"; 489 490 /** Permission grant: not grant the permission. */ 491 private static final int GRANT_DENIED = 1; 492 493 /** Permission grant: grant the permission as an install permission. */ 494 private static final int GRANT_INSTALL = 2; 495 496 /** Permission grant: grant the permission as a runtime one. */ 497 private static final int GRANT_RUNTIME = 3; 498 499 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 500 private static final int GRANT_UPGRADE = 4; 501 502 /** Canonical intent used to identify what counts as a "web browser" app */ 503 private static final Intent sBrowserIntent; 504 static { 505 sBrowserIntent = new Intent(); 506 sBrowserIntent.setAction(Intent.ACTION_VIEW); 507 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 508 sBrowserIntent.setData(Uri.parse("http:")); 509 } 510 511 /** 512 * The set of all protected actions [i.e. those actions for which a high priority 513 * intent filter is disallowed]. 514 */ 515 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 516 static { 517 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 518 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 519 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 520 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 521 } 522 523 // Compilation reasons. 524 public static final int REASON_FIRST_BOOT = 0; 525 public static final int REASON_BOOT = 1; 526 public static final int REASON_INSTALL = 2; 527 public static final int REASON_BACKGROUND_DEXOPT = 3; 528 public static final int REASON_AB_OTA = 4; 529 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 530 public static final int REASON_SHARED_APK = 6; 531 public static final int REASON_FORCED_DEXOPT = 7; 532 public static final int REASON_CORE_APP = 8; 533 534 public static final int REASON_LAST = REASON_CORE_APP; 535 536 /** Special library name that skips shared libraries check during compilation. */ 537 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 538 539 /** All dangerous permission names in the same order as the events in MetricsEvent */ 540 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 541 Manifest.permission.READ_CALENDAR, 542 Manifest.permission.WRITE_CALENDAR, 543 Manifest.permission.CAMERA, 544 Manifest.permission.READ_CONTACTS, 545 Manifest.permission.WRITE_CONTACTS, 546 Manifest.permission.GET_ACCOUNTS, 547 Manifest.permission.ACCESS_FINE_LOCATION, 548 Manifest.permission.ACCESS_COARSE_LOCATION, 549 Manifest.permission.RECORD_AUDIO, 550 Manifest.permission.READ_PHONE_STATE, 551 Manifest.permission.CALL_PHONE, 552 Manifest.permission.READ_CALL_LOG, 553 Manifest.permission.WRITE_CALL_LOG, 554 Manifest.permission.ADD_VOICEMAIL, 555 Manifest.permission.USE_SIP, 556 Manifest.permission.PROCESS_OUTGOING_CALLS, 557 Manifest.permission.READ_CELL_BROADCASTS, 558 Manifest.permission.BODY_SENSORS, 559 Manifest.permission.SEND_SMS, 560 Manifest.permission.RECEIVE_SMS, 561 Manifest.permission.READ_SMS, 562 Manifest.permission.RECEIVE_WAP_PUSH, 563 Manifest.permission.RECEIVE_MMS, 564 Manifest.permission.READ_EXTERNAL_STORAGE, 565 Manifest.permission.WRITE_EXTERNAL_STORAGE, 566 Manifest.permission.READ_PHONE_NUMBER); 567 568 569 /** 570 * Version number for the package parser cache. Increment this whenever the format or 571 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 572 */ 573 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 574 575 /** 576 * Whether the package parser cache is enabled. 577 */ 578 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 579 580 final ServiceThread mHandlerThread; 581 582 final PackageHandler mHandler; 583 584 private final ProcessLoggingHandler mProcessLoggingHandler; 585 586 /** 587 * Messages for {@link #mHandler} that need to wait for system ready before 588 * being dispatched. 589 */ 590 private ArrayList<Message> mPostSystemReadyMessages; 591 592 final int mSdkVersion = Build.VERSION.SDK_INT; 593 594 final Context mContext; 595 final boolean mFactoryTest; 596 final boolean mOnlyCore; 597 final DisplayMetrics mMetrics; 598 final int mDefParseFlags; 599 final String[] mSeparateProcesses; 600 final boolean mIsUpgrade; 601 final boolean mIsPreNUpgrade; 602 final boolean mIsPreNMR1Upgrade; 603 604 @GuardedBy("mPackages") 605 private boolean mDexOptDialogShown; 606 607 /** The location for ASEC container files on internal storage. */ 608 final String mAsecInternalPath; 609 610 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 611 // LOCK HELD. Can be called with mInstallLock held. 612 @GuardedBy("mInstallLock") 613 final Installer mInstaller; 614 615 /** Directory where installed third-party apps stored */ 616 final File mAppInstallDir; 617 final File mEphemeralInstallDir; 618 619 /** 620 * Directory to which applications installed internally have their 621 * 32 bit native libraries copied. 622 */ 623 private File mAppLib32InstallDir; 624 625 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 626 // apps. 627 final File mDrmAppPrivateInstallDir; 628 629 // ---------------------------------------------------------------- 630 631 // Lock for state used when installing and doing other long running 632 // operations. Methods that must be called with this lock held have 633 // the suffix "LI". 634 final Object mInstallLock = new Object(); 635 636 // ---------------------------------------------------------------- 637 638 // Keys are String (package name), values are Package. This also serves 639 // as the lock for the global state. Methods that must be called with 640 // this lock held have the prefix "LP". 641 @GuardedBy("mPackages") 642 final ArrayMap<String, PackageParser.Package> mPackages = 643 new ArrayMap<String, PackageParser.Package>(); 644 645 final ArrayMap<String, Set<String>> mKnownCodebase = 646 new ArrayMap<String, Set<String>>(); 647 648 // Tracks available target package names -> overlay package paths. 649 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 650 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 651 652 /** 653 * Tracks new system packages [received in an OTA] that we expect to 654 * find updated user-installed versions. Keys are package name, values 655 * are package location. 656 */ 657 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 658 /** 659 * Tracks high priority intent filters for protected actions. During boot, certain 660 * filter actions are protected and should never be allowed to have a high priority 661 * intent filter for them. However, there is one, and only one exception -- the 662 * setup wizard. It must be able to define a high priority intent filter for these 663 * actions to ensure there are no escapes from the wizard. We need to delay processing 664 * of these during boot as we need to look at all of the system packages in order 665 * to know which component is the setup wizard. 666 */ 667 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 668 /** 669 * Whether or not processing protected filters should be deferred. 670 */ 671 private boolean mDeferProtectedFilters = true; 672 673 /** 674 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 675 */ 676 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 677 /** 678 * Whether or not system app permissions should be promoted from install to runtime. 679 */ 680 boolean mPromoteSystemApps; 681 682 @GuardedBy("mPackages") 683 final Settings mSettings; 684 685 /** 686 * Set of package names that are currently "frozen", which means active 687 * surgery is being done on the code/data for that package. The platform 688 * will refuse to launch frozen packages to avoid race conditions. 689 * 690 * @see PackageFreezer 691 */ 692 @GuardedBy("mPackages") 693 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 694 695 final ProtectedPackages mProtectedPackages; 696 697 boolean mFirstBoot; 698 699 // System configuration read by SystemConfig. 700 final int[] mGlobalGids; 701 final SparseArray<ArraySet<String>> mSystemPermissions; 702 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 703 704 // If mac_permissions.xml was found for seinfo labeling. 705 boolean mFoundPolicyFile; 706 707 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 708 709 public static final class SharedLibraryEntry { 710 public final String path; 711 public final String apk; 712 713 SharedLibraryEntry(String _path, String _apk) { 714 path = _path; 715 apk = _apk; 716 } 717 } 718 719 // Currently known shared libraries. 720 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 721 new ArrayMap<String, SharedLibraryEntry>(); 722 723 // All available activities, for your resolving pleasure. 724 final ActivityIntentResolver mActivities = 725 new ActivityIntentResolver(); 726 727 // All available receivers, for your resolving pleasure. 728 final ActivityIntentResolver mReceivers = 729 new ActivityIntentResolver(); 730 731 // All available services, for your resolving pleasure. 732 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 733 734 // All available providers, for your resolving pleasure. 735 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 736 737 // Mapping from provider base names (first directory in content URI codePath) 738 // to the provider information. 739 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 740 new ArrayMap<String, PackageParser.Provider>(); 741 742 // Mapping from instrumentation class names to info about them. 743 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 744 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 745 746 // Mapping from permission names to info about them. 747 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 748 new ArrayMap<String, PackageParser.PermissionGroup>(); 749 750 // Packages whose data we have transfered into another package, thus 751 // should no longer exist. 752 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 753 754 // Broadcast actions that are only available to the system. 755 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 756 757 /** List of packages waiting for verification. */ 758 final SparseArray<PackageVerificationState> mPendingVerification 759 = new SparseArray<PackageVerificationState>(); 760 761 /** Set of packages associated with each app op permission. */ 762 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 763 764 final PackageInstallerService mInstallerService; 765 766 private final PackageDexOptimizer mPackageDexOptimizer; 767 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 768 // is used by other apps). 769 private final DexManager mDexManager; 770 771 private AtomicInteger mNextMoveId = new AtomicInteger(); 772 private final MoveCallbacks mMoveCallbacks; 773 774 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 775 776 // Cache of users who need badging. 777 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 778 779 /** Token for keys in mPendingVerification. */ 780 private int mPendingVerificationToken = 0; 781 782 volatile boolean mSystemReady; 783 volatile boolean mSafeMode; 784 volatile boolean mHasSystemUidErrors; 785 786 ApplicationInfo mAndroidApplication; 787 final ActivityInfo mResolveActivity = new ActivityInfo(); 788 final ResolveInfo mResolveInfo = new ResolveInfo(); 789 ComponentName mResolveComponentName; 790 PackageParser.Package mPlatformPackage; 791 ComponentName mCustomResolverComponentName; 792 793 boolean mResolverReplaced = false; 794 795 private final @Nullable ComponentName mIntentFilterVerifierComponent; 796 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 797 798 private int mIntentFilterVerificationToken = 0; 799 800 /** The service connection to the ephemeral resolver */ 801 final EphemeralResolverConnection mEphemeralResolverConnection; 802 803 /** Component used to install ephemeral applications */ 804 ComponentName mEphemeralInstallerComponent; 805 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 806 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 807 808 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 809 = new SparseArray<IntentFilterVerificationState>(); 810 811 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 812 813 // List of packages names to keep cached, even if they are uninstalled for all users 814 private List<String> mKeepUninstalledPackages; 815 816 private UserManagerInternal mUserManagerInternal; 817 818 private File mCacheDir; 819 820 private static class IFVerificationParams { 821 PackageParser.Package pkg; 822 boolean replacing; 823 int userId; 824 int verifierUid; 825 826 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 827 int _userId, int _verifierUid) { 828 pkg = _pkg; 829 replacing = _replacing; 830 userId = _userId; 831 replacing = _replacing; 832 verifierUid = _verifierUid; 833 } 834 } 835 836 private interface IntentFilterVerifier<T extends IntentFilter> { 837 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 838 T filter, String packageName); 839 void startVerifications(int userId); 840 void receiveVerificationResponse(int verificationId); 841 } 842 843 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 844 private Context mContext; 845 private ComponentName mIntentFilterVerifierComponent; 846 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 847 848 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 849 mContext = context; 850 mIntentFilterVerifierComponent = verifierComponent; 851 } 852 853 private String getDefaultScheme() { 854 return IntentFilter.SCHEME_HTTPS; 855 } 856 857 @Override 858 public void startVerifications(int userId) { 859 // Launch verifications requests 860 int count = mCurrentIntentFilterVerifications.size(); 861 for (int n=0; n<count; n++) { 862 int verificationId = mCurrentIntentFilterVerifications.get(n); 863 final IntentFilterVerificationState ivs = 864 mIntentFilterVerificationStates.get(verificationId); 865 866 String packageName = ivs.getPackageName(); 867 868 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 869 final int filterCount = filters.size(); 870 ArraySet<String> domainsSet = new ArraySet<>(); 871 for (int m=0; m<filterCount; m++) { 872 PackageParser.ActivityIntentInfo filter = filters.get(m); 873 domainsSet.addAll(filter.getHostsList()); 874 } 875 synchronized (mPackages) { 876 if (mSettings.createIntentFilterVerificationIfNeededLPw( 877 packageName, domainsSet) != null) { 878 scheduleWriteSettingsLocked(); 879 } 880 } 881 sendVerificationRequest(userId, verificationId, ivs); 882 } 883 mCurrentIntentFilterVerifications.clear(); 884 } 885 886 private void sendVerificationRequest(int userId, int verificationId, 887 IntentFilterVerificationState ivs) { 888 889 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 890 verificationIntent.putExtra( 891 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 892 verificationId); 893 verificationIntent.putExtra( 894 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 895 getDefaultScheme()); 896 verificationIntent.putExtra( 897 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 898 ivs.getHostsString()); 899 verificationIntent.putExtra( 900 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 901 ivs.getPackageName()); 902 verificationIntent.setComponent(mIntentFilterVerifierComponent); 903 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 904 905 UserHandle user = new UserHandle(userId); 906 mContext.sendBroadcastAsUser(verificationIntent, user); 907 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 908 "Sending IntentFilter verification broadcast"); 909 } 910 911 public void receiveVerificationResponse(int verificationId) { 912 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 913 914 final boolean verified = ivs.isVerified(); 915 916 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 917 final int count = filters.size(); 918 if (DEBUG_DOMAIN_VERIFICATION) { 919 Slog.i(TAG, "Received verification response " + verificationId 920 + " for " + count + " filters, verified=" + verified); 921 } 922 for (int n=0; n<count; n++) { 923 PackageParser.ActivityIntentInfo filter = filters.get(n); 924 filter.setVerified(verified); 925 926 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 927 + " verified with result:" + verified + " and hosts:" 928 + ivs.getHostsString()); 929 } 930 931 mIntentFilterVerificationStates.remove(verificationId); 932 933 final String packageName = ivs.getPackageName(); 934 IntentFilterVerificationInfo ivi = null; 935 936 synchronized (mPackages) { 937 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 938 } 939 if (ivi == null) { 940 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 941 + verificationId + " packageName:" + packageName); 942 return; 943 } 944 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 945 "Updating IntentFilterVerificationInfo for package " + packageName 946 +" verificationId:" + verificationId); 947 948 synchronized (mPackages) { 949 if (verified) { 950 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 951 } else { 952 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 953 } 954 scheduleWriteSettingsLocked(); 955 956 final int userId = ivs.getUserId(); 957 if (userId != UserHandle.USER_ALL) { 958 final int userStatus = 959 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 960 961 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 962 boolean needUpdate = false; 963 964 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 965 // already been set by the User thru the Disambiguation dialog 966 switch (userStatus) { 967 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 968 if (verified) { 969 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 970 } else { 971 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 972 } 973 needUpdate = true; 974 break; 975 976 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 977 if (verified) { 978 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 979 needUpdate = true; 980 } 981 break; 982 983 default: 984 // Nothing to do 985 } 986 987 if (needUpdate) { 988 mSettings.updateIntentFilterVerificationStatusLPw( 989 packageName, updatedStatus, userId); 990 scheduleWritePackageRestrictionsLocked(userId); 991 } 992 } 993 } 994 } 995 996 @Override 997 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 998 ActivityIntentInfo filter, String packageName) { 999 if (!hasValidDomains(filter)) { 1000 return false; 1001 } 1002 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1003 if (ivs == null) { 1004 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1005 packageName); 1006 } 1007 if (DEBUG_DOMAIN_VERIFICATION) { 1008 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1009 } 1010 ivs.addFilter(filter); 1011 return true; 1012 } 1013 1014 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1015 int userId, int verificationId, String packageName) { 1016 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1017 verifierUid, userId, packageName); 1018 ivs.setPendingState(); 1019 synchronized (mPackages) { 1020 mIntentFilterVerificationStates.append(verificationId, ivs); 1021 mCurrentIntentFilterVerifications.add(verificationId); 1022 } 1023 return ivs; 1024 } 1025 } 1026 1027 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1028 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1029 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1030 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1031 } 1032 1033 // Set of pending broadcasts for aggregating enable/disable of components. 1034 static class PendingPackageBroadcasts { 1035 // for each user id, a map of <package name -> components within that package> 1036 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1037 1038 public PendingPackageBroadcasts() { 1039 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1040 } 1041 1042 public ArrayList<String> get(int userId, String packageName) { 1043 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1044 return packages.get(packageName); 1045 } 1046 1047 public void put(int userId, String packageName, ArrayList<String> components) { 1048 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1049 packages.put(packageName, components); 1050 } 1051 1052 public void remove(int userId, String packageName) { 1053 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1054 if (packages != null) { 1055 packages.remove(packageName); 1056 } 1057 } 1058 1059 public void remove(int userId) { 1060 mUidMap.remove(userId); 1061 } 1062 1063 public int userIdCount() { 1064 return mUidMap.size(); 1065 } 1066 1067 public int userIdAt(int n) { 1068 return mUidMap.keyAt(n); 1069 } 1070 1071 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1072 return mUidMap.get(userId); 1073 } 1074 1075 public int size() { 1076 // total number of pending broadcast entries across all userIds 1077 int num = 0; 1078 for (int i = 0; i< mUidMap.size(); i++) { 1079 num += mUidMap.valueAt(i).size(); 1080 } 1081 return num; 1082 } 1083 1084 public void clear() { 1085 mUidMap.clear(); 1086 } 1087 1088 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1089 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1090 if (map == null) { 1091 map = new ArrayMap<String, ArrayList<String>>(); 1092 mUidMap.put(userId, map); 1093 } 1094 return map; 1095 } 1096 } 1097 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1098 1099 // Service Connection to remote media container service to copy 1100 // package uri's from external media onto secure containers 1101 // or internal storage. 1102 private IMediaContainerService mContainerService = null; 1103 1104 static final int SEND_PENDING_BROADCAST = 1; 1105 static final int MCS_BOUND = 3; 1106 static final int END_COPY = 4; 1107 static final int INIT_COPY = 5; 1108 static final int MCS_UNBIND = 6; 1109 static final int START_CLEANING_PACKAGE = 7; 1110 static final int FIND_INSTALL_LOC = 8; 1111 static final int POST_INSTALL = 9; 1112 static final int MCS_RECONNECT = 10; 1113 static final int MCS_GIVE_UP = 11; 1114 static final int UPDATED_MEDIA_STATUS = 12; 1115 static final int WRITE_SETTINGS = 13; 1116 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1117 static final int PACKAGE_VERIFIED = 15; 1118 static final int CHECK_PENDING_VERIFICATION = 16; 1119 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1120 static final int INTENT_FILTER_VERIFIED = 18; 1121 static final int WRITE_PACKAGE_LIST = 19; 1122 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1123 1124 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1125 1126 // Delay time in millisecs 1127 static final int BROADCAST_DELAY = 10 * 1000; 1128 1129 static UserManagerService sUserManager; 1130 1131 // Stores a list of users whose package restrictions file needs to be updated 1132 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1133 1134 final private DefaultContainerConnection mDefContainerConn = 1135 new DefaultContainerConnection(); 1136 class DefaultContainerConnection implements ServiceConnection { 1137 public void onServiceConnected(ComponentName name, IBinder service) { 1138 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1139 final IMediaContainerService imcs = IMediaContainerService.Stub 1140 .asInterface(Binder.allowBlocking(service)); 1141 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1142 } 1143 1144 public void onServiceDisconnected(ComponentName name) { 1145 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1146 } 1147 } 1148 1149 // Recordkeeping of restore-after-install operations that are currently in flight 1150 // between the Package Manager and the Backup Manager 1151 static class PostInstallData { 1152 public InstallArgs args; 1153 public PackageInstalledInfo res; 1154 1155 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1156 args = _a; 1157 res = _r; 1158 } 1159 } 1160 1161 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1162 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1163 1164 // XML tags for backup/restore of various bits of state 1165 private static final String TAG_PREFERRED_BACKUP = "pa"; 1166 private static final String TAG_DEFAULT_APPS = "da"; 1167 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1168 1169 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1170 private static final String TAG_ALL_GRANTS = "rt-grants"; 1171 private static final String TAG_GRANT = "grant"; 1172 private static final String ATTR_PACKAGE_NAME = "pkg"; 1173 1174 private static final String TAG_PERMISSION = "perm"; 1175 private static final String ATTR_PERMISSION_NAME = "name"; 1176 private static final String ATTR_IS_GRANTED = "g"; 1177 private static final String ATTR_USER_SET = "set"; 1178 private static final String ATTR_USER_FIXED = "fixed"; 1179 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1180 1181 // System/policy permission grants are not backed up 1182 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1183 FLAG_PERMISSION_POLICY_FIXED 1184 | FLAG_PERMISSION_SYSTEM_FIXED 1185 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1186 1187 // And we back up these user-adjusted states 1188 private static final int USER_RUNTIME_GRANT_MASK = 1189 FLAG_PERMISSION_USER_SET 1190 | FLAG_PERMISSION_USER_FIXED 1191 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1192 1193 final @Nullable String mRequiredVerifierPackage; 1194 final @NonNull String mRequiredInstallerPackage; 1195 final @NonNull String mRequiredUninstallerPackage; 1196 final @Nullable String mSetupWizardPackage; 1197 final @Nullable String mStorageManagerPackage; 1198 final @NonNull String mServicesSystemSharedLibraryPackageName; 1199 final @NonNull String mSharedSystemSharedLibraryPackageName; 1200 1201 final boolean mPermissionReviewRequired; 1202 1203 private final PackageUsage mPackageUsage = new PackageUsage(); 1204 private final CompilerStats mCompilerStats = new CompilerStats(); 1205 1206 class PackageHandler extends Handler { 1207 private boolean mBound = false; 1208 final ArrayList<HandlerParams> mPendingInstalls = 1209 new ArrayList<HandlerParams>(); 1210 1211 private boolean connectToService() { 1212 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1213 " DefaultContainerService"); 1214 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1215 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1216 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1217 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1218 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1219 mBound = true; 1220 return true; 1221 } 1222 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1223 return false; 1224 } 1225 1226 private void disconnectService() { 1227 mContainerService = null; 1228 mBound = false; 1229 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1230 mContext.unbindService(mDefContainerConn); 1231 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1232 } 1233 1234 PackageHandler(Looper looper) { 1235 super(looper); 1236 } 1237 1238 public void handleMessage(Message msg) { 1239 try { 1240 doHandleMessage(msg); 1241 } finally { 1242 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1243 } 1244 } 1245 1246 void doHandleMessage(Message msg) { 1247 switch (msg.what) { 1248 case INIT_COPY: { 1249 HandlerParams params = (HandlerParams) msg.obj; 1250 int idx = mPendingInstalls.size(); 1251 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1252 // If a bind was already initiated we dont really 1253 // need to do anything. The pending install 1254 // will be processed later on. 1255 if (!mBound) { 1256 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1257 System.identityHashCode(mHandler)); 1258 // If this is the only one pending we might 1259 // have to bind to the service again. 1260 if (!connectToService()) { 1261 Slog.e(TAG, "Failed to bind to media container service"); 1262 params.serviceError(); 1263 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1264 System.identityHashCode(mHandler)); 1265 if (params.traceMethod != null) { 1266 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1267 params.traceCookie); 1268 } 1269 return; 1270 } else { 1271 // Once we bind to the service, the first 1272 // pending request will be processed. 1273 mPendingInstalls.add(idx, params); 1274 } 1275 } else { 1276 mPendingInstalls.add(idx, params); 1277 // Already bound to the service. Just make 1278 // sure we trigger off processing the first request. 1279 if (idx == 0) { 1280 mHandler.sendEmptyMessage(MCS_BOUND); 1281 } 1282 } 1283 break; 1284 } 1285 case MCS_BOUND: { 1286 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1287 if (msg.obj != null) { 1288 mContainerService = (IMediaContainerService) msg.obj; 1289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1290 System.identityHashCode(mHandler)); 1291 } 1292 if (mContainerService == null) { 1293 if (!mBound) { 1294 // Something seriously wrong since we are not bound and we are not 1295 // waiting for connection. Bail out. 1296 Slog.e(TAG, "Cannot bind to media container service"); 1297 for (HandlerParams params : mPendingInstalls) { 1298 // Indicate service bind error 1299 params.serviceError(); 1300 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1301 System.identityHashCode(params)); 1302 if (params.traceMethod != null) { 1303 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1304 params.traceMethod, params.traceCookie); 1305 } 1306 return; 1307 } 1308 mPendingInstalls.clear(); 1309 } else { 1310 Slog.w(TAG, "Waiting to connect to media container service"); 1311 } 1312 } else if (mPendingInstalls.size() > 0) { 1313 HandlerParams params = mPendingInstalls.get(0); 1314 if (params != null) { 1315 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1316 System.identityHashCode(params)); 1317 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1318 if (params.startCopy()) { 1319 // We are done... look for more work or to 1320 // go idle. 1321 if (DEBUG_SD_INSTALL) Log.i(TAG, 1322 "Checking for more work or unbind..."); 1323 // Delete pending install 1324 if (mPendingInstalls.size() > 0) { 1325 mPendingInstalls.remove(0); 1326 } 1327 if (mPendingInstalls.size() == 0) { 1328 if (mBound) { 1329 if (DEBUG_SD_INSTALL) Log.i(TAG, 1330 "Posting delayed MCS_UNBIND"); 1331 removeMessages(MCS_UNBIND); 1332 Message ubmsg = obtainMessage(MCS_UNBIND); 1333 // Unbind after a little delay, to avoid 1334 // continual thrashing. 1335 sendMessageDelayed(ubmsg, 10000); 1336 } 1337 } else { 1338 // There are more pending requests in queue. 1339 // Just post MCS_BOUND message to trigger processing 1340 // of next pending install. 1341 if (DEBUG_SD_INSTALL) Log.i(TAG, 1342 "Posting MCS_BOUND for next work"); 1343 mHandler.sendEmptyMessage(MCS_BOUND); 1344 } 1345 } 1346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1347 } 1348 } else { 1349 // Should never happen ideally. 1350 Slog.w(TAG, "Empty queue"); 1351 } 1352 break; 1353 } 1354 case MCS_RECONNECT: { 1355 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1356 if (mPendingInstalls.size() > 0) { 1357 if (mBound) { 1358 disconnectService(); 1359 } 1360 if (!connectToService()) { 1361 Slog.e(TAG, "Failed to bind to media container service"); 1362 for (HandlerParams params : mPendingInstalls) { 1363 // Indicate service bind error 1364 params.serviceError(); 1365 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1366 System.identityHashCode(params)); 1367 } 1368 mPendingInstalls.clear(); 1369 } 1370 } 1371 break; 1372 } 1373 case MCS_UNBIND: { 1374 // If there is no actual work left, then time to unbind. 1375 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1376 1377 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1378 if (mBound) { 1379 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1380 1381 disconnectService(); 1382 } 1383 } else if (mPendingInstalls.size() > 0) { 1384 // There are more pending requests in queue. 1385 // Just post MCS_BOUND message to trigger processing 1386 // of next pending install. 1387 mHandler.sendEmptyMessage(MCS_BOUND); 1388 } 1389 1390 break; 1391 } 1392 case MCS_GIVE_UP: { 1393 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1394 HandlerParams params = mPendingInstalls.remove(0); 1395 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1396 System.identityHashCode(params)); 1397 break; 1398 } 1399 case SEND_PENDING_BROADCAST: { 1400 String packages[]; 1401 ArrayList<String> components[]; 1402 int size = 0; 1403 int uids[]; 1404 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1405 synchronized (mPackages) { 1406 if (mPendingBroadcasts == null) { 1407 return; 1408 } 1409 size = mPendingBroadcasts.size(); 1410 if (size <= 0) { 1411 // Nothing to be done. Just return 1412 return; 1413 } 1414 packages = new String[size]; 1415 components = new ArrayList[size]; 1416 uids = new int[size]; 1417 int i = 0; // filling out the above arrays 1418 1419 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1420 int packageUserId = mPendingBroadcasts.userIdAt(n); 1421 Iterator<Map.Entry<String, ArrayList<String>>> it 1422 = mPendingBroadcasts.packagesForUserId(packageUserId) 1423 .entrySet().iterator(); 1424 while (it.hasNext() && i < size) { 1425 Map.Entry<String, ArrayList<String>> ent = it.next(); 1426 packages[i] = ent.getKey(); 1427 components[i] = ent.getValue(); 1428 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1429 uids[i] = (ps != null) 1430 ? UserHandle.getUid(packageUserId, ps.appId) 1431 : -1; 1432 i++; 1433 } 1434 } 1435 size = i; 1436 mPendingBroadcasts.clear(); 1437 } 1438 // Send broadcasts 1439 for (int i = 0; i < size; i++) { 1440 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1441 } 1442 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1443 break; 1444 } 1445 case START_CLEANING_PACKAGE: { 1446 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1447 final String packageName = (String)msg.obj; 1448 final int userId = msg.arg1; 1449 final boolean andCode = msg.arg2 != 0; 1450 synchronized (mPackages) { 1451 if (userId == UserHandle.USER_ALL) { 1452 int[] users = sUserManager.getUserIds(); 1453 for (int user : users) { 1454 mSettings.addPackageToCleanLPw( 1455 new PackageCleanItem(user, packageName, andCode)); 1456 } 1457 } else { 1458 mSettings.addPackageToCleanLPw( 1459 new PackageCleanItem(userId, packageName, andCode)); 1460 } 1461 } 1462 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1463 startCleaningPackages(); 1464 } break; 1465 case POST_INSTALL: { 1466 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1467 1468 PostInstallData data = mRunningInstalls.get(msg.arg1); 1469 final boolean didRestore = (msg.arg2 != 0); 1470 mRunningInstalls.delete(msg.arg1); 1471 1472 if (data != null) { 1473 InstallArgs args = data.args; 1474 PackageInstalledInfo parentRes = data.res; 1475 1476 final boolean grantPermissions = (args.installFlags 1477 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1478 final boolean killApp = (args.installFlags 1479 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1480 final String[] grantedPermissions = args.installGrantPermissions; 1481 1482 // Handle the parent package 1483 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1484 grantedPermissions, didRestore, args.installerPackageName, 1485 args.observer); 1486 1487 // Handle the child packages 1488 final int childCount = (parentRes.addedChildPackages != null) 1489 ? parentRes.addedChildPackages.size() : 0; 1490 for (int i = 0; i < childCount; i++) { 1491 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1492 handlePackagePostInstall(childRes, grantPermissions, killApp, 1493 grantedPermissions, false, args.installerPackageName, 1494 args.observer); 1495 } 1496 1497 // Log tracing if needed 1498 if (args.traceMethod != null) { 1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1500 args.traceCookie); 1501 } 1502 } else { 1503 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1504 } 1505 1506 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1507 } break; 1508 case UPDATED_MEDIA_STATUS: { 1509 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1510 boolean reportStatus = msg.arg1 == 1; 1511 boolean doGc = msg.arg2 == 1; 1512 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1513 if (doGc) { 1514 // Force a gc to clear up stale containers. 1515 Runtime.getRuntime().gc(); 1516 } 1517 if (msg.obj != null) { 1518 @SuppressWarnings("unchecked") 1519 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1520 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1521 // Unload containers 1522 unloadAllContainers(args); 1523 } 1524 if (reportStatus) { 1525 try { 1526 if (DEBUG_SD_INSTALL) Log.i(TAG, 1527 "Invoking StorageManagerService call back"); 1528 PackageHelper.getStorageManager().finishMediaUpdate(); 1529 } catch (RemoteException e) { 1530 Log.e(TAG, "StorageManagerService not running?"); 1531 } 1532 } 1533 } break; 1534 case WRITE_SETTINGS: { 1535 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1536 synchronized (mPackages) { 1537 removeMessages(WRITE_SETTINGS); 1538 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1539 mSettings.writeLPr(); 1540 mDirtyUsers.clear(); 1541 } 1542 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1543 } break; 1544 case WRITE_PACKAGE_RESTRICTIONS: { 1545 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1546 synchronized (mPackages) { 1547 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1548 for (int userId : mDirtyUsers) { 1549 mSettings.writePackageRestrictionsLPr(userId); 1550 } 1551 mDirtyUsers.clear(); 1552 } 1553 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1554 } break; 1555 case WRITE_PACKAGE_LIST: { 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1557 synchronized (mPackages) { 1558 removeMessages(WRITE_PACKAGE_LIST); 1559 mSettings.writePackageListLPr(msg.arg1); 1560 } 1561 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1562 } break; 1563 case CHECK_PENDING_VERIFICATION: { 1564 final int verificationId = msg.arg1; 1565 final PackageVerificationState state = mPendingVerification.get(verificationId); 1566 1567 if ((state != null) && !state.timeoutExtended()) { 1568 final InstallArgs args = state.getInstallArgs(); 1569 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1570 1571 Slog.i(TAG, "Verification timed out for " + originUri); 1572 mPendingVerification.remove(verificationId); 1573 1574 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1575 1576 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1577 Slog.i(TAG, "Continuing with installation of " + originUri); 1578 state.setVerifierResponse(Binder.getCallingUid(), 1579 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1580 broadcastPackageVerified(verificationId, originUri, 1581 PackageManager.VERIFICATION_ALLOW, 1582 state.getInstallArgs().getUser()); 1583 try { 1584 ret = args.copyApk(mContainerService, true); 1585 } catch (RemoteException e) { 1586 Slog.e(TAG, "Could not contact the ContainerService"); 1587 } 1588 } else { 1589 broadcastPackageVerified(verificationId, originUri, 1590 PackageManager.VERIFICATION_REJECT, 1591 state.getInstallArgs().getUser()); 1592 } 1593 1594 Trace.asyncTraceEnd( 1595 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1596 1597 processPendingInstall(args, ret); 1598 mHandler.sendEmptyMessage(MCS_UNBIND); 1599 } 1600 break; 1601 } 1602 case PACKAGE_VERIFIED: { 1603 final int verificationId = msg.arg1; 1604 1605 final PackageVerificationState state = mPendingVerification.get(verificationId); 1606 if (state == null) { 1607 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1608 break; 1609 } 1610 1611 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1612 1613 state.setVerifierResponse(response.callerUid, response.code); 1614 1615 if (state.isVerificationComplete()) { 1616 mPendingVerification.remove(verificationId); 1617 1618 final InstallArgs args = state.getInstallArgs(); 1619 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1620 1621 int ret; 1622 if (state.isInstallAllowed()) { 1623 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1624 broadcastPackageVerified(verificationId, originUri, 1625 response.code, state.getInstallArgs().getUser()); 1626 try { 1627 ret = args.copyApk(mContainerService, true); 1628 } catch (RemoteException e) { 1629 Slog.e(TAG, "Could not contact the ContainerService"); 1630 } 1631 } else { 1632 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1633 } 1634 1635 Trace.asyncTraceEnd( 1636 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1637 1638 processPendingInstall(args, ret); 1639 mHandler.sendEmptyMessage(MCS_UNBIND); 1640 } 1641 1642 break; 1643 } 1644 case START_INTENT_FILTER_VERIFICATIONS: { 1645 IFVerificationParams params = (IFVerificationParams) msg.obj; 1646 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1647 params.replacing, params.pkg); 1648 break; 1649 } 1650 case INTENT_FILTER_VERIFIED: { 1651 final int verificationId = msg.arg1; 1652 1653 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1654 verificationId); 1655 if (state == null) { 1656 Slog.w(TAG, "Invalid IntentFilter verification token " 1657 + verificationId + " received"); 1658 break; 1659 } 1660 1661 final int userId = state.getUserId(); 1662 1663 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1664 "Processing IntentFilter verification with token:" 1665 + verificationId + " and userId:" + userId); 1666 1667 final IntentFilterVerificationResponse response = 1668 (IntentFilterVerificationResponse) msg.obj; 1669 1670 state.setVerifierResponse(response.callerUid, response.code); 1671 1672 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1673 "IntentFilter verification with token:" + verificationId 1674 + " and userId:" + userId 1675 + " is settings verifier response with response code:" 1676 + response.code); 1677 1678 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1679 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1680 + response.getFailedDomainsString()); 1681 } 1682 1683 if (state.isVerificationComplete()) { 1684 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1685 } else { 1686 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1687 "IntentFilter verification with token:" + verificationId 1688 + " was not said to be complete"); 1689 } 1690 1691 break; 1692 } 1693 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1694 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1695 mEphemeralResolverConnection, 1696 (EphemeralRequest) msg.obj, 1697 mEphemeralInstallerActivity, 1698 mHandler); 1699 } 1700 } 1701 } 1702 } 1703 1704 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1705 boolean killApp, String[] grantedPermissions, 1706 boolean launchedForRestore, String installerPackage, 1707 IPackageInstallObserver2 installObserver) { 1708 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1709 // Send the removed broadcasts 1710 if (res.removedInfo != null) { 1711 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1712 } 1713 1714 // Now that we successfully installed the package, grant runtime 1715 // permissions if requested before broadcasting the install. 1716 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1717 >= Build.VERSION_CODES.M) { 1718 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1719 } 1720 1721 final boolean update = res.removedInfo != null 1722 && res.removedInfo.removedPackage != null; 1723 1724 // If this is the first time we have child packages for a disabled privileged 1725 // app that had no children, we grant requested runtime permissions to the new 1726 // children if the parent on the system image had them already granted. 1727 if (res.pkg.parentPackage != null) { 1728 synchronized (mPackages) { 1729 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1730 } 1731 } 1732 1733 synchronized (mPackages) { 1734 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1735 } 1736 1737 final String packageName = res.pkg.applicationInfo.packageName; 1738 1739 // Determine the set of users who are adding this package for 1740 // the first time vs. those who are seeing an update. 1741 int[] firstUsers = EMPTY_INT_ARRAY; 1742 int[] updateUsers = EMPTY_INT_ARRAY; 1743 if (res.origUsers == null || res.origUsers.length == 0) { 1744 firstUsers = res.newUsers; 1745 } else { 1746 for (int newUser : res.newUsers) { 1747 boolean isNew = true; 1748 for (int origUser : res.origUsers) { 1749 if (origUser == newUser) { 1750 isNew = false; 1751 break; 1752 } 1753 } 1754 if (isNew) { 1755 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1756 } else { 1757 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1758 } 1759 } 1760 } 1761 1762 // Send installed broadcasts if the install/update is not ephemeral 1763 if (!isEphemeral(res.pkg)) { 1764 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1765 1766 // Send added for users that see the package for the first time 1767 // sendPackageAddedForNewUsers also deals with system apps 1768 int appId = UserHandle.getAppId(res.uid); 1769 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1770 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1771 1772 // Send added for users that don't see the package for the first time 1773 Bundle extras = new Bundle(1); 1774 extras.putInt(Intent.EXTRA_UID, res.uid); 1775 if (update) { 1776 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1777 } 1778 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1779 extras, 0 /*flags*/, null /*targetPackage*/, 1780 null /*finishedReceiver*/, updateUsers); 1781 1782 // Send replaced for users that don't see the package for the first time 1783 if (update) { 1784 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1785 packageName, extras, 0 /*flags*/, 1786 null /*targetPackage*/, null /*finishedReceiver*/, 1787 updateUsers); 1788 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1789 null /*package*/, null /*extras*/, 0 /*flags*/, 1790 packageName /*targetPackage*/, 1791 null /*finishedReceiver*/, updateUsers); 1792 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1793 // First-install and we did a restore, so we're responsible for the 1794 // first-launch broadcast. 1795 if (DEBUG_BACKUP) { 1796 Slog.i(TAG, "Post-restore of " + packageName 1797 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1798 } 1799 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1800 } 1801 1802 // Send broadcast package appeared if forward locked/external for all users 1803 // treat asec-hosted packages like removable media on upgrade 1804 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1805 if (DEBUG_INSTALL) { 1806 Slog.i(TAG, "upgrading pkg " + res.pkg 1807 + " is ASEC-hosted -> AVAILABLE"); 1808 } 1809 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1810 ArrayList<String> pkgList = new ArrayList<>(1); 1811 pkgList.add(packageName); 1812 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1813 } 1814 } 1815 1816 // Work that needs to happen on first install within each user 1817 if (firstUsers != null && firstUsers.length > 0) { 1818 synchronized (mPackages) { 1819 for (int userId : firstUsers) { 1820 // If this app is a browser and it's newly-installed for some 1821 // users, clear any default-browser state in those users. The 1822 // app's nature doesn't depend on the user, so we can just check 1823 // its browser nature in any user and generalize. 1824 if (packageIsBrowser(packageName, userId)) { 1825 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1826 } 1827 1828 // We may also need to apply pending (restored) runtime 1829 // permission grants within these users. 1830 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1831 } 1832 } 1833 } 1834 1835 // Log current value of "unknown sources" setting 1836 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1837 getUnknownSourcesSettings()); 1838 1839 // Force a gc to clear up things 1840 Runtime.getRuntime().gc(); 1841 1842 // Remove the replaced package's older resources safely now 1843 // We delete after a gc for applications on sdcard. 1844 if (res.removedInfo != null && res.removedInfo.args != null) { 1845 synchronized (mInstallLock) { 1846 res.removedInfo.args.doPostDeleteLI(true); 1847 } 1848 } 1849 } 1850 1851 // If someone is watching installs - notify them 1852 if (installObserver != null) { 1853 try { 1854 Bundle extras = extrasForInstallResult(res); 1855 installObserver.onPackageInstalled(res.name, res.returnCode, 1856 res.returnMsg, extras); 1857 } catch (RemoteException e) { 1858 Slog.i(TAG, "Observer no longer exists."); 1859 } 1860 } 1861 } 1862 1863 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1864 PackageParser.Package pkg) { 1865 if (pkg.parentPackage == null) { 1866 return; 1867 } 1868 if (pkg.requestedPermissions == null) { 1869 return; 1870 } 1871 final PackageSetting disabledSysParentPs = mSettings 1872 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1873 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1874 || !disabledSysParentPs.isPrivileged() 1875 || (disabledSysParentPs.childPackageNames != null 1876 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1877 return; 1878 } 1879 final int[] allUserIds = sUserManager.getUserIds(); 1880 final int permCount = pkg.requestedPermissions.size(); 1881 for (int i = 0; i < permCount; i++) { 1882 String permission = pkg.requestedPermissions.get(i); 1883 BasePermission bp = mSettings.mPermissions.get(permission); 1884 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1885 continue; 1886 } 1887 for (int userId : allUserIds) { 1888 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1889 permission, userId)) { 1890 grantRuntimePermission(pkg.packageName, permission, userId); 1891 } 1892 } 1893 } 1894 } 1895 1896 private StorageEventListener mStorageListener = new StorageEventListener() { 1897 @Override 1898 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1899 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1900 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1901 final String volumeUuid = vol.getFsUuid(); 1902 1903 // Clean up any users or apps that were removed or recreated 1904 // while this volume was missing 1905 reconcileUsers(volumeUuid); 1906 reconcileApps(volumeUuid); 1907 1908 // Clean up any install sessions that expired or were 1909 // cancelled while this volume was missing 1910 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1911 1912 loadPrivatePackages(vol); 1913 1914 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1915 unloadPrivatePackages(vol); 1916 } 1917 } 1918 1919 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1920 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1921 updateExternalMediaStatus(true, false); 1922 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1923 updateExternalMediaStatus(false, false); 1924 } 1925 } 1926 } 1927 1928 @Override 1929 public void onVolumeForgotten(String fsUuid) { 1930 if (TextUtils.isEmpty(fsUuid)) { 1931 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1932 return; 1933 } 1934 1935 // Remove any apps installed on the forgotten volume 1936 synchronized (mPackages) { 1937 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1938 for (PackageSetting ps : packages) { 1939 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1940 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1941 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1942 1943 // Try very hard to release any references to this package 1944 // so we don't risk the system server being killed due to 1945 // open FDs 1946 AttributeCache.instance().removePackage(ps.name); 1947 } 1948 1949 mSettings.onVolumeForgotten(fsUuid); 1950 mSettings.writeLPr(); 1951 } 1952 } 1953 }; 1954 1955 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1956 String[] grantedPermissions) { 1957 for (int userId : userIds) { 1958 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1959 } 1960 1961 // We could have touched GID membership, so flush out packages.list 1962 synchronized (mPackages) { 1963 mSettings.writePackageListLPr(); 1964 } 1965 } 1966 1967 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1968 String[] grantedPermissions) { 1969 SettingBase sb = (SettingBase) pkg.mExtras; 1970 if (sb == null) { 1971 return; 1972 } 1973 1974 PermissionsState permissionsState = sb.getPermissionsState(); 1975 1976 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1977 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1978 1979 for (String permission : pkg.requestedPermissions) { 1980 final BasePermission bp; 1981 synchronized (mPackages) { 1982 bp = mSettings.mPermissions.get(permission); 1983 } 1984 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1985 && (grantedPermissions == null 1986 || ArrayUtils.contains(grantedPermissions, permission))) { 1987 final int flags = permissionsState.getPermissionFlags(permission, userId); 1988 // Installer cannot change immutable permissions. 1989 if ((flags & immutableFlags) == 0) { 1990 grantRuntimePermission(pkg.packageName, permission, userId); 1991 } 1992 } 1993 } 1994 } 1995 1996 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1997 Bundle extras = null; 1998 switch (res.returnCode) { 1999 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2000 extras = new Bundle(); 2001 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2002 res.origPermission); 2003 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2004 res.origPackage); 2005 break; 2006 } 2007 case PackageManager.INSTALL_SUCCEEDED: { 2008 extras = new Bundle(); 2009 extras.putBoolean(Intent.EXTRA_REPLACING, 2010 res.removedInfo != null && res.removedInfo.removedPackage != null); 2011 break; 2012 } 2013 } 2014 return extras; 2015 } 2016 2017 void scheduleWriteSettingsLocked() { 2018 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2019 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2020 } 2021 } 2022 2023 void scheduleWritePackageListLocked(int userId) { 2024 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2025 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2026 msg.arg1 = userId; 2027 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2028 } 2029 } 2030 2031 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2032 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2033 scheduleWritePackageRestrictionsLocked(userId); 2034 } 2035 2036 void scheduleWritePackageRestrictionsLocked(int userId) { 2037 final int[] userIds = (userId == UserHandle.USER_ALL) 2038 ? sUserManager.getUserIds() : new int[]{userId}; 2039 for (int nextUserId : userIds) { 2040 if (!sUserManager.exists(nextUserId)) return; 2041 mDirtyUsers.add(nextUserId); 2042 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2043 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2044 } 2045 } 2046 } 2047 2048 public static PackageManagerService main(Context context, Installer installer, 2049 boolean factoryTest, boolean onlyCore) { 2050 // Self-check for initial settings. 2051 PackageManagerServiceCompilerMapping.checkProperties(); 2052 2053 PackageManagerService m = new PackageManagerService(context, installer, 2054 factoryTest, onlyCore); 2055 m.enableSystemUserPackages(); 2056 ServiceManager.addService("package", m); 2057 return m; 2058 } 2059 2060 private void enableSystemUserPackages() { 2061 if (!UserManager.isSplitSystemUser()) { 2062 return; 2063 } 2064 // For system user, enable apps based on the following conditions: 2065 // - app is whitelisted or belong to one of these groups: 2066 // -- system app which has no launcher icons 2067 // -- system app which has INTERACT_ACROSS_USERS permission 2068 // -- system IME app 2069 // - app is not in the blacklist 2070 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2071 Set<String> enableApps = new ArraySet<>(); 2072 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2073 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2074 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2075 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2076 enableApps.addAll(wlApps); 2077 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2078 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2079 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2080 enableApps.removeAll(blApps); 2081 Log.i(TAG, "Applications installed for system user: " + enableApps); 2082 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2083 UserHandle.SYSTEM); 2084 final int allAppsSize = allAps.size(); 2085 synchronized (mPackages) { 2086 for (int i = 0; i < allAppsSize; i++) { 2087 String pName = allAps.get(i); 2088 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2089 // Should not happen, but we shouldn't be failing if it does 2090 if (pkgSetting == null) { 2091 continue; 2092 } 2093 boolean install = enableApps.contains(pName); 2094 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2095 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2096 + " for system user"); 2097 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2098 } 2099 } 2100 } 2101 } 2102 2103 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2104 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2105 Context.DISPLAY_SERVICE); 2106 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2107 } 2108 2109 /** 2110 * Requests that files preopted on a secondary system partition be copied to the data partition 2111 * if possible. Note that the actual copying of the files is accomplished by init for security 2112 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2113 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2114 */ 2115 private static void requestCopyPreoptedFiles() { 2116 final int WAIT_TIME_MS = 100; 2117 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2118 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2119 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2120 // We will wait for up to 100 seconds. 2121 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2122 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2123 try { 2124 Thread.sleep(WAIT_TIME_MS); 2125 } catch (InterruptedException e) { 2126 // Do nothing 2127 } 2128 if (SystemClock.uptimeMillis() > timeEnd) { 2129 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2130 Slog.wtf(TAG, "cppreopt did not finish!"); 2131 break; 2132 } 2133 } 2134 } 2135 } 2136 2137 public PackageManagerService(Context context, Installer installer, 2138 boolean factoryTest, boolean onlyCore) { 2139 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2140 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2141 SystemClock.uptimeMillis()); 2142 2143 if (mSdkVersion <= 0) { 2144 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2145 } 2146 2147 mContext = context; 2148 2149 mPermissionReviewRequired = context.getResources().getBoolean( 2150 R.bool.config_permissionReviewRequired); 2151 2152 mFactoryTest = factoryTest; 2153 mOnlyCore = onlyCore; 2154 mMetrics = new DisplayMetrics(); 2155 mSettings = new Settings(mPackages); 2156 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2157 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2158 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2159 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2160 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2161 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2162 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2163 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2164 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2165 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2166 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2167 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2168 2169 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2170 if (separateProcesses != null && separateProcesses.length() > 0) { 2171 if ("*".equals(separateProcesses)) { 2172 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2173 mSeparateProcesses = null; 2174 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2175 } else { 2176 mDefParseFlags = 0; 2177 mSeparateProcesses = separateProcesses.split(","); 2178 Slog.w(TAG, "Running with debug.separate_processes: " 2179 + separateProcesses); 2180 } 2181 } else { 2182 mDefParseFlags = 0; 2183 mSeparateProcesses = null; 2184 } 2185 2186 mInstaller = installer; 2187 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2188 "*dexopt*"); 2189 mDexManager = new DexManager(); 2190 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2191 2192 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2193 FgThread.get().getLooper()); 2194 2195 getDefaultDisplayMetrics(context, mMetrics); 2196 2197 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2198 SystemConfig systemConfig = SystemConfig.getInstance(); 2199 mGlobalGids = systemConfig.getGlobalGids(); 2200 mSystemPermissions = systemConfig.getSystemPermissions(); 2201 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2202 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2203 2204 mProtectedPackages = new ProtectedPackages(mContext); 2205 2206 synchronized (mInstallLock) { 2207 // writer 2208 synchronized (mPackages) { 2209 mHandlerThread = new ServiceThread(TAG, 2210 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2211 mHandlerThread.start(); 2212 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2213 mProcessLoggingHandler = new ProcessLoggingHandler(); 2214 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2215 2216 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2217 2218 File dataDir = Environment.getDataDirectory(); 2219 mAppInstallDir = new File(dataDir, "app"); 2220 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2221 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2222 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2223 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2224 2225 sUserManager = new UserManagerService(context, this, mPackages); 2226 2227 // Propagate permission configuration in to package manager. 2228 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2229 = systemConfig.getPermissions(); 2230 for (int i=0; i<permConfig.size(); i++) { 2231 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2232 BasePermission bp = mSettings.mPermissions.get(perm.name); 2233 if (bp == null) { 2234 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2235 mSettings.mPermissions.put(perm.name, bp); 2236 } 2237 if (perm.gids != null) { 2238 bp.setGids(perm.gids, perm.perUser); 2239 } 2240 } 2241 2242 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2243 for (int i=0; i<libConfig.size(); i++) { 2244 mSharedLibraries.put(libConfig.keyAt(i), 2245 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2246 } 2247 2248 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2249 2250 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2251 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2252 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2253 2254 // Clean up orphaned packages for which the code path doesn't exist 2255 // and they are an update to a system app - caused by bug/32321269 2256 final int packageSettingCount = mSettings.mPackages.size(); 2257 for (int i = packageSettingCount - 1; i >= 0; i--) { 2258 PackageSetting ps = mSettings.mPackages.valueAt(i); 2259 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2260 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2261 mSettings.mPackages.removeAt(i); 2262 mSettings.enableSystemPackageLPw(ps.name); 2263 } 2264 } 2265 2266 if (mFirstBoot) { 2267 requestCopyPreoptedFiles(); 2268 } 2269 2270 String customResolverActivity = Resources.getSystem().getString( 2271 R.string.config_customResolverActivity); 2272 if (TextUtils.isEmpty(customResolverActivity)) { 2273 customResolverActivity = null; 2274 } else { 2275 mCustomResolverComponentName = ComponentName.unflattenFromString( 2276 customResolverActivity); 2277 } 2278 2279 long startTime = SystemClock.uptimeMillis(); 2280 2281 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2282 startTime); 2283 2284 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2285 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2286 2287 if (bootClassPath == null) { 2288 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2289 } 2290 2291 if (systemServerClassPath == null) { 2292 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2293 } 2294 2295 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2296 final String[] dexCodeInstructionSets = 2297 getDexCodeInstructionSets( 2298 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2299 2300 /** 2301 * Ensure all external libraries have had dexopt run on them. 2302 */ 2303 if (mSharedLibraries.size() > 0) { 2304 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2305 // NOTE: For now, we're compiling these system "shared libraries" 2306 // (and framework jars) into all available architectures. It's possible 2307 // to compile them only when we come across an app that uses them (there's 2308 // already logic for that in scanPackageLI) but that adds some complexity. 2309 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2310 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2311 final String lib = libEntry.path; 2312 if (lib == null) { 2313 continue; 2314 } 2315 2316 try { 2317 // Shared libraries do not have profiles so we perform a full 2318 // AOT compilation (if needed). 2319 int dexoptNeeded = DexFile.getDexOptNeeded( 2320 lib, dexCodeInstructionSet, 2321 getCompilerFilterForReason(REASON_SHARED_APK), 2322 false /* newProfile */); 2323 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2324 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2325 dexCodeInstructionSet, dexoptNeeded, null, 2326 DEXOPT_PUBLIC, 2327 getCompilerFilterForReason(REASON_SHARED_APK), 2328 StorageManager.UUID_PRIVATE_INTERNAL, 2329 SKIP_SHARED_LIBRARY_CHECK); 2330 } 2331 } catch (FileNotFoundException e) { 2332 Slog.w(TAG, "Library not found: " + lib); 2333 } catch (IOException | InstallerException e) { 2334 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2335 + e.getMessage()); 2336 } 2337 } 2338 } 2339 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2340 } 2341 2342 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2343 2344 final VersionInfo ver = mSettings.getInternalVersion(); 2345 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2346 2347 // when upgrading from pre-M, promote system app permissions from install to runtime 2348 mPromoteSystemApps = 2349 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2350 2351 // When upgrading from pre-N, we need to handle package extraction like first boot, 2352 // as there is no profiling data available. 2353 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2354 2355 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2356 2357 // save off the names of pre-existing system packages prior to scanning; we don't 2358 // want to automatically grant runtime permissions for new system apps 2359 if (mPromoteSystemApps) { 2360 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2361 while (pkgSettingIter.hasNext()) { 2362 PackageSetting ps = pkgSettingIter.next(); 2363 if (isSystemApp(ps)) { 2364 mExistingSystemPackages.add(ps.name); 2365 } 2366 } 2367 } 2368 2369 mCacheDir = preparePackageParserCache(mIsUpgrade); 2370 2371 // Set flag to monitor and not change apk file paths when 2372 // scanning install directories. 2373 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2374 2375 if (mIsUpgrade || mFirstBoot) { 2376 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2377 } 2378 2379 // Collect vendor overlay packages. (Do this before scanning any apps.) 2380 // For security and version matching reason, only consider 2381 // overlay packages if they reside in the right directory. 2382 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2383 if (overlayThemeDir.isEmpty()) { 2384 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2385 } 2386 if (!overlayThemeDir.isEmpty()) { 2387 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2388 | PackageParser.PARSE_IS_SYSTEM 2389 | PackageParser.PARSE_IS_SYSTEM_DIR 2390 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2391 } 2392 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2393 | PackageParser.PARSE_IS_SYSTEM 2394 | PackageParser.PARSE_IS_SYSTEM_DIR 2395 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2396 2397 // Find base frameworks (resource packages without code). 2398 scanDirTracedLI(frameworkDir, mDefParseFlags 2399 | PackageParser.PARSE_IS_SYSTEM 2400 | PackageParser.PARSE_IS_SYSTEM_DIR 2401 | PackageParser.PARSE_IS_PRIVILEGED, 2402 scanFlags | SCAN_NO_DEX, 0); 2403 2404 // Collected privileged system packages. 2405 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2406 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2407 | PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR 2409 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2410 2411 // Collect ordinary system packages. 2412 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2413 scanDirTracedLI(systemAppDir, mDefParseFlags 2414 | PackageParser.PARSE_IS_SYSTEM 2415 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2416 2417 // Collect all vendor packages. 2418 File vendorAppDir = new File("/vendor/app"); 2419 try { 2420 vendorAppDir = vendorAppDir.getCanonicalFile(); 2421 } catch (IOException e) { 2422 // failed to look up canonical path, continue with original one 2423 } 2424 scanDirTracedLI(vendorAppDir, mDefParseFlags 2425 | PackageParser.PARSE_IS_SYSTEM 2426 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2427 2428 // Collect all OEM packages. 2429 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2430 scanDirTracedLI(oemAppDir, mDefParseFlags 2431 | PackageParser.PARSE_IS_SYSTEM 2432 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2433 2434 // Prune any system packages that no longer exist. 2435 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2436 if (!mOnlyCore) { 2437 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2438 while (psit.hasNext()) { 2439 PackageSetting ps = psit.next(); 2440 2441 /* 2442 * If this is not a system app, it can't be a 2443 * disable system app. 2444 */ 2445 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2446 continue; 2447 } 2448 2449 /* 2450 * If the package is scanned, it's not erased. 2451 */ 2452 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2453 if (scannedPkg != null) { 2454 /* 2455 * If the system app is both scanned and in the 2456 * disabled packages list, then it must have been 2457 * added via OTA. Remove it from the currently 2458 * scanned package so the previously user-installed 2459 * application can be scanned. 2460 */ 2461 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2462 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2463 + ps.name + "; removing system app. Last known codePath=" 2464 + ps.codePathString + ", installStatus=" + ps.installStatus 2465 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2466 + scannedPkg.mVersionCode); 2467 removePackageLI(scannedPkg, true); 2468 mExpectingBetter.put(ps.name, ps.codePath); 2469 } 2470 2471 continue; 2472 } 2473 2474 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2475 psit.remove(); 2476 logCriticalInfo(Log.WARN, "System package " + ps.name 2477 + " no longer exists; it's data will be wiped"); 2478 // Actual deletion of code and data will be handled by later 2479 // reconciliation step 2480 } else { 2481 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2482 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2483 possiblyDeletedUpdatedSystemApps.add(ps.name); 2484 } 2485 } 2486 } 2487 } 2488 2489 //look for any incomplete package installations 2490 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2491 for (int i = 0; i < deletePkgsList.size(); i++) { 2492 // Actual deletion of code and data will be handled by later 2493 // reconciliation step 2494 final String packageName = deletePkgsList.get(i).name; 2495 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2496 synchronized (mPackages) { 2497 mSettings.removePackageLPw(packageName); 2498 } 2499 } 2500 2501 //delete tmp files 2502 deleteTempPackageFiles(); 2503 2504 // Remove any shared userIDs that have no associated packages 2505 mSettings.pruneSharedUsersLPw(); 2506 2507 if (!mOnlyCore) { 2508 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2509 SystemClock.uptimeMillis()); 2510 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2511 2512 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2513 | PackageParser.PARSE_FORWARD_LOCK, 2514 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2515 2516 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2517 | PackageParser.PARSE_IS_EPHEMERAL, 2518 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2519 2520 /** 2521 * Remove disable package settings for any updated system 2522 * apps that were removed via an OTA. If they're not a 2523 * previously-updated app, remove them completely. 2524 * Otherwise, just revoke their system-level permissions. 2525 */ 2526 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2527 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2528 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2529 2530 String msg; 2531 if (deletedPkg == null) { 2532 msg = "Updated system package " + deletedAppName 2533 + " no longer exists; it's data will be wiped"; 2534 // Actual deletion of code and data will be handled by later 2535 // reconciliation step 2536 } else { 2537 msg = "Updated system app + " + deletedAppName 2538 + " no longer present; removing system privileges for " 2539 + deletedAppName; 2540 2541 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2542 2543 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2544 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2545 } 2546 logCriticalInfo(Log.WARN, msg); 2547 } 2548 2549 /** 2550 * Make sure all system apps that we expected to appear on 2551 * the userdata partition actually showed up. If they never 2552 * appeared, crawl back and revive the system version. 2553 */ 2554 for (int i = 0; i < mExpectingBetter.size(); i++) { 2555 final String packageName = mExpectingBetter.keyAt(i); 2556 if (!mPackages.containsKey(packageName)) { 2557 final File scanFile = mExpectingBetter.valueAt(i); 2558 2559 logCriticalInfo(Log.WARN, "Expected better " + packageName 2560 + " but never showed up; reverting to system"); 2561 2562 int reparseFlags = mDefParseFlags; 2563 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2564 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2565 | PackageParser.PARSE_IS_SYSTEM_DIR 2566 | PackageParser.PARSE_IS_PRIVILEGED; 2567 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2568 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2569 | PackageParser.PARSE_IS_SYSTEM_DIR; 2570 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2571 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2572 | PackageParser.PARSE_IS_SYSTEM_DIR; 2573 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2574 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2575 | PackageParser.PARSE_IS_SYSTEM_DIR; 2576 } else { 2577 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2578 continue; 2579 } 2580 2581 mSettings.enableSystemPackageLPw(packageName); 2582 2583 try { 2584 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2585 } catch (PackageManagerException e) { 2586 Slog.e(TAG, "Failed to parse original system package: " 2587 + e.getMessage()); 2588 } 2589 } 2590 } 2591 } 2592 mExpectingBetter.clear(); 2593 2594 // Resolve the storage manager. 2595 mStorageManagerPackage = getStorageManagerPackageName(); 2596 2597 // Resolve protected action filters. Only the setup wizard is allowed to 2598 // have a high priority filter for these actions. 2599 mSetupWizardPackage = getSetupWizardPackageName(); 2600 if (mProtectedFilters.size() > 0) { 2601 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2602 Slog.i(TAG, "No setup wizard;" 2603 + " All protected intents capped to priority 0"); 2604 } 2605 for (ActivityIntentInfo filter : mProtectedFilters) { 2606 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2607 if (DEBUG_FILTERS) { 2608 Slog.i(TAG, "Found setup wizard;" 2609 + " allow priority " + filter.getPriority() + ";" 2610 + " package: " + filter.activity.info.packageName 2611 + " activity: " + filter.activity.className 2612 + " priority: " + filter.getPriority()); 2613 } 2614 // skip setup wizard; allow it to keep the high priority filter 2615 continue; 2616 } 2617 Slog.w(TAG, "Protected action; cap priority to 0;" 2618 + " package: " + filter.activity.info.packageName 2619 + " activity: " + filter.activity.className 2620 + " origPrio: " + filter.getPriority()); 2621 filter.setPriority(0); 2622 } 2623 } 2624 mDeferProtectedFilters = false; 2625 mProtectedFilters.clear(); 2626 2627 // Now that we know all of the shared libraries, update all clients to have 2628 // the correct library paths. 2629 updateAllSharedLibrariesLPw(); 2630 2631 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2632 // NOTE: We ignore potential failures here during a system scan (like 2633 // the rest of the commands above) because there's precious little we 2634 // can do about it. A settings error is reported, though. 2635 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2636 } 2637 2638 // Now that we know all the packages we are keeping, 2639 // read and update their last usage times. 2640 mPackageUsage.read(mPackages); 2641 mCompilerStats.read(); 2642 2643 // Read and update the usage of dex files. 2644 // At this point we know the code paths of the packages, so we can validate 2645 // the disk file and build the internal cache. 2646 // The usage file is expected to be small so loading and verifying it 2647 // should take a fairly small time compare to the other activities (e.g. package 2648 // scanning). 2649 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2650 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2651 for (int userId : currentUserIds) { 2652 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2653 } 2654 mDexManager.load(userPackages); 2655 2656 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2657 SystemClock.uptimeMillis()); 2658 Slog.i(TAG, "Time to scan packages: " 2659 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2660 + " seconds"); 2661 2662 // If the platform SDK has changed since the last time we booted, 2663 // we need to re-grant app permission to catch any new ones that 2664 // appear. This is really a hack, and means that apps can in some 2665 // cases get permissions that the user didn't initially explicitly 2666 // allow... it would be nice to have some better way to handle 2667 // this situation. 2668 int updateFlags = UPDATE_PERMISSIONS_ALL; 2669 if (ver.sdkVersion != mSdkVersion) { 2670 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2671 + mSdkVersion + "; regranting permissions for internal storage"); 2672 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2673 } 2674 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2675 ver.sdkVersion = mSdkVersion; 2676 2677 // If this is the first boot or an update from pre-M, and it is a normal 2678 // boot, then we need to initialize the default preferred apps across 2679 // all defined users. 2680 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2681 for (UserInfo user : sUserManager.getUsers(true)) { 2682 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2683 applyFactoryDefaultBrowserLPw(user.id); 2684 primeDomainVerificationsLPw(user.id); 2685 } 2686 } 2687 2688 // Prepare storage for system user really early during boot, 2689 // since core system apps like SettingsProvider and SystemUI 2690 // can't wait for user to start 2691 final int storageFlags; 2692 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2693 storageFlags = StorageManager.FLAG_STORAGE_DE; 2694 } else { 2695 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2696 } 2697 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2698 storageFlags, true /* migrateAppData */); 2699 2700 // If this is first boot after an OTA, and a normal boot, then 2701 // we need to clear code cache directories. 2702 // Note that we do *not* clear the application profiles. These remain valid 2703 // across OTAs and are used to drive profile verification (post OTA) and 2704 // profile compilation (without waiting to collect a fresh set of profiles). 2705 if (mIsUpgrade && !onlyCore) { 2706 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2707 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2708 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2709 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2710 // No apps are running this early, so no need to freeze 2711 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2712 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2713 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2714 } 2715 } 2716 ver.fingerprint = Build.FINGERPRINT; 2717 } 2718 2719 checkDefaultBrowser(); 2720 2721 // clear only after permissions and other defaults have been updated 2722 mExistingSystemPackages.clear(); 2723 mPromoteSystemApps = false; 2724 2725 // All the changes are done during package scanning. 2726 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2727 2728 // can downgrade to reader 2729 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2730 mSettings.writeLPr(); 2731 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2732 2733 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2734 // early on (before the package manager declares itself as early) because other 2735 // components in the system server might ask for package contexts for these apps. 2736 // 2737 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2738 // (i.e, that the data partition is unavailable). 2739 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2740 long start = System.nanoTime(); 2741 List<PackageParser.Package> coreApps = new ArrayList<>(); 2742 for (PackageParser.Package pkg : mPackages.values()) { 2743 if (pkg.coreApp) { 2744 coreApps.add(pkg); 2745 } 2746 } 2747 2748 int[] stats = performDexOptUpgrade(coreApps, false, 2749 getCompilerFilterForReason(REASON_CORE_APP)); 2750 2751 final int elapsedTimeSeconds = 2752 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2753 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2754 2755 if (DEBUG_DEXOPT) { 2756 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2757 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2758 } 2759 2760 2761 // TODO: Should we log these stats to tron too ? 2762 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2763 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2764 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2765 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2766 } 2767 2768 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2769 SystemClock.uptimeMillis()); 2770 2771 if (!mOnlyCore) { 2772 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2773 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2774 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2775 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2776 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2777 mIntentFilterVerifierComponent); 2778 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2779 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2780 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2781 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2782 } else { 2783 mRequiredVerifierPackage = null; 2784 mRequiredInstallerPackage = null; 2785 mRequiredUninstallerPackage = null; 2786 mIntentFilterVerifierComponent = null; 2787 mIntentFilterVerifier = null; 2788 mServicesSystemSharedLibraryPackageName = null; 2789 mSharedSystemSharedLibraryPackageName = null; 2790 } 2791 2792 mInstallerService = new PackageInstallerService(context, this); 2793 2794 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2795 if (ephemeralResolverComponent != null) { 2796 if (DEBUG_EPHEMERAL) { 2797 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2798 } 2799 mEphemeralResolverConnection = 2800 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2801 } else { 2802 mEphemeralResolverConnection = null; 2803 } 2804 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2805 if (mEphemeralInstallerComponent != null) { 2806 if (DEBUG_EPHEMERAL) { 2807 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2808 } 2809 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2810 } 2811 2812 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2813 } // synchronized (mPackages) 2814 } // synchronized (mInstallLock) 2815 2816 // Now after opening every single application zip, make sure they 2817 // are all flushed. Not really needed, but keeps things nice and 2818 // tidy. 2819 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2820 Runtime.getRuntime().gc(); 2821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2822 2823 // The initial scanning above does many calls into installd while 2824 // holding the mPackages lock, but we're mostly interested in yelling 2825 // once we have a booted system. 2826 mInstaller.setWarnIfHeld(mPackages); 2827 2828 // Expose private service for system components to use. 2829 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2831 } 2832 2833 private static File preparePackageParserCache(boolean isUpgrade) { 2834 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2835 return null; 2836 } 2837 2838 if (SystemProperties.getBoolean("ro.boot.disable_package_cache", false)) { 2839 Slog.i(TAG, "Disabling package parser cache due to system property."); 2840 return null; 2841 } 2842 2843 // The base directory for the package parser cache lives under /data/system/. 2844 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2845 "package_cache"); 2846 if (cacheBaseDir == null) { 2847 return null; 2848 } 2849 2850 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2851 // This also serves to "GC" unused entries when the package cache version changes (which 2852 // can only happen during upgrades). 2853 if (isUpgrade) { 2854 FileUtils.deleteContents(cacheBaseDir); 2855 } 2856 2857 // Return the versioned package cache directory. This is something like 2858 // "/data/system/package_cache/1" 2859 return FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2860 } 2861 2862 @Override 2863 public boolean isFirstBoot() { 2864 return mFirstBoot; 2865 } 2866 2867 @Override 2868 public boolean isOnlyCoreApps() { 2869 return mOnlyCore; 2870 } 2871 2872 @Override 2873 public boolean isUpgrade() { 2874 return mIsUpgrade; 2875 } 2876 2877 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2878 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2879 2880 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2881 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2882 UserHandle.USER_SYSTEM); 2883 if (matches.size() == 1) { 2884 return matches.get(0).getComponentInfo().packageName; 2885 } else if (matches.size() == 0) { 2886 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2887 return null; 2888 } 2889 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2890 } 2891 2892 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2893 synchronized (mPackages) { 2894 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2895 if (libraryEntry == null) { 2896 throw new IllegalStateException("Missing required shared library:" + libraryName); 2897 } 2898 return libraryEntry.apk; 2899 } 2900 } 2901 2902 private @NonNull String getRequiredInstallerLPr() { 2903 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2904 intent.addCategory(Intent.CATEGORY_DEFAULT); 2905 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2906 2907 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2908 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2909 UserHandle.USER_SYSTEM); 2910 if (matches.size() == 1) { 2911 ResolveInfo resolveInfo = matches.get(0); 2912 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2913 throw new RuntimeException("The installer must be a privileged app"); 2914 } 2915 return matches.get(0).getComponentInfo().packageName; 2916 } else { 2917 throw new RuntimeException("There must be exactly one installer; found " + matches); 2918 } 2919 } 2920 2921 private @NonNull String getRequiredUninstallerLPr() { 2922 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2923 intent.addCategory(Intent.CATEGORY_DEFAULT); 2924 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2925 2926 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2927 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2928 UserHandle.USER_SYSTEM); 2929 if (resolveInfo == null || 2930 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2931 throw new RuntimeException("There must be exactly one uninstaller; found " 2932 + resolveInfo); 2933 } 2934 return resolveInfo.getComponentInfo().packageName; 2935 } 2936 2937 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2938 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2939 2940 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2941 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2942 UserHandle.USER_SYSTEM); 2943 ResolveInfo best = null; 2944 final int N = matches.size(); 2945 for (int i = 0; i < N; i++) { 2946 final ResolveInfo cur = matches.get(i); 2947 final String packageName = cur.getComponentInfo().packageName; 2948 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2949 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2950 continue; 2951 } 2952 2953 if (best == null || cur.priority > best.priority) { 2954 best = cur; 2955 } 2956 } 2957 2958 if (best != null) { 2959 return best.getComponentInfo().getComponentName(); 2960 } else { 2961 throw new RuntimeException("There must be at least one intent filter verifier"); 2962 } 2963 } 2964 2965 private @Nullable ComponentName getEphemeralResolverLPr() { 2966 final String[] packageArray = 2967 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2968 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2969 if (DEBUG_EPHEMERAL) { 2970 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2971 } 2972 return null; 2973 } 2974 2975 final int resolveFlags = 2976 MATCH_DIRECT_BOOT_AWARE 2977 | MATCH_DIRECT_BOOT_UNAWARE 2978 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2979 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2980 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2981 resolveFlags, UserHandle.USER_SYSTEM); 2982 2983 final int N = resolvers.size(); 2984 if (N == 0) { 2985 if (DEBUG_EPHEMERAL) { 2986 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2987 } 2988 return null; 2989 } 2990 2991 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2992 for (int i = 0; i < N; i++) { 2993 final ResolveInfo info = resolvers.get(i); 2994 2995 if (info.serviceInfo == null) { 2996 continue; 2997 } 2998 2999 final String packageName = info.serviceInfo.packageName; 3000 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3001 if (DEBUG_EPHEMERAL) { 3002 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3003 + " pkg: " + packageName + ", info:" + info); 3004 } 3005 continue; 3006 } 3007 3008 if (DEBUG_EPHEMERAL) { 3009 Slog.v(TAG, "Ephemeral resolver found;" 3010 + " pkg: " + packageName + ", info:" + info); 3011 } 3012 return new ComponentName(packageName, info.serviceInfo.name); 3013 } 3014 if (DEBUG_EPHEMERAL) { 3015 Slog.v(TAG, "Ephemeral resolver NOT found"); 3016 } 3017 return null; 3018 } 3019 3020 private @Nullable ComponentName getEphemeralInstallerLPr() { 3021 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3022 intent.addCategory(Intent.CATEGORY_DEFAULT); 3023 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3024 3025 final int resolveFlags = 3026 MATCH_DIRECT_BOOT_AWARE 3027 | MATCH_DIRECT_BOOT_UNAWARE 3028 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3029 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3030 resolveFlags, UserHandle.USER_SYSTEM); 3031 Iterator<ResolveInfo> iter = matches.iterator(); 3032 while (iter.hasNext()) { 3033 final ResolveInfo rInfo = iter.next(); 3034 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3035 if (ps != null) { 3036 final PermissionsState permissionsState = ps.getPermissionsState(); 3037 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3038 continue; 3039 } 3040 } 3041 iter.remove(); 3042 } 3043 if (matches.size() == 0) { 3044 return null; 3045 } else if (matches.size() == 1) { 3046 return matches.get(0).getComponentInfo().getComponentName(); 3047 } else { 3048 throw new RuntimeException( 3049 "There must be at most one ephemeral installer; found " + matches); 3050 } 3051 } 3052 3053 private void primeDomainVerificationsLPw(int userId) { 3054 if (DEBUG_DOMAIN_VERIFICATION) { 3055 Slog.d(TAG, "Priming domain verifications in user " + userId); 3056 } 3057 3058 SystemConfig systemConfig = SystemConfig.getInstance(); 3059 ArraySet<String> packages = systemConfig.getLinkedApps(); 3060 3061 for (String packageName : packages) { 3062 PackageParser.Package pkg = mPackages.get(packageName); 3063 if (pkg != null) { 3064 if (!pkg.isSystemApp()) { 3065 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3066 continue; 3067 } 3068 3069 ArraySet<String> domains = null; 3070 for (PackageParser.Activity a : pkg.activities) { 3071 for (ActivityIntentInfo filter : a.intents) { 3072 if (hasValidDomains(filter)) { 3073 if (domains == null) { 3074 domains = new ArraySet<String>(); 3075 } 3076 domains.addAll(filter.getHostsList()); 3077 } 3078 } 3079 } 3080 3081 if (domains != null && domains.size() > 0) { 3082 if (DEBUG_DOMAIN_VERIFICATION) { 3083 Slog.v(TAG, " + " + packageName); 3084 } 3085 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3086 // state w.r.t. the formal app-linkage "no verification attempted" state; 3087 // and then 'always' in the per-user state actually used for intent resolution. 3088 final IntentFilterVerificationInfo ivi; 3089 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3090 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3091 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3092 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3093 } else { 3094 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3095 + "' does not handle web links"); 3096 } 3097 } else { 3098 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3099 } 3100 } 3101 3102 scheduleWritePackageRestrictionsLocked(userId); 3103 scheduleWriteSettingsLocked(); 3104 } 3105 3106 private void applyFactoryDefaultBrowserLPw(int userId) { 3107 // The default browser app's package name is stored in a string resource, 3108 // with a product-specific overlay used for vendor customization. 3109 String browserPkg = mContext.getResources().getString( 3110 com.android.internal.R.string.default_browser); 3111 if (!TextUtils.isEmpty(browserPkg)) { 3112 // non-empty string => required to be a known package 3113 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3114 if (ps == null) { 3115 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3116 browserPkg = null; 3117 } else { 3118 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3119 } 3120 } 3121 3122 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3123 // default. If there's more than one, just leave everything alone. 3124 if (browserPkg == null) { 3125 calculateDefaultBrowserLPw(userId); 3126 } 3127 } 3128 3129 private void calculateDefaultBrowserLPw(int userId) { 3130 List<String> allBrowsers = resolveAllBrowserApps(userId); 3131 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3132 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3133 } 3134 3135 private List<String> resolveAllBrowserApps(int userId) { 3136 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3137 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3138 PackageManager.MATCH_ALL, userId); 3139 3140 final int count = list.size(); 3141 List<String> result = new ArrayList<String>(count); 3142 for (int i=0; i<count; i++) { 3143 ResolveInfo info = list.get(i); 3144 if (info.activityInfo == null 3145 || !info.handleAllWebDataURI 3146 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3147 || result.contains(info.activityInfo.packageName)) { 3148 continue; 3149 } 3150 result.add(info.activityInfo.packageName); 3151 } 3152 3153 return result; 3154 } 3155 3156 private boolean packageIsBrowser(String packageName, int userId) { 3157 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3158 PackageManager.MATCH_ALL, userId); 3159 final int N = list.size(); 3160 for (int i = 0; i < N; i++) { 3161 ResolveInfo info = list.get(i); 3162 if (packageName.equals(info.activityInfo.packageName)) { 3163 return true; 3164 } 3165 } 3166 return false; 3167 } 3168 3169 private void checkDefaultBrowser() { 3170 final int myUserId = UserHandle.myUserId(); 3171 final String packageName = getDefaultBrowserPackageName(myUserId); 3172 if (packageName != null) { 3173 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3174 if (info == null) { 3175 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3176 synchronized (mPackages) { 3177 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3178 } 3179 } 3180 } 3181 } 3182 3183 @Override 3184 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3185 throws RemoteException { 3186 try { 3187 return super.onTransact(code, data, reply, flags); 3188 } catch (RuntimeException e) { 3189 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3190 Slog.wtf(TAG, "Package Manager Crash", e); 3191 } 3192 throw e; 3193 } 3194 } 3195 3196 static int[] appendInts(int[] cur, int[] add) { 3197 if (add == null) return cur; 3198 if (cur == null) return add; 3199 final int N = add.length; 3200 for (int i=0; i<N; i++) { 3201 cur = appendInt(cur, add[i]); 3202 } 3203 return cur; 3204 } 3205 3206 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3207 if (!sUserManager.exists(userId)) return null; 3208 if (ps == null) { 3209 return null; 3210 } 3211 final PackageParser.Package p = ps.pkg; 3212 if (p == null) { 3213 return null; 3214 } 3215 3216 final PermissionsState permissionsState = ps.getPermissionsState(); 3217 3218 // Compute GIDs only if requested 3219 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3220 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3221 // Compute granted permissions only if package has requested permissions 3222 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3223 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3224 final PackageUserState state = ps.readUserState(userId); 3225 3226 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3227 && ps.isSystem()) { 3228 flags |= MATCH_ANY_USER; 3229 } 3230 3231 return PackageParser.generatePackageInfo(p, gids, flags, 3232 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3233 } 3234 3235 @Override 3236 public void checkPackageStartable(String packageName, int userId) { 3237 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3238 3239 synchronized (mPackages) { 3240 final PackageSetting ps = mSettings.mPackages.get(packageName); 3241 if (ps == null) { 3242 throw new SecurityException("Package " + packageName + " was not found!"); 3243 } 3244 3245 if (!ps.getInstalled(userId)) { 3246 throw new SecurityException( 3247 "Package " + packageName + " was not installed for user " + userId + "!"); 3248 } 3249 3250 if (mSafeMode && !ps.isSystem()) { 3251 throw new SecurityException("Package " + packageName + " not a system app!"); 3252 } 3253 3254 if (mFrozenPackages.contains(packageName)) { 3255 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3256 } 3257 3258 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3259 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3260 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3261 } 3262 } 3263 } 3264 3265 @Override 3266 public boolean isPackageAvailable(String packageName, int userId) { 3267 if (!sUserManager.exists(userId)) return false; 3268 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3269 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3270 synchronized (mPackages) { 3271 PackageParser.Package p = mPackages.get(packageName); 3272 if (p != null) { 3273 final PackageSetting ps = (PackageSetting) p.mExtras; 3274 if (ps != null) { 3275 final PackageUserState state = ps.readUserState(userId); 3276 if (state != null) { 3277 return PackageParser.isAvailable(state); 3278 } 3279 } 3280 } 3281 } 3282 return false; 3283 } 3284 3285 @Override 3286 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3287 if (!sUserManager.exists(userId)) return null; 3288 flags = updateFlagsForPackage(flags, userId, packageName); 3289 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3290 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3291 3292 // reader 3293 synchronized (mPackages) { 3294 // Normalize package name to hanlde renamed packages 3295 packageName = normalizePackageNameLPr(packageName); 3296 3297 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3298 PackageParser.Package p = null; 3299 if (matchFactoryOnly) { 3300 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3301 if (ps != null) { 3302 return generatePackageInfo(ps, flags, userId); 3303 } 3304 } 3305 if (p == null) { 3306 p = mPackages.get(packageName); 3307 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3308 return null; 3309 } 3310 } 3311 if (DEBUG_PACKAGE_INFO) 3312 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3313 if (p != null) { 3314 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3315 } 3316 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3317 final PackageSetting ps = mSettings.mPackages.get(packageName); 3318 return generatePackageInfo(ps, flags, userId); 3319 } 3320 } 3321 return null; 3322 } 3323 3324 @Override 3325 public String[] currentToCanonicalPackageNames(String[] names) { 3326 String[] out = new String[names.length]; 3327 // reader 3328 synchronized (mPackages) { 3329 for (int i=names.length-1; i>=0; i--) { 3330 PackageSetting ps = mSettings.mPackages.get(names[i]); 3331 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3332 } 3333 } 3334 return out; 3335 } 3336 3337 @Override 3338 public String[] canonicalToCurrentPackageNames(String[] names) { 3339 String[] out = new String[names.length]; 3340 // reader 3341 synchronized (mPackages) { 3342 for (int i=names.length-1; i>=0; i--) { 3343 String cur = mSettings.getRenamedPackageLPr(names[i]); 3344 out[i] = cur != null ? cur : names[i]; 3345 } 3346 } 3347 return out; 3348 } 3349 3350 @Override 3351 public int getPackageUid(String packageName, int flags, int userId) { 3352 if (!sUserManager.exists(userId)) return -1; 3353 flags = updateFlagsForPackage(flags, userId, packageName); 3354 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3355 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3356 3357 // reader 3358 synchronized (mPackages) { 3359 final PackageParser.Package p = mPackages.get(packageName); 3360 if (p != null && p.isMatch(flags)) { 3361 return UserHandle.getUid(userId, p.applicationInfo.uid); 3362 } 3363 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3364 final PackageSetting ps = mSettings.mPackages.get(packageName); 3365 if (ps != null && ps.isMatch(flags)) { 3366 return UserHandle.getUid(userId, ps.appId); 3367 } 3368 } 3369 } 3370 3371 return -1; 3372 } 3373 3374 @Override 3375 public int[] getPackageGids(String packageName, int flags, int userId) { 3376 if (!sUserManager.exists(userId)) return null; 3377 flags = updateFlagsForPackage(flags, userId, packageName); 3378 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3379 false /* requireFullPermission */, false /* checkShell */, 3380 "getPackageGids"); 3381 3382 // reader 3383 synchronized (mPackages) { 3384 final PackageParser.Package p = mPackages.get(packageName); 3385 if (p != null && p.isMatch(flags)) { 3386 PackageSetting ps = (PackageSetting) p.mExtras; 3387 // TODO: Shouldn't this be checking for package installed state for userId and 3388 // return null? 3389 return ps.getPermissionsState().computeGids(userId); 3390 } 3391 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3392 final PackageSetting ps = mSettings.mPackages.get(packageName); 3393 if (ps != null && ps.isMatch(flags)) { 3394 return ps.getPermissionsState().computeGids(userId); 3395 } 3396 } 3397 } 3398 3399 return null; 3400 } 3401 3402 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3403 if (bp.perm != null) { 3404 return PackageParser.generatePermissionInfo(bp.perm, flags); 3405 } 3406 PermissionInfo pi = new PermissionInfo(); 3407 pi.name = bp.name; 3408 pi.packageName = bp.sourcePackage; 3409 pi.nonLocalizedLabel = bp.name; 3410 pi.protectionLevel = bp.protectionLevel; 3411 return pi; 3412 } 3413 3414 @Override 3415 public PermissionInfo getPermissionInfo(String name, int flags) { 3416 // reader 3417 synchronized (mPackages) { 3418 final BasePermission p = mSettings.mPermissions.get(name); 3419 if (p != null) { 3420 return generatePermissionInfo(p, flags); 3421 } 3422 return null; 3423 } 3424 } 3425 3426 @Override 3427 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3428 int flags) { 3429 // reader 3430 synchronized (mPackages) { 3431 if (group != null && !mPermissionGroups.containsKey(group)) { 3432 // This is thrown as NameNotFoundException 3433 return null; 3434 } 3435 3436 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3437 for (BasePermission p : mSettings.mPermissions.values()) { 3438 if (group == null) { 3439 if (p.perm == null || p.perm.info.group == null) { 3440 out.add(generatePermissionInfo(p, flags)); 3441 } 3442 } else { 3443 if (p.perm != null && group.equals(p.perm.info.group)) { 3444 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3445 } 3446 } 3447 } 3448 return new ParceledListSlice<>(out); 3449 } 3450 } 3451 3452 @Override 3453 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3454 // reader 3455 synchronized (mPackages) { 3456 return PackageParser.generatePermissionGroupInfo( 3457 mPermissionGroups.get(name), flags); 3458 } 3459 } 3460 3461 @Override 3462 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3463 // reader 3464 synchronized (mPackages) { 3465 final int N = mPermissionGroups.size(); 3466 ArrayList<PermissionGroupInfo> out 3467 = new ArrayList<PermissionGroupInfo>(N); 3468 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3469 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3470 } 3471 return new ParceledListSlice<>(out); 3472 } 3473 } 3474 3475 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3476 int userId) { 3477 if (!sUserManager.exists(userId)) return null; 3478 PackageSetting ps = mSettings.mPackages.get(packageName); 3479 if (ps != null) { 3480 if (ps.pkg == null) { 3481 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3482 if (pInfo != null) { 3483 return pInfo.applicationInfo; 3484 } 3485 return null; 3486 } 3487 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3488 ps.readUserState(userId), userId); 3489 } 3490 return null; 3491 } 3492 3493 @Override 3494 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3495 if (!sUserManager.exists(userId)) return null; 3496 flags = updateFlagsForApplication(flags, userId, packageName); 3497 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3498 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3499 3500 // writer 3501 synchronized (mPackages) { 3502 // Normalize package name to hanlde renamed packages 3503 packageName = normalizePackageNameLPr(packageName); 3504 3505 PackageParser.Package p = mPackages.get(packageName); 3506 if (DEBUG_PACKAGE_INFO) Log.v( 3507 TAG, "getApplicationInfo " + packageName 3508 + ": " + p); 3509 if (p != null) { 3510 PackageSetting ps = mSettings.mPackages.get(packageName); 3511 if (ps == null) return null; 3512 // Note: isEnabledLP() does not apply here - always return info 3513 return PackageParser.generateApplicationInfo( 3514 p, flags, ps.readUserState(userId), userId); 3515 } 3516 if ("android".equals(packageName)||"system".equals(packageName)) { 3517 return mAndroidApplication; 3518 } 3519 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3520 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3521 } 3522 } 3523 return null; 3524 } 3525 3526 private String normalizePackageNameLPr(String packageName) { 3527 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3528 return normalizedPackageName != null ? normalizedPackageName : packageName; 3529 } 3530 3531 @Override 3532 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3533 final IPackageDataObserver observer) { 3534 mContext.enforceCallingOrSelfPermission( 3535 android.Manifest.permission.CLEAR_APP_CACHE, null); 3536 // Queue up an async operation since clearing cache may take a little while. 3537 mHandler.post(new Runnable() { 3538 public void run() { 3539 mHandler.removeCallbacks(this); 3540 boolean success = true; 3541 synchronized (mInstallLock) { 3542 try { 3543 mInstaller.freeCache(volumeUuid, freeStorageSize); 3544 } catch (InstallerException e) { 3545 Slog.w(TAG, "Couldn't clear application caches: " + e); 3546 success = false; 3547 } 3548 } 3549 if (observer != null) { 3550 try { 3551 observer.onRemoveCompleted(null, success); 3552 } catch (RemoteException e) { 3553 Slog.w(TAG, "RemoveException when invoking call back"); 3554 } 3555 } 3556 } 3557 }); 3558 } 3559 3560 @Override 3561 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3562 final IntentSender pi) { 3563 mContext.enforceCallingOrSelfPermission( 3564 android.Manifest.permission.CLEAR_APP_CACHE, null); 3565 // Queue up an async operation since clearing cache may take a little while. 3566 mHandler.post(new Runnable() { 3567 public void run() { 3568 mHandler.removeCallbacks(this); 3569 boolean success = true; 3570 synchronized (mInstallLock) { 3571 try { 3572 mInstaller.freeCache(volumeUuid, freeStorageSize); 3573 } catch (InstallerException e) { 3574 Slog.w(TAG, "Couldn't clear application caches: " + e); 3575 success = false; 3576 } 3577 } 3578 if(pi != null) { 3579 try { 3580 // Callback via pending intent 3581 int code = success ? 1 : 0; 3582 pi.sendIntent(null, code, null, 3583 null, null); 3584 } catch (SendIntentException e1) { 3585 Slog.i(TAG, "Failed to send pending intent"); 3586 } 3587 } 3588 } 3589 }); 3590 } 3591 3592 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3593 synchronized (mInstallLock) { 3594 try { 3595 mInstaller.freeCache(volumeUuid, freeStorageSize); 3596 } catch (InstallerException e) { 3597 throw new IOException("Failed to free enough space", e); 3598 } 3599 } 3600 } 3601 3602 /** 3603 * Update given flags based on encryption status of current user. 3604 */ 3605 private int updateFlags(int flags, int userId) { 3606 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3607 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3608 // Caller expressed an explicit opinion about what encryption 3609 // aware/unaware components they want to see, so fall through and 3610 // give them what they want 3611 } else { 3612 // Caller expressed no opinion, so match based on user state 3613 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3614 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3615 } else { 3616 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3617 } 3618 } 3619 return flags; 3620 } 3621 3622 private UserManagerInternal getUserManagerInternal() { 3623 if (mUserManagerInternal == null) { 3624 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3625 } 3626 return mUserManagerInternal; 3627 } 3628 3629 /** 3630 * Update given flags when being used to request {@link PackageInfo}. 3631 */ 3632 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3633 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3634 boolean triaged = true; 3635 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3636 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3637 // Caller is asking for component details, so they'd better be 3638 // asking for specific encryption matching behavior, or be triaged 3639 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3640 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3641 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3642 triaged = false; 3643 } 3644 } 3645 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3646 | PackageManager.MATCH_SYSTEM_ONLY 3647 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3648 triaged = false; 3649 } 3650 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3651 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3652 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3653 + Debug.getCallers(5)); 3654 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3655 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3656 // If the caller wants all packages and has a restricted profile associated with it, 3657 // then match all users. This is to make sure that launchers that need to access work 3658 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3659 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3660 flags |= PackageManager.MATCH_ANY_USER; 3661 } 3662 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3663 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3664 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3665 } 3666 return updateFlags(flags, userId); 3667 } 3668 3669 /** 3670 * Update given flags when being used to request {@link ApplicationInfo}. 3671 */ 3672 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3673 return updateFlagsForPackage(flags, userId, cookie); 3674 } 3675 3676 /** 3677 * Update given flags when being used to request {@link ComponentInfo}. 3678 */ 3679 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3680 if (cookie instanceof Intent) { 3681 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3682 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3683 } 3684 } 3685 3686 boolean triaged = true; 3687 // Caller is asking for component details, so they'd better be 3688 // asking for specific encryption matching behavior, or be triaged 3689 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3690 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3691 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3692 triaged = false; 3693 } 3694 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3695 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3696 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3697 } 3698 3699 return updateFlags(flags, userId); 3700 } 3701 3702 /** 3703 * Update given flags when being used to request {@link ResolveInfo}. 3704 */ 3705 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3706 // Safe mode means we shouldn't match any third-party components 3707 if (mSafeMode) { 3708 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3709 } 3710 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 3711 if (ephemeralPkgName != null) { 3712 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3713 flags |= PackageManager.MATCH_EPHEMERAL; 3714 } 3715 3716 return updateFlagsForComponent(flags, userId, cookie); 3717 } 3718 3719 @Override 3720 public ActivityInfo getActivityInfo(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 activity info"); 3725 synchronized (mPackages) { 3726 PackageParser.Activity a = mActivities.mActivities.get(component); 3727 3728 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3729 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3730 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3731 if (ps == null) return null; 3732 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3733 userId); 3734 } 3735 if (mResolveComponentName.equals(component)) { 3736 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3737 new PackageUserState(), userId); 3738 } 3739 } 3740 return null; 3741 } 3742 3743 @Override 3744 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3745 String resolvedType) { 3746 synchronized (mPackages) { 3747 if (component.equals(mResolveComponentName)) { 3748 // The resolver supports EVERYTHING! 3749 return true; 3750 } 3751 PackageParser.Activity a = mActivities.mActivities.get(component); 3752 if (a == null) { 3753 return false; 3754 } 3755 for (int i=0; i<a.intents.size(); i++) { 3756 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3757 intent.getData(), intent.getCategories(), TAG) >= 0) { 3758 return true; 3759 } 3760 } 3761 return false; 3762 } 3763 } 3764 3765 @Override 3766 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3767 if (!sUserManager.exists(userId)) return null; 3768 flags = updateFlagsForComponent(flags, userId, component); 3769 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3770 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3771 synchronized (mPackages) { 3772 PackageParser.Activity a = mReceivers.mActivities.get(component); 3773 if (DEBUG_PACKAGE_INFO) Log.v( 3774 TAG, "getReceiverInfo " + component + ": " + a); 3775 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3776 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3777 if (ps == null) return null; 3778 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3779 userId); 3780 } 3781 } 3782 return null; 3783 } 3784 3785 @Override 3786 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3787 if (!sUserManager.exists(userId)) return null; 3788 flags = updateFlagsForComponent(flags, userId, component); 3789 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3790 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3791 synchronized (mPackages) { 3792 PackageParser.Service s = mServices.mServices.get(component); 3793 if (DEBUG_PACKAGE_INFO) Log.v( 3794 TAG, "getServiceInfo " + component + ": " + s); 3795 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3796 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3797 if (ps == null) return null; 3798 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3799 userId); 3800 } 3801 } 3802 return null; 3803 } 3804 3805 @Override 3806 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3807 if (!sUserManager.exists(userId)) return null; 3808 flags = updateFlagsForComponent(flags, userId, component); 3809 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3810 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3811 synchronized (mPackages) { 3812 PackageParser.Provider p = mProviders.mProviders.get(component); 3813 if (DEBUG_PACKAGE_INFO) Log.v( 3814 TAG, "getProviderInfo " + component + ": " + p); 3815 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3816 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3817 if (ps == null) return null; 3818 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3819 userId); 3820 } 3821 } 3822 return null; 3823 } 3824 3825 @Override 3826 public String[] getSystemSharedLibraryNames() { 3827 Set<String> libSet; 3828 synchronized (mPackages) { 3829 libSet = mSharedLibraries.keySet(); 3830 int size = libSet.size(); 3831 if (size > 0) { 3832 String[] libs = new String[size]; 3833 libSet.toArray(libs); 3834 return libs; 3835 } 3836 } 3837 return null; 3838 } 3839 3840 @Override 3841 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3842 synchronized (mPackages) { 3843 return mServicesSystemSharedLibraryPackageName; 3844 } 3845 } 3846 3847 @Override 3848 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3849 synchronized (mPackages) { 3850 return mSharedSystemSharedLibraryPackageName; 3851 } 3852 } 3853 3854 @Override 3855 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3856 synchronized (mPackages) { 3857 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3858 3859 final FeatureInfo fi = new FeatureInfo(); 3860 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3861 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3862 res.add(fi); 3863 3864 return new ParceledListSlice<>(res); 3865 } 3866 } 3867 3868 @Override 3869 public boolean hasSystemFeature(String name, int version) { 3870 synchronized (mPackages) { 3871 final FeatureInfo feat = mAvailableFeatures.get(name); 3872 if (feat == null) { 3873 return false; 3874 } else { 3875 return feat.version >= version; 3876 } 3877 } 3878 } 3879 3880 @Override 3881 public int checkPermission(String permName, String pkgName, int userId) { 3882 if (!sUserManager.exists(userId)) { 3883 return PackageManager.PERMISSION_DENIED; 3884 } 3885 3886 synchronized (mPackages) { 3887 final PackageParser.Package p = mPackages.get(pkgName); 3888 if (p != null && p.mExtras != null) { 3889 final PackageSetting ps = (PackageSetting) p.mExtras; 3890 final PermissionsState permissionsState = ps.getPermissionsState(); 3891 if (permissionsState.hasPermission(permName, userId)) { 3892 return PackageManager.PERMISSION_GRANTED; 3893 } 3894 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3895 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3896 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3897 return PackageManager.PERMISSION_GRANTED; 3898 } 3899 } 3900 } 3901 3902 return PackageManager.PERMISSION_DENIED; 3903 } 3904 3905 @Override 3906 public int checkUidPermission(String permName, int uid) { 3907 final int userId = UserHandle.getUserId(uid); 3908 3909 if (!sUserManager.exists(userId)) { 3910 return PackageManager.PERMISSION_DENIED; 3911 } 3912 3913 synchronized (mPackages) { 3914 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3915 if (obj != null) { 3916 final SettingBase ps = (SettingBase) obj; 3917 final PermissionsState permissionsState = ps.getPermissionsState(); 3918 if (permissionsState.hasPermission(permName, userId)) { 3919 return PackageManager.PERMISSION_GRANTED; 3920 } 3921 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3922 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3923 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3924 return PackageManager.PERMISSION_GRANTED; 3925 } 3926 } else { 3927 ArraySet<String> perms = mSystemPermissions.get(uid); 3928 if (perms != null) { 3929 if (perms.contains(permName)) { 3930 return PackageManager.PERMISSION_GRANTED; 3931 } 3932 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3933 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3934 return PackageManager.PERMISSION_GRANTED; 3935 } 3936 } 3937 } 3938 } 3939 3940 return PackageManager.PERMISSION_DENIED; 3941 } 3942 3943 @Override 3944 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3945 if (UserHandle.getCallingUserId() != userId) { 3946 mContext.enforceCallingPermission( 3947 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3948 "isPermissionRevokedByPolicy for user " + userId); 3949 } 3950 3951 if (checkPermission(permission, packageName, userId) 3952 == PackageManager.PERMISSION_GRANTED) { 3953 return false; 3954 } 3955 3956 final long identity = Binder.clearCallingIdentity(); 3957 try { 3958 final int flags = getPermissionFlags(permission, packageName, userId); 3959 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3960 } finally { 3961 Binder.restoreCallingIdentity(identity); 3962 } 3963 } 3964 3965 @Override 3966 public String getPermissionControllerPackageName() { 3967 synchronized (mPackages) { 3968 return mRequiredInstallerPackage; 3969 } 3970 } 3971 3972 /** 3973 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3974 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3975 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3976 * @param message the message to log on security exception 3977 */ 3978 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3979 boolean checkShell, String message) { 3980 if (userId < 0) { 3981 throw new IllegalArgumentException("Invalid userId " + userId); 3982 } 3983 if (checkShell) { 3984 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3985 } 3986 if (userId == UserHandle.getUserId(callingUid)) return; 3987 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3988 if (requireFullPermission) { 3989 mContext.enforceCallingOrSelfPermission( 3990 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3991 } else { 3992 try { 3993 mContext.enforceCallingOrSelfPermission( 3994 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3995 } catch (SecurityException se) { 3996 mContext.enforceCallingOrSelfPermission( 3997 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3998 } 3999 } 4000 } 4001 } 4002 4003 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4004 if (callingUid == Process.SHELL_UID) { 4005 if (userHandle >= 0 4006 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4007 throw new SecurityException("Shell does not have permission to access user " 4008 + userHandle); 4009 } else if (userHandle < 0) { 4010 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4011 + Debug.getCallers(3)); 4012 } 4013 } 4014 } 4015 4016 private BasePermission findPermissionTreeLP(String permName) { 4017 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4018 if (permName.startsWith(bp.name) && 4019 permName.length() > bp.name.length() && 4020 permName.charAt(bp.name.length()) == '.') { 4021 return bp; 4022 } 4023 } 4024 return null; 4025 } 4026 4027 private BasePermission checkPermissionTreeLP(String permName) { 4028 if (permName != null) { 4029 BasePermission bp = findPermissionTreeLP(permName); 4030 if (bp != null) { 4031 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4032 return bp; 4033 } 4034 throw new SecurityException("Calling uid " 4035 + Binder.getCallingUid() 4036 + " is not allowed to add to permission tree " 4037 + bp.name + " owned by uid " + bp.uid); 4038 } 4039 } 4040 throw new SecurityException("No permission tree found for " + permName); 4041 } 4042 4043 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4044 if (s1 == null) { 4045 return s2 == null; 4046 } 4047 if (s2 == null) { 4048 return false; 4049 } 4050 if (s1.getClass() != s2.getClass()) { 4051 return false; 4052 } 4053 return s1.equals(s2); 4054 } 4055 4056 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4057 if (pi1.icon != pi2.icon) return false; 4058 if (pi1.logo != pi2.logo) return false; 4059 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4060 if (!compareStrings(pi1.name, pi2.name)) return false; 4061 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4062 // We'll take care of setting this one. 4063 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4064 // These are not currently stored in settings. 4065 //if (!compareStrings(pi1.group, pi2.group)) return false; 4066 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4067 //if (pi1.labelRes != pi2.labelRes) return false; 4068 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4069 return true; 4070 } 4071 4072 int permissionInfoFootprint(PermissionInfo info) { 4073 int size = info.name.length(); 4074 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4075 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4076 return size; 4077 } 4078 4079 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4080 int size = 0; 4081 for (BasePermission perm : mSettings.mPermissions.values()) { 4082 if (perm.uid == tree.uid) { 4083 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4084 } 4085 } 4086 return size; 4087 } 4088 4089 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4090 // We calculate the max size of permissions defined by this uid and throw 4091 // if that plus the size of 'info' would exceed our stated maximum. 4092 if (tree.uid != Process.SYSTEM_UID) { 4093 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4094 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4095 throw new SecurityException("Permission tree size cap exceeded"); 4096 } 4097 } 4098 } 4099 4100 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4101 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4102 throw new SecurityException("Label must be specified in permission"); 4103 } 4104 BasePermission tree = checkPermissionTreeLP(info.name); 4105 BasePermission bp = mSettings.mPermissions.get(info.name); 4106 boolean added = bp == null; 4107 boolean changed = true; 4108 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4109 if (added) { 4110 enforcePermissionCapLocked(info, tree); 4111 bp = new BasePermission(info.name, tree.sourcePackage, 4112 BasePermission.TYPE_DYNAMIC); 4113 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4114 throw new SecurityException( 4115 "Not allowed to modify non-dynamic permission " 4116 + info.name); 4117 } else { 4118 if (bp.protectionLevel == fixedLevel 4119 && bp.perm.owner.equals(tree.perm.owner) 4120 && bp.uid == tree.uid 4121 && comparePermissionInfos(bp.perm.info, info)) { 4122 changed = false; 4123 } 4124 } 4125 bp.protectionLevel = fixedLevel; 4126 info = new PermissionInfo(info); 4127 info.protectionLevel = fixedLevel; 4128 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4129 bp.perm.info.packageName = tree.perm.info.packageName; 4130 bp.uid = tree.uid; 4131 if (added) { 4132 mSettings.mPermissions.put(info.name, bp); 4133 } 4134 if (changed) { 4135 if (!async) { 4136 mSettings.writeLPr(); 4137 } else { 4138 scheduleWriteSettingsLocked(); 4139 } 4140 } 4141 return added; 4142 } 4143 4144 @Override 4145 public boolean addPermission(PermissionInfo info) { 4146 synchronized (mPackages) { 4147 return addPermissionLocked(info, false); 4148 } 4149 } 4150 4151 @Override 4152 public boolean addPermissionAsync(PermissionInfo info) { 4153 synchronized (mPackages) { 4154 return addPermissionLocked(info, true); 4155 } 4156 } 4157 4158 @Override 4159 public void removePermission(String name) { 4160 synchronized (mPackages) { 4161 checkPermissionTreeLP(name); 4162 BasePermission bp = mSettings.mPermissions.get(name); 4163 if (bp != null) { 4164 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4165 throw new SecurityException( 4166 "Not allowed to modify non-dynamic permission " 4167 + name); 4168 } 4169 mSettings.mPermissions.remove(name); 4170 mSettings.writeLPr(); 4171 } 4172 } 4173 } 4174 4175 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4176 BasePermission bp) { 4177 int index = pkg.requestedPermissions.indexOf(bp.name); 4178 if (index == -1) { 4179 throw new SecurityException("Package " + pkg.packageName 4180 + " has not requested permission " + bp.name); 4181 } 4182 if (!bp.isRuntime() && !bp.isDevelopment()) { 4183 throw new SecurityException("Permission " + bp.name 4184 + " is not a changeable permission type"); 4185 } 4186 } 4187 4188 @Override 4189 public void grantRuntimePermission(String packageName, String name, final int userId) { 4190 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4191 } 4192 4193 private void grantRuntimePermission(String packageName, String name, final int userId, 4194 boolean overridePolicy) { 4195 if (!sUserManager.exists(userId)) { 4196 Log.e(TAG, "No such user:" + userId); 4197 return; 4198 } 4199 4200 mContext.enforceCallingOrSelfPermission( 4201 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4202 "grantRuntimePermission"); 4203 4204 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4205 true /* requireFullPermission */, true /* checkShell */, 4206 "grantRuntimePermission"); 4207 4208 final int uid; 4209 final SettingBase sb; 4210 4211 synchronized (mPackages) { 4212 final PackageParser.Package pkg = mPackages.get(packageName); 4213 if (pkg == null) { 4214 throw new IllegalArgumentException("Unknown package: " + packageName); 4215 } 4216 4217 final BasePermission bp = mSettings.mPermissions.get(name); 4218 if (bp == null) { 4219 throw new IllegalArgumentException("Unknown permission: " + name); 4220 } 4221 4222 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4223 4224 // If a permission review is required for legacy apps we represent 4225 // their permissions as always granted runtime ones since we need 4226 // to keep the review required permission flag per user while an 4227 // install permission's state is shared across all users. 4228 if (mPermissionReviewRequired 4229 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4230 && bp.isRuntime()) { 4231 return; 4232 } 4233 4234 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4235 sb = (SettingBase) pkg.mExtras; 4236 if (sb == null) { 4237 throw new IllegalArgumentException("Unknown package: " + packageName); 4238 } 4239 4240 final PermissionsState permissionsState = sb.getPermissionsState(); 4241 4242 final int flags = permissionsState.getPermissionFlags(name, userId); 4243 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4244 throw new SecurityException("Cannot grant system fixed permission " 4245 + name + " for package " + packageName); 4246 } 4247 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4248 throw new SecurityException("Cannot grant policy fixed permission " 4249 + name + " for package " + packageName); 4250 } 4251 4252 if (bp.isDevelopment()) { 4253 // Development permissions must be handled specially, since they are not 4254 // normal runtime permissions. For now they apply to all users. 4255 if (permissionsState.grantInstallPermission(bp) != 4256 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4257 scheduleWriteSettingsLocked(); 4258 } 4259 return; 4260 } 4261 4262 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4263 throw new SecurityException("Cannot grant non-ephemeral permission" 4264 + name + " for package " + packageName); 4265 } 4266 4267 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4268 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4269 return; 4270 } 4271 4272 final int result = permissionsState.grantRuntimePermission(bp, userId); 4273 switch (result) { 4274 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4275 return; 4276 } 4277 4278 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4279 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4280 mHandler.post(new Runnable() { 4281 @Override 4282 public void run() { 4283 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4284 } 4285 }); 4286 } 4287 break; 4288 } 4289 4290 if (bp.isRuntime()) { 4291 logPermissionGranted(mContext, name, packageName); 4292 } 4293 4294 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4295 4296 // Not critical if that is lost - app has to request again. 4297 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4298 } 4299 4300 // Only need to do this if user is initialized. Otherwise it's a new user 4301 // and there are no processes running as the user yet and there's no need 4302 // to make an expensive call to remount processes for the changed permissions. 4303 if (READ_EXTERNAL_STORAGE.equals(name) 4304 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4305 final long token = Binder.clearCallingIdentity(); 4306 try { 4307 if (sUserManager.isInitialized(userId)) { 4308 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4309 StorageManagerInternal.class); 4310 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4311 } 4312 } finally { 4313 Binder.restoreCallingIdentity(token); 4314 } 4315 } 4316 } 4317 4318 @Override 4319 public void revokeRuntimePermission(String packageName, String name, int userId) { 4320 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4321 } 4322 4323 private void revokeRuntimePermission(String packageName, String name, int userId, 4324 boolean overridePolicy) { 4325 if (!sUserManager.exists(userId)) { 4326 Log.e(TAG, "No such user:" + userId); 4327 return; 4328 } 4329 4330 mContext.enforceCallingOrSelfPermission( 4331 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4332 "revokeRuntimePermission"); 4333 4334 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4335 true /* requireFullPermission */, true /* checkShell */, 4336 "revokeRuntimePermission"); 4337 4338 final int appId; 4339 4340 synchronized (mPackages) { 4341 final PackageParser.Package pkg = mPackages.get(packageName); 4342 if (pkg == null) { 4343 throw new IllegalArgumentException("Unknown package: " + packageName); 4344 } 4345 4346 final BasePermission bp = mSettings.mPermissions.get(name); 4347 if (bp == null) { 4348 throw new IllegalArgumentException("Unknown permission: " + name); 4349 } 4350 4351 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4352 4353 // If a permission review is required for legacy apps we represent 4354 // their permissions as always granted runtime ones since we need 4355 // to keep the review required permission flag per user while an 4356 // install permission's state is shared across all users. 4357 if (mPermissionReviewRequired 4358 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4359 && bp.isRuntime()) { 4360 return; 4361 } 4362 4363 SettingBase sb = (SettingBase) pkg.mExtras; 4364 if (sb == null) { 4365 throw new IllegalArgumentException("Unknown package: " + packageName); 4366 } 4367 4368 final PermissionsState permissionsState = sb.getPermissionsState(); 4369 4370 final int flags = permissionsState.getPermissionFlags(name, userId); 4371 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4372 throw new SecurityException("Cannot revoke system fixed permission " 4373 + name + " for package " + packageName); 4374 } 4375 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4376 throw new SecurityException("Cannot revoke policy fixed permission " 4377 + name + " for package " + packageName); 4378 } 4379 4380 if (bp.isDevelopment()) { 4381 // Development permissions must be handled specially, since they are not 4382 // normal runtime permissions. For now they apply to all users. 4383 if (permissionsState.revokeInstallPermission(bp) != 4384 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4385 scheduleWriteSettingsLocked(); 4386 } 4387 return; 4388 } 4389 4390 if (permissionsState.revokeRuntimePermission(bp, userId) == 4391 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4392 return; 4393 } 4394 4395 if (bp.isRuntime()) { 4396 logPermissionRevoked(mContext, name, packageName); 4397 } 4398 4399 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4400 4401 // Critical, after this call app should never have the permission. 4402 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4403 4404 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4405 } 4406 4407 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4408 } 4409 4410 /** 4411 * Get the first event id for the permission. 4412 * 4413 * <p>There are four events for each permission: <ul> 4414 * <li>Request permission: first id + 0</li> 4415 * <li>Grant permission: first id + 1</li> 4416 * <li>Request for permission denied: first id + 2</li> 4417 * <li>Revoke permission: first id + 3</li> 4418 * </ul></p> 4419 * 4420 * @param name name of the permission 4421 * 4422 * @return The first event id for the permission 4423 */ 4424 private static int getBaseEventId(@NonNull String name) { 4425 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4426 4427 if (eventIdIndex == -1) { 4428 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4429 || "user".equals(Build.TYPE)) { 4430 Log.i(TAG, "Unknown permission " + name); 4431 4432 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4433 } else { 4434 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4435 // 4436 // Also update 4437 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4438 // - metrics_constants.proto 4439 throw new IllegalStateException("Unknown permission " + name); 4440 } 4441 } 4442 4443 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4444 } 4445 4446 /** 4447 * Log that a permission was revoked. 4448 * 4449 * @param context Context of the caller 4450 * @param name name of the permission 4451 * @param packageName package permission if for 4452 */ 4453 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4454 @NonNull String packageName) { 4455 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4456 } 4457 4458 /** 4459 * Log that a permission request was granted. 4460 * 4461 * @param context Context of the caller 4462 * @param name name of the permission 4463 * @param packageName package permission if for 4464 */ 4465 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4466 @NonNull String packageName) { 4467 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4468 } 4469 4470 @Override 4471 public void resetRuntimePermissions() { 4472 mContext.enforceCallingOrSelfPermission( 4473 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4474 "revokeRuntimePermission"); 4475 4476 int callingUid = Binder.getCallingUid(); 4477 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4478 mContext.enforceCallingOrSelfPermission( 4479 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4480 "resetRuntimePermissions"); 4481 } 4482 4483 synchronized (mPackages) { 4484 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4485 for (int userId : UserManagerService.getInstance().getUserIds()) { 4486 final int packageCount = mPackages.size(); 4487 for (int i = 0; i < packageCount; i++) { 4488 PackageParser.Package pkg = mPackages.valueAt(i); 4489 if (!(pkg.mExtras instanceof PackageSetting)) { 4490 continue; 4491 } 4492 PackageSetting ps = (PackageSetting) pkg.mExtras; 4493 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4494 } 4495 } 4496 } 4497 } 4498 4499 @Override 4500 public int getPermissionFlags(String name, String packageName, int userId) { 4501 if (!sUserManager.exists(userId)) { 4502 return 0; 4503 } 4504 4505 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4506 4507 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4508 true /* requireFullPermission */, false /* checkShell */, 4509 "getPermissionFlags"); 4510 4511 synchronized (mPackages) { 4512 final PackageParser.Package pkg = mPackages.get(packageName); 4513 if (pkg == null) { 4514 return 0; 4515 } 4516 4517 final BasePermission bp = mSettings.mPermissions.get(name); 4518 if (bp == null) { 4519 return 0; 4520 } 4521 4522 SettingBase sb = (SettingBase) pkg.mExtras; 4523 if (sb == null) { 4524 return 0; 4525 } 4526 4527 PermissionsState permissionsState = sb.getPermissionsState(); 4528 return permissionsState.getPermissionFlags(name, userId); 4529 } 4530 } 4531 4532 @Override 4533 public void updatePermissionFlags(String name, String packageName, int flagMask, 4534 int flagValues, int userId) { 4535 if (!sUserManager.exists(userId)) { 4536 return; 4537 } 4538 4539 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4540 4541 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4542 true /* requireFullPermission */, true /* checkShell */, 4543 "updatePermissionFlags"); 4544 4545 // Only the system can change these flags and nothing else. 4546 if (getCallingUid() != Process.SYSTEM_UID) { 4547 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4548 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4549 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4550 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4551 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4552 } 4553 4554 synchronized (mPackages) { 4555 final PackageParser.Package pkg = mPackages.get(packageName); 4556 if (pkg == null) { 4557 throw new IllegalArgumentException("Unknown package: " + packageName); 4558 } 4559 4560 final BasePermission bp = mSettings.mPermissions.get(name); 4561 if (bp == null) { 4562 throw new IllegalArgumentException("Unknown permission: " + name); 4563 } 4564 4565 SettingBase sb = (SettingBase) pkg.mExtras; 4566 if (sb == null) { 4567 throw new IllegalArgumentException("Unknown package: " + packageName); 4568 } 4569 4570 PermissionsState permissionsState = sb.getPermissionsState(); 4571 4572 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4573 4574 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4575 // Install and runtime permissions are stored in different places, 4576 // so figure out what permission changed and persist the change. 4577 if (permissionsState.getInstallPermissionState(name) != null) { 4578 scheduleWriteSettingsLocked(); 4579 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4580 || hadState) { 4581 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4582 } 4583 } 4584 } 4585 } 4586 4587 /** 4588 * Update the permission flags for all packages and runtime permissions of a user in order 4589 * to allow device or profile owner to remove POLICY_FIXED. 4590 */ 4591 @Override 4592 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4593 if (!sUserManager.exists(userId)) { 4594 return; 4595 } 4596 4597 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4598 4599 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4600 true /* requireFullPermission */, true /* checkShell */, 4601 "updatePermissionFlagsForAllApps"); 4602 4603 // Only the system can change system fixed flags. 4604 if (getCallingUid() != Process.SYSTEM_UID) { 4605 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4606 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4607 } 4608 4609 synchronized (mPackages) { 4610 boolean changed = false; 4611 final int packageCount = mPackages.size(); 4612 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4613 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4614 SettingBase sb = (SettingBase) pkg.mExtras; 4615 if (sb == null) { 4616 continue; 4617 } 4618 PermissionsState permissionsState = sb.getPermissionsState(); 4619 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4620 userId, flagMask, flagValues); 4621 } 4622 if (changed) { 4623 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4624 } 4625 } 4626 } 4627 4628 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4629 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4630 != PackageManager.PERMISSION_GRANTED 4631 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4632 != PackageManager.PERMISSION_GRANTED) { 4633 throw new SecurityException(message + " requires " 4634 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4635 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4636 } 4637 } 4638 4639 @Override 4640 public boolean shouldShowRequestPermissionRationale(String permissionName, 4641 String packageName, int userId) { 4642 if (UserHandle.getCallingUserId() != userId) { 4643 mContext.enforceCallingPermission( 4644 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4645 "canShowRequestPermissionRationale for user " + userId); 4646 } 4647 4648 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4649 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4650 return false; 4651 } 4652 4653 if (checkPermission(permissionName, packageName, userId) 4654 == PackageManager.PERMISSION_GRANTED) { 4655 return false; 4656 } 4657 4658 final int flags; 4659 4660 final long identity = Binder.clearCallingIdentity(); 4661 try { 4662 flags = getPermissionFlags(permissionName, 4663 packageName, userId); 4664 } finally { 4665 Binder.restoreCallingIdentity(identity); 4666 } 4667 4668 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4669 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4670 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4671 4672 if ((flags & fixedFlags) != 0) { 4673 return false; 4674 } 4675 4676 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4677 } 4678 4679 @Override 4680 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4681 mContext.enforceCallingOrSelfPermission( 4682 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4683 "addOnPermissionsChangeListener"); 4684 4685 synchronized (mPackages) { 4686 mOnPermissionChangeListeners.addListenerLocked(listener); 4687 } 4688 } 4689 4690 @Override 4691 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4692 synchronized (mPackages) { 4693 mOnPermissionChangeListeners.removeListenerLocked(listener); 4694 } 4695 } 4696 4697 @Override 4698 public boolean isProtectedBroadcast(String actionName) { 4699 synchronized (mPackages) { 4700 if (mProtectedBroadcasts.contains(actionName)) { 4701 return true; 4702 } else if (actionName != null) { 4703 // TODO: remove these terrible hacks 4704 if (actionName.startsWith("android.net.netmon.lingerExpired") 4705 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4706 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4707 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4708 return true; 4709 } 4710 } 4711 } 4712 return false; 4713 } 4714 4715 @Override 4716 public int checkSignatures(String pkg1, String pkg2) { 4717 synchronized (mPackages) { 4718 final PackageParser.Package p1 = mPackages.get(pkg1); 4719 final PackageParser.Package p2 = mPackages.get(pkg2); 4720 if (p1 == null || p1.mExtras == null 4721 || p2 == null || p2.mExtras == null) { 4722 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4723 } 4724 return compareSignatures(p1.mSignatures, p2.mSignatures); 4725 } 4726 } 4727 4728 @Override 4729 public int checkUidSignatures(int uid1, int uid2) { 4730 // Map to base uids. 4731 uid1 = UserHandle.getAppId(uid1); 4732 uid2 = UserHandle.getAppId(uid2); 4733 // reader 4734 synchronized (mPackages) { 4735 Signature[] s1; 4736 Signature[] s2; 4737 Object obj = mSettings.getUserIdLPr(uid1); 4738 if (obj != null) { 4739 if (obj instanceof SharedUserSetting) { 4740 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4741 } else if (obj instanceof PackageSetting) { 4742 s1 = ((PackageSetting)obj).signatures.mSignatures; 4743 } else { 4744 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4745 } 4746 } else { 4747 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4748 } 4749 obj = mSettings.getUserIdLPr(uid2); 4750 if (obj != null) { 4751 if (obj instanceof SharedUserSetting) { 4752 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4753 } else if (obj instanceof PackageSetting) { 4754 s2 = ((PackageSetting)obj).signatures.mSignatures; 4755 } else { 4756 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4757 } 4758 } else { 4759 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4760 } 4761 return compareSignatures(s1, s2); 4762 } 4763 } 4764 4765 /** 4766 * This method should typically only be used when granting or revoking 4767 * permissions, since the app may immediately restart after this call. 4768 * <p> 4769 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4770 * guard your work against the app being relaunched. 4771 */ 4772 private void killUid(int appId, int userId, String reason) { 4773 final long identity = Binder.clearCallingIdentity(); 4774 try { 4775 IActivityManager am = ActivityManager.getService(); 4776 if (am != null) { 4777 try { 4778 am.killUid(appId, userId, reason); 4779 } catch (RemoteException e) { 4780 /* ignore - same process */ 4781 } 4782 } 4783 } finally { 4784 Binder.restoreCallingIdentity(identity); 4785 } 4786 } 4787 4788 /** 4789 * Compares two sets of signatures. Returns: 4790 * <br /> 4791 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4792 * <br /> 4793 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4794 * <br /> 4795 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4796 * <br /> 4797 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4798 * <br /> 4799 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4800 */ 4801 static int compareSignatures(Signature[] s1, Signature[] s2) { 4802 if (s1 == null) { 4803 return s2 == null 4804 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4805 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4806 } 4807 4808 if (s2 == null) { 4809 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4810 } 4811 4812 if (s1.length != s2.length) { 4813 return PackageManager.SIGNATURE_NO_MATCH; 4814 } 4815 4816 // Since both signature sets are of size 1, we can compare without HashSets. 4817 if (s1.length == 1) { 4818 return s1[0].equals(s2[0]) ? 4819 PackageManager.SIGNATURE_MATCH : 4820 PackageManager.SIGNATURE_NO_MATCH; 4821 } 4822 4823 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4824 for (Signature sig : s1) { 4825 set1.add(sig); 4826 } 4827 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4828 for (Signature sig : s2) { 4829 set2.add(sig); 4830 } 4831 // Make sure s2 contains all signatures in s1. 4832 if (set1.equals(set2)) { 4833 return PackageManager.SIGNATURE_MATCH; 4834 } 4835 return PackageManager.SIGNATURE_NO_MATCH; 4836 } 4837 4838 /** 4839 * If the database version for this type of package (internal storage or 4840 * external storage) is less than the version where package signatures 4841 * were updated, return true. 4842 */ 4843 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4844 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4845 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4846 } 4847 4848 /** 4849 * Used for backward compatibility to make sure any packages with 4850 * certificate chains get upgraded to the new style. {@code existingSigs} 4851 * will be in the old format (since they were stored on disk from before the 4852 * system upgrade) and {@code scannedSigs} will be in the newer format. 4853 */ 4854 private int compareSignaturesCompat(PackageSignatures existingSigs, 4855 PackageParser.Package scannedPkg) { 4856 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4857 return PackageManager.SIGNATURE_NO_MATCH; 4858 } 4859 4860 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4861 for (Signature sig : existingSigs.mSignatures) { 4862 existingSet.add(sig); 4863 } 4864 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4865 for (Signature sig : scannedPkg.mSignatures) { 4866 try { 4867 Signature[] chainSignatures = sig.getChainSignatures(); 4868 for (Signature chainSig : chainSignatures) { 4869 scannedCompatSet.add(chainSig); 4870 } 4871 } catch (CertificateEncodingException e) { 4872 scannedCompatSet.add(sig); 4873 } 4874 } 4875 /* 4876 * Make sure the expanded scanned set contains all signatures in the 4877 * existing one. 4878 */ 4879 if (scannedCompatSet.equals(existingSet)) { 4880 // Migrate the old signatures to the new scheme. 4881 existingSigs.assignSignatures(scannedPkg.mSignatures); 4882 // The new KeySets will be re-added later in the scanning process. 4883 synchronized (mPackages) { 4884 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4885 } 4886 return PackageManager.SIGNATURE_MATCH; 4887 } 4888 return PackageManager.SIGNATURE_NO_MATCH; 4889 } 4890 4891 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4892 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4893 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4894 } 4895 4896 private int compareSignaturesRecover(PackageSignatures existingSigs, 4897 PackageParser.Package scannedPkg) { 4898 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4899 return PackageManager.SIGNATURE_NO_MATCH; 4900 } 4901 4902 String msg = null; 4903 try { 4904 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4905 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4906 + scannedPkg.packageName); 4907 return PackageManager.SIGNATURE_MATCH; 4908 } 4909 } catch (CertificateException e) { 4910 msg = e.getMessage(); 4911 } 4912 4913 logCriticalInfo(Log.INFO, 4914 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4915 return PackageManager.SIGNATURE_NO_MATCH; 4916 } 4917 4918 @Override 4919 public List<String> getAllPackages() { 4920 synchronized (mPackages) { 4921 return new ArrayList<String>(mPackages.keySet()); 4922 } 4923 } 4924 4925 @Override 4926 public String[] getPackagesForUid(int uid) { 4927 final int userId = UserHandle.getUserId(uid); 4928 uid = UserHandle.getAppId(uid); 4929 // reader 4930 synchronized (mPackages) { 4931 Object obj = mSettings.getUserIdLPr(uid); 4932 if (obj instanceof SharedUserSetting) { 4933 final SharedUserSetting sus = (SharedUserSetting) obj; 4934 final int N = sus.packages.size(); 4935 String[] res = new String[N]; 4936 final Iterator<PackageSetting> it = sus.packages.iterator(); 4937 int i = 0; 4938 while (it.hasNext()) { 4939 PackageSetting ps = it.next(); 4940 if (ps.getInstalled(userId)) { 4941 res[i++] = ps.name; 4942 } else { 4943 res = ArrayUtils.removeElement(String.class, res, res[i]); 4944 } 4945 } 4946 return res; 4947 } else if (obj instanceof PackageSetting) { 4948 final PackageSetting ps = (PackageSetting) obj; 4949 return new String[] { ps.name }; 4950 } 4951 } 4952 return null; 4953 } 4954 4955 @Override 4956 public String getNameForUid(int uid) { 4957 // reader 4958 synchronized (mPackages) { 4959 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4960 if (obj instanceof SharedUserSetting) { 4961 final SharedUserSetting sus = (SharedUserSetting) obj; 4962 return sus.name + ":" + sus.userId; 4963 } else if (obj instanceof PackageSetting) { 4964 final PackageSetting ps = (PackageSetting) obj; 4965 return ps.name; 4966 } 4967 } 4968 return null; 4969 } 4970 4971 @Override 4972 public int getUidForSharedUser(String sharedUserName) { 4973 if(sharedUserName == null) { 4974 return -1; 4975 } 4976 // reader 4977 synchronized (mPackages) { 4978 SharedUserSetting suid; 4979 try { 4980 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4981 if (suid != null) { 4982 return suid.userId; 4983 } 4984 } catch (PackageManagerException ignore) { 4985 // can't happen, but, still need to catch it 4986 } 4987 return -1; 4988 } 4989 } 4990 4991 @Override 4992 public int getFlagsForUid(int uid) { 4993 synchronized (mPackages) { 4994 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4995 if (obj instanceof SharedUserSetting) { 4996 final SharedUserSetting sus = (SharedUserSetting) obj; 4997 return sus.pkgFlags; 4998 } else if (obj instanceof PackageSetting) { 4999 final PackageSetting ps = (PackageSetting) obj; 5000 return ps.pkgFlags; 5001 } 5002 } 5003 return 0; 5004 } 5005 5006 @Override 5007 public int getPrivateFlagsForUid(int uid) { 5008 synchronized (mPackages) { 5009 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5010 if (obj instanceof SharedUserSetting) { 5011 final SharedUserSetting sus = (SharedUserSetting) obj; 5012 return sus.pkgPrivateFlags; 5013 } else if (obj instanceof PackageSetting) { 5014 final PackageSetting ps = (PackageSetting) obj; 5015 return ps.pkgPrivateFlags; 5016 } 5017 } 5018 return 0; 5019 } 5020 5021 @Override 5022 public boolean isUidPrivileged(int uid) { 5023 uid = UserHandle.getAppId(uid); 5024 // reader 5025 synchronized (mPackages) { 5026 Object obj = mSettings.getUserIdLPr(uid); 5027 if (obj instanceof SharedUserSetting) { 5028 final SharedUserSetting sus = (SharedUserSetting) obj; 5029 final Iterator<PackageSetting> it = sus.packages.iterator(); 5030 while (it.hasNext()) { 5031 if (it.next().isPrivileged()) { 5032 return true; 5033 } 5034 } 5035 } else if (obj instanceof PackageSetting) { 5036 final PackageSetting ps = (PackageSetting) obj; 5037 return ps.isPrivileged(); 5038 } 5039 } 5040 return false; 5041 } 5042 5043 @Override 5044 public String[] getAppOpPermissionPackages(String permissionName) { 5045 synchronized (mPackages) { 5046 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5047 if (pkgs == null) { 5048 return null; 5049 } 5050 return pkgs.toArray(new String[pkgs.size()]); 5051 } 5052 } 5053 5054 @Override 5055 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5056 int flags, int userId) { 5057 try { 5058 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5059 5060 if (!sUserManager.exists(userId)) return null; 5061 flags = updateFlagsForResolve(flags, userId, intent); 5062 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5063 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5064 5065 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5066 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5067 flags, userId); 5068 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5069 5070 final ResolveInfo bestChoice = 5071 chooseBestActivity(intent, resolvedType, flags, query, userId); 5072 return bestChoice; 5073 } finally { 5074 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5075 } 5076 } 5077 5078 @Override 5079 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5080 IntentFilter filter, int match, ComponentName activity) { 5081 final int userId = UserHandle.getCallingUserId(); 5082 if (DEBUG_PREFERRED) { 5083 Log.v(TAG, "setLastChosenActivity intent=" + intent 5084 + " resolvedType=" + resolvedType 5085 + " flags=" + flags 5086 + " filter=" + filter 5087 + " match=" + match 5088 + " activity=" + activity); 5089 filter.dump(new PrintStreamPrinter(System.out), " "); 5090 } 5091 intent.setComponent(null); 5092 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5093 userId); 5094 // Find any earlier preferred or last chosen entries and nuke them 5095 findPreferredActivity(intent, resolvedType, 5096 flags, query, 0, false, true, false, userId); 5097 // Add the new activity as the last chosen for this filter 5098 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5099 "Setting last chosen"); 5100 } 5101 5102 @Override 5103 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5104 final int userId = UserHandle.getCallingUserId(); 5105 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5106 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5107 userId); 5108 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5109 false, false, false, userId); 5110 } 5111 5112 private boolean isEphemeralDisabled() { 5113 // ephemeral apps have been disabled across the board 5114 if (DISABLE_EPHEMERAL_APPS) { 5115 return true; 5116 } 5117 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5118 if (!mSystemReady) { 5119 return true; 5120 } 5121 // we can't get a content resolver until the system is ready; these checks must happen last 5122 final ContentResolver resolver = mContext.getContentResolver(); 5123 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5124 return true; 5125 } 5126 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5127 } 5128 5129 private boolean isEphemeralAllowed( 5130 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5131 boolean skipPackageCheck) { 5132 // Short circuit and return early if possible. 5133 if (isEphemeralDisabled()) { 5134 return false; 5135 } 5136 final int callingUser = UserHandle.getCallingUserId(); 5137 if (callingUser != UserHandle.USER_SYSTEM) { 5138 return false; 5139 } 5140 if (mEphemeralResolverConnection == null) { 5141 return false; 5142 } 5143 if (mEphemeralInstallerComponent == null) { 5144 return false; 5145 } 5146 if (intent.getComponent() != null) { 5147 return false; 5148 } 5149 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5150 return false; 5151 } 5152 if (!skipPackageCheck && intent.getPackage() != null) { 5153 return false; 5154 } 5155 final boolean isWebUri = hasWebURI(intent); 5156 if (!isWebUri || intent.getData().getHost() == null) { 5157 return false; 5158 } 5159 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5160 synchronized (mPackages) { 5161 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5162 for (int n = 0; n < count; n++) { 5163 ResolveInfo info = resolvedActivities.get(n); 5164 String packageName = info.activityInfo.packageName; 5165 PackageSetting ps = mSettings.mPackages.get(packageName); 5166 if (ps != null) { 5167 // Try to get the status from User settings first 5168 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5169 int status = (int) (packedStatus >> 32); 5170 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5171 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5172 if (DEBUG_EPHEMERAL) { 5173 Slog.v(TAG, "DENY ephemeral apps;" 5174 + " pkg: " + packageName + ", status: " + status); 5175 } 5176 return false; 5177 } 5178 } 5179 } 5180 } 5181 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5182 return true; 5183 } 5184 5185 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5186 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5187 int userId) { 5188 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5189 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5190 callingPackage, userId)); 5191 mHandler.sendMessage(msg); 5192 } 5193 5194 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5195 int flags, List<ResolveInfo> query, int userId) { 5196 if (query != null) { 5197 final int N = query.size(); 5198 if (N == 1) { 5199 return query.get(0); 5200 } else if (N > 1) { 5201 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5202 // If there is more than one activity with the same priority, 5203 // then let the user decide between them. 5204 ResolveInfo r0 = query.get(0); 5205 ResolveInfo r1 = query.get(1); 5206 if (DEBUG_INTENT_MATCHING || debug) { 5207 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5208 + r1.activityInfo.name + "=" + r1.priority); 5209 } 5210 // If the first activity has a higher priority, or a different 5211 // default, then it is always desirable to pick it. 5212 if (r0.priority != r1.priority 5213 || r0.preferredOrder != r1.preferredOrder 5214 || r0.isDefault != r1.isDefault) { 5215 return query.get(0); 5216 } 5217 // If we have saved a preference for a preferred activity for 5218 // this Intent, use that. 5219 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5220 flags, query, r0.priority, true, false, debug, userId); 5221 if (ri != null) { 5222 return ri; 5223 } 5224 ri = new ResolveInfo(mResolveInfo); 5225 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5226 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5227 // If all of the options come from the same package, show the application's 5228 // label and icon instead of the generic resolver's. 5229 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5230 // and then throw away the ResolveInfo itself, meaning that the caller loses 5231 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5232 // a fallback for this case; we only set the target package's resources on 5233 // the ResolveInfo, not the ActivityInfo. 5234 final String intentPackage = intent.getPackage(); 5235 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5236 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5237 ri.resolvePackageName = intentPackage; 5238 if (userNeedsBadging(userId)) { 5239 ri.noResourceId = true; 5240 } else { 5241 ri.icon = appi.icon; 5242 } 5243 ri.iconResourceId = appi.icon; 5244 ri.labelRes = appi.labelRes; 5245 } 5246 ri.activityInfo.applicationInfo = new ApplicationInfo( 5247 ri.activityInfo.applicationInfo); 5248 if (userId != 0) { 5249 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5250 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5251 } 5252 // Make sure that the resolver is displayable in car mode 5253 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5254 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5255 return ri; 5256 } 5257 } 5258 return null; 5259 } 5260 5261 /** 5262 * Return true if the given list is not empty and all of its contents have 5263 * an activityInfo with the given package name. 5264 */ 5265 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5266 if (ArrayUtils.isEmpty(list)) { 5267 return false; 5268 } 5269 for (int i = 0, N = list.size(); i < N; i++) { 5270 final ResolveInfo ri = list.get(i); 5271 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5272 if (ai == null || !packageName.equals(ai.packageName)) { 5273 return false; 5274 } 5275 } 5276 return true; 5277 } 5278 5279 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5280 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5281 final int N = query.size(); 5282 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5283 .get(userId); 5284 // Get the list of persistent preferred activities that handle the intent 5285 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5286 List<PersistentPreferredActivity> pprefs = ppir != null 5287 ? ppir.queryIntent(intent, resolvedType, 5288 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5289 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5290 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5291 : null; 5292 if (pprefs != null && pprefs.size() > 0) { 5293 final int M = pprefs.size(); 5294 for (int i=0; i<M; i++) { 5295 final PersistentPreferredActivity ppa = pprefs.get(i); 5296 if (DEBUG_PREFERRED || debug) { 5297 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5298 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5299 + "\n component=" + ppa.mComponent); 5300 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5301 } 5302 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5303 flags | MATCH_DISABLED_COMPONENTS, userId); 5304 if (DEBUG_PREFERRED || debug) { 5305 Slog.v(TAG, "Found persistent preferred activity:"); 5306 if (ai != null) { 5307 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5308 } else { 5309 Slog.v(TAG, " null"); 5310 } 5311 } 5312 if (ai == null) { 5313 // This previously registered persistent preferred activity 5314 // component is no longer known. Ignore it and do NOT remove it. 5315 continue; 5316 } 5317 for (int j=0; j<N; j++) { 5318 final ResolveInfo ri = query.get(j); 5319 if (!ri.activityInfo.applicationInfo.packageName 5320 .equals(ai.applicationInfo.packageName)) { 5321 continue; 5322 } 5323 if (!ri.activityInfo.name.equals(ai.name)) { 5324 continue; 5325 } 5326 // Found a persistent preference that can handle the intent. 5327 if (DEBUG_PREFERRED || debug) { 5328 Slog.v(TAG, "Returning persistent preferred activity: " + 5329 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5330 } 5331 return ri; 5332 } 5333 } 5334 } 5335 return null; 5336 } 5337 5338 // TODO: handle preferred activities missing while user has amnesia 5339 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5340 List<ResolveInfo> query, int priority, boolean always, 5341 boolean removeMatches, boolean debug, int userId) { 5342 if (!sUserManager.exists(userId)) return null; 5343 flags = updateFlagsForResolve(flags, userId, intent); 5344 // writer 5345 synchronized (mPackages) { 5346 if (intent.getSelector() != null) { 5347 intent = intent.getSelector(); 5348 } 5349 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5350 5351 // Try to find a matching persistent preferred activity. 5352 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5353 debug, userId); 5354 5355 // If a persistent preferred activity matched, use it. 5356 if (pri != null) { 5357 return pri; 5358 } 5359 5360 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5361 // Get the list of preferred activities that handle the intent 5362 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5363 List<PreferredActivity> prefs = pir != null 5364 ? pir.queryIntent(intent, resolvedType, 5365 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5366 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5367 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5368 : null; 5369 if (prefs != null && prefs.size() > 0) { 5370 boolean changed = false; 5371 try { 5372 // First figure out how good the original match set is. 5373 // We will only allow preferred activities that came 5374 // from the same match quality. 5375 int match = 0; 5376 5377 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5378 5379 final int N = query.size(); 5380 for (int j=0; j<N; j++) { 5381 final ResolveInfo ri = query.get(j); 5382 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5383 + ": 0x" + Integer.toHexString(match)); 5384 if (ri.match > match) { 5385 match = ri.match; 5386 } 5387 } 5388 5389 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5390 + Integer.toHexString(match)); 5391 5392 match &= IntentFilter.MATCH_CATEGORY_MASK; 5393 final int M = prefs.size(); 5394 for (int i=0; i<M; i++) { 5395 final PreferredActivity pa = prefs.get(i); 5396 if (DEBUG_PREFERRED || debug) { 5397 Slog.v(TAG, "Checking PreferredActivity ds=" 5398 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5399 + "\n component=" + pa.mPref.mComponent); 5400 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5401 } 5402 if (pa.mPref.mMatch != match) { 5403 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5404 + Integer.toHexString(pa.mPref.mMatch)); 5405 continue; 5406 } 5407 // If it's not an "always" type preferred activity and that's what we're 5408 // looking for, skip it. 5409 if (always && !pa.mPref.mAlways) { 5410 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5411 continue; 5412 } 5413 final ActivityInfo ai = getActivityInfo( 5414 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5415 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5416 userId); 5417 if (DEBUG_PREFERRED || debug) { 5418 Slog.v(TAG, "Found preferred activity:"); 5419 if (ai != null) { 5420 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5421 } else { 5422 Slog.v(TAG, " null"); 5423 } 5424 } 5425 if (ai == null) { 5426 // This previously registered preferred activity 5427 // component is no longer known. Most likely an update 5428 // to the app was installed and in the new version this 5429 // component no longer exists. Clean it up by removing 5430 // it from the preferred activities list, and skip it. 5431 Slog.w(TAG, "Removing dangling preferred activity: " 5432 + pa.mPref.mComponent); 5433 pir.removeFilter(pa); 5434 changed = true; 5435 continue; 5436 } 5437 for (int j=0; j<N; j++) { 5438 final ResolveInfo ri = query.get(j); 5439 if (!ri.activityInfo.applicationInfo.packageName 5440 .equals(ai.applicationInfo.packageName)) { 5441 continue; 5442 } 5443 if (!ri.activityInfo.name.equals(ai.name)) { 5444 continue; 5445 } 5446 5447 if (removeMatches) { 5448 pir.removeFilter(pa); 5449 changed = true; 5450 if (DEBUG_PREFERRED) { 5451 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5452 } 5453 break; 5454 } 5455 5456 // Okay we found a previously set preferred or last chosen app. 5457 // If the result set is different from when this 5458 // was created, we need to clear it and re-ask the 5459 // user their preference, if we're looking for an "always" type entry. 5460 if (always && !pa.mPref.sameSet(query)) { 5461 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5462 + intent + " type " + resolvedType); 5463 if (DEBUG_PREFERRED) { 5464 Slog.v(TAG, "Removing preferred activity since set changed " 5465 + pa.mPref.mComponent); 5466 } 5467 pir.removeFilter(pa); 5468 // Re-add the filter as a "last chosen" entry (!always) 5469 PreferredActivity lastChosen = new PreferredActivity( 5470 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5471 pir.addFilter(lastChosen); 5472 changed = true; 5473 return null; 5474 } 5475 5476 // Yay! Either the set matched or we're looking for the last chosen 5477 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5478 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5479 return ri; 5480 } 5481 } 5482 } finally { 5483 if (changed) { 5484 if (DEBUG_PREFERRED) { 5485 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5486 } 5487 scheduleWritePackageRestrictionsLocked(userId); 5488 } 5489 } 5490 } 5491 } 5492 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5493 return null; 5494 } 5495 5496 /* 5497 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5498 */ 5499 @Override 5500 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5501 int targetUserId) { 5502 mContext.enforceCallingOrSelfPermission( 5503 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5504 List<CrossProfileIntentFilter> matches = 5505 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5506 if (matches != null) { 5507 int size = matches.size(); 5508 for (int i = 0; i < size; i++) { 5509 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5510 } 5511 } 5512 if (hasWebURI(intent)) { 5513 // cross-profile app linking works only towards the parent. 5514 final UserInfo parent = getProfileParent(sourceUserId); 5515 synchronized(mPackages) { 5516 int flags = updateFlagsForResolve(0, parent.id, intent); 5517 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5518 intent, resolvedType, flags, sourceUserId, parent.id); 5519 return xpDomainInfo != null; 5520 } 5521 } 5522 return false; 5523 } 5524 5525 private UserInfo getProfileParent(int userId) { 5526 final long identity = Binder.clearCallingIdentity(); 5527 try { 5528 return sUserManager.getProfileParent(userId); 5529 } finally { 5530 Binder.restoreCallingIdentity(identity); 5531 } 5532 } 5533 5534 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5535 String resolvedType, int userId) { 5536 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5537 if (resolver != null) { 5538 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5539 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5540 } 5541 return null; 5542 } 5543 5544 @Override 5545 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5546 String resolvedType, int flags, int userId) { 5547 try { 5548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5549 5550 return new ParceledListSlice<>( 5551 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5552 } finally { 5553 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5554 } 5555 } 5556 5557 /** 5558 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5559 * ephemeral, returns {@code null}. 5560 */ 5561 private String getEphemeralPackageName(int callingUid) { 5562 final int appId = UserHandle.getAppId(callingUid); 5563 synchronized (mPackages) { 5564 final Object obj = mSettings.getUserIdLPr(appId); 5565 if (obj instanceof PackageSetting) { 5566 final PackageSetting ps = (PackageSetting) obj; 5567 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5568 } 5569 } 5570 return null; 5571 } 5572 5573 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5574 String resolvedType, int flags, int userId) { 5575 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5576 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5577 flags = updateFlagsForResolve(flags, userId, intent); 5578 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5579 false /* requireFullPermission */, false /* checkShell */, 5580 "query intent activities"); 5581 ComponentName comp = intent.getComponent(); 5582 if (comp == null) { 5583 if (intent.getSelector() != null) { 5584 intent = intent.getSelector(); 5585 comp = intent.getComponent(); 5586 } 5587 } 5588 5589 if (comp != null) { 5590 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5591 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5592 if (ai != null) { 5593 // When specifying an explicit component, we prevent the activity from being 5594 // used when either 1) the calling package is normal and the activity is within 5595 // an ephemeral application or 2) the calling package is ephemeral and the 5596 // activity is not visible to ephemeral applications. 5597 boolean blockResolution = 5598 (ephemeralPkgName == null 5599 && (ai.applicationInfo.privateFlags 5600 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5601 || (ephemeralPkgName != null 5602 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5603 if (!blockResolution) { 5604 final ResolveInfo ri = new ResolveInfo(); 5605 ri.activityInfo = ai; 5606 list.add(ri); 5607 } 5608 } 5609 return list; 5610 } 5611 5612 // reader 5613 boolean sortResult = false; 5614 boolean addEphemeral = false; 5615 List<ResolveInfo> result; 5616 final String pkgName = intent.getPackage(); 5617 synchronized (mPackages) { 5618 if (pkgName == null) { 5619 List<CrossProfileIntentFilter> matchingFilters = 5620 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5621 // Check for results that need to skip the current profile. 5622 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5623 resolvedType, flags, userId); 5624 if (xpResolveInfo != null) { 5625 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5626 xpResult.add(xpResolveInfo); 5627 return filterForEphemeral( 5628 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5629 } 5630 5631 // Check for results in the current profile. 5632 result = filterIfNotSystemUser(mActivities.queryIntent( 5633 intent, resolvedType, flags, userId), userId); 5634 addEphemeral = 5635 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5636 5637 // Check for cross profile results. 5638 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5639 xpResolveInfo = queryCrossProfileIntents( 5640 matchingFilters, intent, resolvedType, flags, userId, 5641 hasNonNegativePriorityResult); 5642 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5643 boolean isVisibleToUser = filterIfNotSystemUser( 5644 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5645 if (isVisibleToUser) { 5646 result.add(xpResolveInfo); 5647 sortResult = true; 5648 } 5649 } 5650 if (hasWebURI(intent)) { 5651 CrossProfileDomainInfo xpDomainInfo = null; 5652 final UserInfo parent = getProfileParent(userId); 5653 if (parent != null) { 5654 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5655 flags, userId, parent.id); 5656 } 5657 if (xpDomainInfo != null) { 5658 if (xpResolveInfo != null) { 5659 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5660 // in the result. 5661 result.remove(xpResolveInfo); 5662 } 5663 if (result.size() == 0 && !addEphemeral) { 5664 // No result in current profile, but found candidate in parent user. 5665 // And we are not going to add emphemeral app, so we can return the 5666 // result straight away. 5667 result.add(xpDomainInfo.resolveInfo); 5668 return filterForEphemeral(result, ephemeralPkgName); 5669 } 5670 } else if (result.size() <= 1 && !addEphemeral) { 5671 // No result in parent user and <= 1 result in current profile, and we 5672 // are not going to add emphemeral app, so we can return the result without 5673 // further processing. 5674 return filterForEphemeral(result, ephemeralPkgName); 5675 } 5676 // We have more than one candidate (combining results from current and parent 5677 // profile), so we need filtering and sorting. 5678 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5679 intent, flags, result, xpDomainInfo, userId); 5680 sortResult = true; 5681 } 5682 } else { 5683 final PackageParser.Package pkg = mPackages.get(pkgName); 5684 if (pkg != null) { 5685 result = filterForEphemeral(filterIfNotSystemUser( 5686 mActivities.queryIntentForPackage( 5687 intent, resolvedType, flags, pkg.activities, userId), 5688 userId), ephemeralPkgName); 5689 } else { 5690 // the caller wants to resolve for a particular package; however, there 5691 // were no installed results, so, try to find an ephemeral result 5692 addEphemeral = isEphemeralAllowed( 5693 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5694 result = new ArrayList<ResolveInfo>(); 5695 } 5696 } 5697 } 5698 if (addEphemeral) { 5699 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5700 final EphemeralRequest requestObject = new EphemeralRequest( 5701 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5702 null /*launchIntent*/, null /*callingPackage*/, userId); 5703 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5704 mContext, mEphemeralResolverConnection, requestObject); 5705 if (intentInfo != null) { 5706 if (DEBUG_EPHEMERAL) { 5707 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5708 } 5709 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5710 ephemeralInstaller.ephemeralResponse = intentInfo; 5711 // make sure this resolver is the default 5712 ephemeralInstaller.isDefault = true; 5713 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5714 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5715 // add a non-generic filter 5716 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5717 ephemeralInstaller.filter.addDataPath( 5718 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5719 result.add(ephemeralInstaller); 5720 } 5721 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5722 } 5723 if (sortResult) { 5724 Collections.sort(result, mResolvePrioritySorter); 5725 } 5726 return filterForEphemeral(result, ephemeralPkgName); 5727 } 5728 5729 private static class CrossProfileDomainInfo { 5730 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5731 ResolveInfo resolveInfo; 5732 /* Best domain verification status of the activities found in the other profile */ 5733 int bestDomainVerificationStatus; 5734 } 5735 5736 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5737 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5738 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5739 sourceUserId)) { 5740 return null; 5741 } 5742 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5743 resolvedType, flags, parentUserId); 5744 5745 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5746 return null; 5747 } 5748 CrossProfileDomainInfo result = null; 5749 int size = resultTargetUser.size(); 5750 for (int i = 0; i < size; i++) { 5751 ResolveInfo riTargetUser = resultTargetUser.get(i); 5752 // Intent filter verification is only for filters that specify a host. So don't return 5753 // those that handle all web uris. 5754 if (riTargetUser.handleAllWebDataURI) { 5755 continue; 5756 } 5757 String packageName = riTargetUser.activityInfo.packageName; 5758 PackageSetting ps = mSettings.mPackages.get(packageName); 5759 if (ps == null) { 5760 continue; 5761 } 5762 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5763 int status = (int)(verificationState >> 32); 5764 if (result == null) { 5765 result = new CrossProfileDomainInfo(); 5766 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5767 sourceUserId, parentUserId); 5768 result.bestDomainVerificationStatus = status; 5769 } else { 5770 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5771 result.bestDomainVerificationStatus); 5772 } 5773 } 5774 // Don't consider matches with status NEVER across profiles. 5775 if (result != null && result.bestDomainVerificationStatus 5776 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5777 return null; 5778 } 5779 return result; 5780 } 5781 5782 /** 5783 * Verification statuses are ordered from the worse to the best, except for 5784 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5785 */ 5786 private int bestDomainVerificationStatus(int status1, int status2) { 5787 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5788 return status2; 5789 } 5790 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5791 return status1; 5792 } 5793 return (int) MathUtils.max(status1, status2); 5794 } 5795 5796 private boolean isUserEnabled(int userId) { 5797 long callingId = Binder.clearCallingIdentity(); 5798 try { 5799 UserInfo userInfo = sUserManager.getUserInfo(userId); 5800 return userInfo != null && userInfo.isEnabled(); 5801 } finally { 5802 Binder.restoreCallingIdentity(callingId); 5803 } 5804 } 5805 5806 /** 5807 * Filter out activities with systemUserOnly flag set, when current user is not System. 5808 * 5809 * @return filtered list 5810 */ 5811 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5812 if (userId == UserHandle.USER_SYSTEM) { 5813 return resolveInfos; 5814 } 5815 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5816 ResolveInfo info = resolveInfos.get(i); 5817 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5818 resolveInfos.remove(i); 5819 } 5820 } 5821 return resolveInfos; 5822 } 5823 5824 /** 5825 * Filters out ephemeral activities. 5826 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 5827 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 5828 * 5829 * @param resolveInfos The pre-filtered list of resolved activities 5830 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 5831 * is performed. 5832 * @return A filtered list of resolved activities. 5833 */ 5834 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 5835 String ephemeralPkgName) { 5836 if (ephemeralPkgName == null) { 5837 return resolveInfos; 5838 } 5839 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5840 ResolveInfo info = resolveInfos.get(i); 5841 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 5842 // allow activities that are defined in the provided package 5843 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 5844 continue; 5845 } 5846 // allow activities that have been explicitly exposed to ephemeral apps 5847 if (!isEphemeralApp 5848 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 5849 continue; 5850 } 5851 resolveInfos.remove(i); 5852 } 5853 return resolveInfos; 5854 } 5855 5856 /** 5857 * @param resolveInfos list of resolve infos in descending priority order 5858 * @return if the list contains a resolve info with non-negative priority 5859 */ 5860 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5861 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5862 } 5863 5864 private static boolean hasWebURI(Intent intent) { 5865 if (intent.getData() == null) { 5866 return false; 5867 } 5868 final String scheme = intent.getScheme(); 5869 if (TextUtils.isEmpty(scheme)) { 5870 return false; 5871 } 5872 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5873 } 5874 5875 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5876 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5877 int userId) { 5878 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5879 5880 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5881 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5882 candidates.size()); 5883 } 5884 5885 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5886 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5887 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5888 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5889 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5890 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5891 5892 synchronized (mPackages) { 5893 final int count = candidates.size(); 5894 // First, try to use linked apps. Partition the candidates into four lists: 5895 // one for the final results, one for the "do not use ever", one for "undefined status" 5896 // and finally one for "browser app type". 5897 for (int n=0; n<count; n++) { 5898 ResolveInfo info = candidates.get(n); 5899 String packageName = info.activityInfo.packageName; 5900 PackageSetting ps = mSettings.mPackages.get(packageName); 5901 if (ps != null) { 5902 // Add to the special match all list (Browser use case) 5903 if (info.handleAllWebDataURI) { 5904 matchAllList.add(info); 5905 continue; 5906 } 5907 // Try to get the status from User settings first 5908 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5909 int status = (int)(packedStatus >> 32); 5910 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5911 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5912 if (DEBUG_DOMAIN_VERIFICATION) { 5913 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5914 + " : linkgen=" + linkGeneration); 5915 } 5916 // Use link-enabled generation as preferredOrder, i.e. 5917 // prefer newly-enabled over earlier-enabled. 5918 info.preferredOrder = linkGeneration; 5919 alwaysList.add(info); 5920 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5921 if (DEBUG_DOMAIN_VERIFICATION) { 5922 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5923 } 5924 neverList.add(info); 5925 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5926 if (DEBUG_DOMAIN_VERIFICATION) { 5927 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5928 } 5929 alwaysAskList.add(info); 5930 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5931 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5932 if (DEBUG_DOMAIN_VERIFICATION) { 5933 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5934 } 5935 undefinedList.add(info); 5936 } 5937 } 5938 } 5939 5940 // We'll want to include browser possibilities in a few cases 5941 boolean includeBrowser = false; 5942 5943 // First try to add the "always" resolution(s) for the current user, if any 5944 if (alwaysList.size() > 0) { 5945 result.addAll(alwaysList); 5946 } else { 5947 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5948 result.addAll(undefinedList); 5949 // Maybe add one for the other profile. 5950 if (xpDomainInfo != null && ( 5951 xpDomainInfo.bestDomainVerificationStatus 5952 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5953 result.add(xpDomainInfo.resolveInfo); 5954 } 5955 includeBrowser = true; 5956 } 5957 5958 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5959 // If there were 'always' entries their preferred order has been set, so we also 5960 // back that off to make the alternatives equivalent 5961 if (alwaysAskList.size() > 0) { 5962 for (ResolveInfo i : result) { 5963 i.preferredOrder = 0; 5964 } 5965 result.addAll(alwaysAskList); 5966 includeBrowser = true; 5967 } 5968 5969 if (includeBrowser) { 5970 // Also add browsers (all of them or only the default one) 5971 if (DEBUG_DOMAIN_VERIFICATION) { 5972 Slog.v(TAG, " ...including browsers in candidate set"); 5973 } 5974 if ((matchFlags & MATCH_ALL) != 0) { 5975 result.addAll(matchAllList); 5976 } else { 5977 // Browser/generic handling case. If there's a default browser, go straight 5978 // to that (but only if there is no other higher-priority match). 5979 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5980 int maxMatchPrio = 0; 5981 ResolveInfo defaultBrowserMatch = null; 5982 final int numCandidates = matchAllList.size(); 5983 for (int n = 0; n < numCandidates; n++) { 5984 ResolveInfo info = matchAllList.get(n); 5985 // track the highest overall match priority... 5986 if (info.priority > maxMatchPrio) { 5987 maxMatchPrio = info.priority; 5988 } 5989 // ...and the highest-priority default browser match 5990 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5991 if (defaultBrowserMatch == null 5992 || (defaultBrowserMatch.priority < info.priority)) { 5993 if (debug) { 5994 Slog.v(TAG, "Considering default browser match " + info); 5995 } 5996 defaultBrowserMatch = info; 5997 } 5998 } 5999 } 6000 if (defaultBrowserMatch != null 6001 && defaultBrowserMatch.priority >= maxMatchPrio 6002 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6003 { 6004 if (debug) { 6005 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6006 } 6007 result.add(defaultBrowserMatch); 6008 } else { 6009 result.addAll(matchAllList); 6010 } 6011 } 6012 6013 // If there is nothing selected, add all candidates and remove the ones that the user 6014 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6015 if (result.size() == 0) { 6016 result.addAll(candidates); 6017 result.removeAll(neverList); 6018 } 6019 } 6020 } 6021 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6022 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6023 result.size()); 6024 for (ResolveInfo info : result) { 6025 Slog.v(TAG, " + " + info.activityInfo); 6026 } 6027 } 6028 return result; 6029 } 6030 6031 // Returns a packed value as a long: 6032 // 6033 // high 'int'-sized word: link status: undefined/ask/never/always. 6034 // low 'int'-sized word: relative priority among 'always' results. 6035 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6036 long result = ps.getDomainVerificationStatusForUser(userId); 6037 // if none available, get the master status 6038 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6039 if (ps.getIntentFilterVerificationInfo() != null) { 6040 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6041 } 6042 } 6043 return result; 6044 } 6045 6046 private ResolveInfo querySkipCurrentProfileIntents( 6047 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6048 int flags, int sourceUserId) { 6049 if (matchingFilters != null) { 6050 int size = matchingFilters.size(); 6051 for (int i = 0; i < size; i ++) { 6052 CrossProfileIntentFilter filter = matchingFilters.get(i); 6053 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6054 // Checking if there are activities in the target user that can handle the 6055 // intent. 6056 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6057 resolvedType, flags, sourceUserId); 6058 if (resolveInfo != null) { 6059 return resolveInfo; 6060 } 6061 } 6062 } 6063 } 6064 return null; 6065 } 6066 6067 // Return matching ResolveInfo in target user if any. 6068 private ResolveInfo queryCrossProfileIntents( 6069 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6070 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6071 if (matchingFilters != null) { 6072 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6073 // match the same intent. For performance reasons, it is better not to 6074 // run queryIntent twice for the same userId 6075 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6076 int size = matchingFilters.size(); 6077 for (int i = 0; i < size; i++) { 6078 CrossProfileIntentFilter filter = matchingFilters.get(i); 6079 int targetUserId = filter.getTargetUserId(); 6080 boolean skipCurrentProfile = 6081 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6082 boolean skipCurrentProfileIfNoMatchFound = 6083 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6084 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6085 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6086 // Checking if there are activities in the target user that can handle the 6087 // intent. 6088 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6089 resolvedType, flags, sourceUserId); 6090 if (resolveInfo != null) return resolveInfo; 6091 alreadyTriedUserIds.put(targetUserId, true); 6092 } 6093 } 6094 } 6095 return null; 6096 } 6097 6098 /** 6099 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6100 * will forward the intent to the filter's target user. 6101 * Otherwise, returns null. 6102 */ 6103 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6104 String resolvedType, int flags, int sourceUserId) { 6105 int targetUserId = filter.getTargetUserId(); 6106 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6107 resolvedType, flags, targetUserId); 6108 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6109 // If all the matches in the target profile are suspended, return null. 6110 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6111 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6112 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6113 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6114 targetUserId); 6115 } 6116 } 6117 } 6118 return null; 6119 } 6120 6121 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6122 int sourceUserId, int targetUserId) { 6123 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6124 long ident = Binder.clearCallingIdentity(); 6125 boolean targetIsProfile; 6126 try { 6127 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6128 } finally { 6129 Binder.restoreCallingIdentity(ident); 6130 } 6131 String className; 6132 if (targetIsProfile) { 6133 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6134 } else { 6135 className = FORWARD_INTENT_TO_PARENT; 6136 } 6137 ComponentName forwardingActivityComponentName = new ComponentName( 6138 mAndroidApplication.packageName, className); 6139 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6140 sourceUserId); 6141 if (!targetIsProfile) { 6142 forwardingActivityInfo.showUserIcon = targetUserId; 6143 forwardingResolveInfo.noResourceId = true; 6144 } 6145 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6146 forwardingResolveInfo.priority = 0; 6147 forwardingResolveInfo.preferredOrder = 0; 6148 forwardingResolveInfo.match = 0; 6149 forwardingResolveInfo.isDefault = true; 6150 forwardingResolveInfo.filter = filter; 6151 forwardingResolveInfo.targetUserId = targetUserId; 6152 return forwardingResolveInfo; 6153 } 6154 6155 @Override 6156 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6157 Intent[] specifics, String[] specificTypes, Intent intent, 6158 String resolvedType, int flags, int userId) { 6159 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6160 specificTypes, intent, resolvedType, flags, userId)); 6161 } 6162 6163 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6164 Intent[] specifics, String[] specificTypes, Intent intent, 6165 String resolvedType, int flags, int userId) { 6166 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6167 flags = updateFlagsForResolve(flags, userId, intent); 6168 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6169 false /* requireFullPermission */, false /* checkShell */, 6170 "query intent activity options"); 6171 final String resultsAction = intent.getAction(); 6172 6173 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6174 | PackageManager.GET_RESOLVED_FILTER, userId); 6175 6176 if (DEBUG_INTENT_MATCHING) { 6177 Log.v(TAG, "Query " + intent + ": " + results); 6178 } 6179 6180 int specificsPos = 0; 6181 int N; 6182 6183 // todo: note that the algorithm used here is O(N^2). This 6184 // isn't a problem in our current environment, but if we start running 6185 // into situations where we have more than 5 or 10 matches then this 6186 // should probably be changed to something smarter... 6187 6188 // First we go through and resolve each of the specific items 6189 // that were supplied, taking care of removing any corresponding 6190 // duplicate items in the generic resolve list. 6191 if (specifics != null) { 6192 for (int i=0; i<specifics.length; i++) { 6193 final Intent sintent = specifics[i]; 6194 if (sintent == null) { 6195 continue; 6196 } 6197 6198 if (DEBUG_INTENT_MATCHING) { 6199 Log.v(TAG, "Specific #" + i + ": " + sintent); 6200 } 6201 6202 String action = sintent.getAction(); 6203 if (resultsAction != null && resultsAction.equals(action)) { 6204 // If this action was explicitly requested, then don't 6205 // remove things that have it. 6206 action = null; 6207 } 6208 6209 ResolveInfo ri = null; 6210 ActivityInfo ai = null; 6211 6212 ComponentName comp = sintent.getComponent(); 6213 if (comp == null) { 6214 ri = resolveIntent( 6215 sintent, 6216 specificTypes != null ? specificTypes[i] : null, 6217 flags, userId); 6218 if (ri == null) { 6219 continue; 6220 } 6221 if (ri == mResolveInfo) { 6222 // ACK! Must do something better with this. 6223 } 6224 ai = ri.activityInfo; 6225 comp = new ComponentName(ai.applicationInfo.packageName, 6226 ai.name); 6227 } else { 6228 ai = getActivityInfo(comp, flags, userId); 6229 if (ai == null) { 6230 continue; 6231 } 6232 } 6233 6234 // Look for any generic query activities that are duplicates 6235 // of this specific one, and remove them from the results. 6236 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6237 N = results.size(); 6238 int j; 6239 for (j=specificsPos; j<N; j++) { 6240 ResolveInfo sri = results.get(j); 6241 if ((sri.activityInfo.name.equals(comp.getClassName()) 6242 && sri.activityInfo.applicationInfo.packageName.equals( 6243 comp.getPackageName())) 6244 || (action != null && sri.filter.matchAction(action))) { 6245 results.remove(j); 6246 if (DEBUG_INTENT_MATCHING) Log.v( 6247 TAG, "Removing duplicate item from " + j 6248 + " due to specific " + specificsPos); 6249 if (ri == null) { 6250 ri = sri; 6251 } 6252 j--; 6253 N--; 6254 } 6255 } 6256 6257 // Add this specific item to its proper place. 6258 if (ri == null) { 6259 ri = new ResolveInfo(); 6260 ri.activityInfo = ai; 6261 } 6262 results.add(specificsPos, ri); 6263 ri.specificIndex = i; 6264 specificsPos++; 6265 } 6266 } 6267 6268 // Now we go through the remaining generic results and remove any 6269 // duplicate actions that are found here. 6270 N = results.size(); 6271 for (int i=specificsPos; i<N-1; i++) { 6272 final ResolveInfo rii = results.get(i); 6273 if (rii.filter == null) { 6274 continue; 6275 } 6276 6277 // Iterate over all of the actions of this result's intent 6278 // filter... typically this should be just one. 6279 final Iterator<String> it = rii.filter.actionsIterator(); 6280 if (it == null) { 6281 continue; 6282 } 6283 while (it.hasNext()) { 6284 final String action = it.next(); 6285 if (resultsAction != null && resultsAction.equals(action)) { 6286 // If this action was explicitly requested, then don't 6287 // remove things that have it. 6288 continue; 6289 } 6290 for (int j=i+1; j<N; j++) { 6291 final ResolveInfo rij = results.get(j); 6292 if (rij.filter != null && rij.filter.hasAction(action)) { 6293 results.remove(j); 6294 if (DEBUG_INTENT_MATCHING) Log.v( 6295 TAG, "Removing duplicate item from " + j 6296 + " due to action " + action + " at " + i); 6297 j--; 6298 N--; 6299 } 6300 } 6301 } 6302 6303 // If the caller didn't request filter information, drop it now 6304 // so we don't have to marshall/unmarshall it. 6305 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6306 rii.filter = null; 6307 } 6308 } 6309 6310 // Filter out the caller activity if so requested. 6311 if (caller != null) { 6312 N = results.size(); 6313 for (int i=0; i<N; i++) { 6314 ActivityInfo ainfo = results.get(i).activityInfo; 6315 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6316 && caller.getClassName().equals(ainfo.name)) { 6317 results.remove(i); 6318 break; 6319 } 6320 } 6321 } 6322 6323 // If the caller didn't request filter information, 6324 // drop them now so we don't have to 6325 // marshall/unmarshall it. 6326 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6327 N = results.size(); 6328 for (int i=0; i<N; i++) { 6329 results.get(i).filter = null; 6330 } 6331 } 6332 6333 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6334 return results; 6335 } 6336 6337 @Override 6338 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6339 String resolvedType, int flags, int userId) { 6340 return new ParceledListSlice<>( 6341 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6342 } 6343 6344 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6345 String resolvedType, int flags, int userId) { 6346 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6347 flags = updateFlagsForResolve(flags, userId, intent); 6348 ComponentName comp = intent.getComponent(); 6349 if (comp == null) { 6350 if (intent.getSelector() != null) { 6351 intent = intent.getSelector(); 6352 comp = intent.getComponent(); 6353 } 6354 } 6355 if (comp != null) { 6356 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6357 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6358 if (ai != null) { 6359 ResolveInfo ri = new ResolveInfo(); 6360 ri.activityInfo = ai; 6361 list.add(ri); 6362 } 6363 return list; 6364 } 6365 6366 // reader 6367 synchronized (mPackages) { 6368 String pkgName = intent.getPackage(); 6369 if (pkgName == null) { 6370 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6371 } 6372 final PackageParser.Package pkg = mPackages.get(pkgName); 6373 if (pkg != null) { 6374 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6375 userId); 6376 } 6377 return Collections.emptyList(); 6378 } 6379 } 6380 6381 @Override 6382 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6383 if (!sUserManager.exists(userId)) return null; 6384 flags = updateFlagsForResolve(flags, userId, intent); 6385 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6386 if (query != null) { 6387 if (query.size() >= 1) { 6388 // If there is more than one service with the same priority, 6389 // just arbitrarily pick the first one. 6390 return query.get(0); 6391 } 6392 } 6393 return null; 6394 } 6395 6396 @Override 6397 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6398 String resolvedType, int flags, int userId) { 6399 return new ParceledListSlice<>( 6400 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6401 } 6402 6403 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6404 String resolvedType, int flags, int userId) { 6405 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6406 flags = updateFlagsForResolve(flags, userId, intent); 6407 ComponentName comp = intent.getComponent(); 6408 if (comp == null) { 6409 if (intent.getSelector() != null) { 6410 intent = intent.getSelector(); 6411 comp = intent.getComponent(); 6412 } 6413 } 6414 if (comp != null) { 6415 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6416 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6417 if (si != null) { 6418 final ResolveInfo ri = new ResolveInfo(); 6419 ri.serviceInfo = si; 6420 list.add(ri); 6421 } 6422 return list; 6423 } 6424 6425 // reader 6426 synchronized (mPackages) { 6427 String pkgName = intent.getPackage(); 6428 if (pkgName == null) { 6429 return mServices.queryIntent(intent, resolvedType, flags, userId); 6430 } 6431 final PackageParser.Package pkg = mPackages.get(pkgName); 6432 if (pkg != null) { 6433 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6434 userId); 6435 } 6436 return Collections.emptyList(); 6437 } 6438 } 6439 6440 @Override 6441 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6442 String resolvedType, int flags, int userId) { 6443 return new ParceledListSlice<>( 6444 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6445 } 6446 6447 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6448 Intent intent, String resolvedType, int flags, int userId) { 6449 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6450 flags = updateFlagsForResolve(flags, userId, intent); 6451 ComponentName comp = intent.getComponent(); 6452 if (comp == null) { 6453 if (intent.getSelector() != null) { 6454 intent = intent.getSelector(); 6455 comp = intent.getComponent(); 6456 } 6457 } 6458 if (comp != null) { 6459 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6460 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6461 if (pi != null) { 6462 final ResolveInfo ri = new ResolveInfo(); 6463 ri.providerInfo = pi; 6464 list.add(ri); 6465 } 6466 return list; 6467 } 6468 6469 // reader 6470 synchronized (mPackages) { 6471 String pkgName = intent.getPackage(); 6472 if (pkgName == null) { 6473 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6474 } 6475 final PackageParser.Package pkg = mPackages.get(pkgName); 6476 if (pkg != null) { 6477 return mProviders.queryIntentForPackage( 6478 intent, resolvedType, flags, pkg.providers, userId); 6479 } 6480 return Collections.emptyList(); 6481 } 6482 } 6483 6484 @Override 6485 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6486 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6487 flags = updateFlagsForPackage(flags, userId, null); 6488 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6489 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6490 true /* requireFullPermission */, false /* checkShell */, 6491 "get installed packages"); 6492 6493 // writer 6494 synchronized (mPackages) { 6495 ArrayList<PackageInfo> list; 6496 if (listUninstalled) { 6497 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6498 for (PackageSetting ps : mSettings.mPackages.values()) { 6499 final PackageInfo pi; 6500 if (ps.pkg != null) { 6501 pi = generatePackageInfo(ps, flags, userId); 6502 } else { 6503 pi = generatePackageInfo(ps, flags, userId); 6504 } 6505 if (pi != null) { 6506 list.add(pi); 6507 } 6508 } 6509 } else { 6510 list = new ArrayList<PackageInfo>(mPackages.size()); 6511 for (PackageParser.Package p : mPackages.values()) { 6512 final PackageInfo pi = 6513 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6514 if (pi != null) { 6515 list.add(pi); 6516 } 6517 } 6518 } 6519 6520 return new ParceledListSlice<PackageInfo>(list); 6521 } 6522 } 6523 6524 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6525 String[] permissions, boolean[] tmp, int flags, int userId) { 6526 int numMatch = 0; 6527 final PermissionsState permissionsState = ps.getPermissionsState(); 6528 for (int i=0; i<permissions.length; i++) { 6529 final String permission = permissions[i]; 6530 if (permissionsState.hasPermission(permission, userId)) { 6531 tmp[i] = true; 6532 numMatch++; 6533 } else { 6534 tmp[i] = false; 6535 } 6536 } 6537 if (numMatch == 0) { 6538 return; 6539 } 6540 final PackageInfo pi; 6541 if (ps.pkg != null) { 6542 pi = generatePackageInfo(ps, flags, userId); 6543 } else { 6544 pi = generatePackageInfo(ps, flags, userId); 6545 } 6546 // The above might return null in cases of uninstalled apps or install-state 6547 // skew across users/profiles. 6548 if (pi != null) { 6549 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6550 if (numMatch == permissions.length) { 6551 pi.requestedPermissions = permissions; 6552 } else { 6553 pi.requestedPermissions = new String[numMatch]; 6554 numMatch = 0; 6555 for (int i=0; i<permissions.length; i++) { 6556 if (tmp[i]) { 6557 pi.requestedPermissions[numMatch] = permissions[i]; 6558 numMatch++; 6559 } 6560 } 6561 } 6562 } 6563 list.add(pi); 6564 } 6565 } 6566 6567 @Override 6568 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6569 String[] permissions, int flags, int userId) { 6570 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6571 flags = updateFlagsForPackage(flags, userId, permissions); 6572 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6573 true /* requireFullPermission */, false /* checkShell */, 6574 "get packages holding permissions"); 6575 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6576 6577 // writer 6578 synchronized (mPackages) { 6579 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6580 boolean[] tmpBools = new boolean[permissions.length]; 6581 if (listUninstalled) { 6582 for (PackageSetting ps : mSettings.mPackages.values()) { 6583 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6584 userId); 6585 } 6586 } else { 6587 for (PackageParser.Package pkg : mPackages.values()) { 6588 PackageSetting ps = (PackageSetting)pkg.mExtras; 6589 if (ps != null) { 6590 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6591 userId); 6592 } 6593 } 6594 } 6595 6596 return new ParceledListSlice<PackageInfo>(list); 6597 } 6598 } 6599 6600 @Override 6601 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6602 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6603 flags = updateFlagsForApplication(flags, userId, null); 6604 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6605 6606 // writer 6607 synchronized (mPackages) { 6608 ArrayList<ApplicationInfo> list; 6609 if (listUninstalled) { 6610 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6611 for (PackageSetting ps : mSettings.mPackages.values()) { 6612 ApplicationInfo ai; 6613 int effectiveFlags = flags; 6614 if (ps.isSystem()) { 6615 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6616 } 6617 if (ps.pkg != null) { 6618 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6619 ps.readUserState(userId), userId); 6620 } else { 6621 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6622 userId); 6623 } 6624 if (ai != null) { 6625 list.add(ai); 6626 } 6627 } 6628 } else { 6629 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6630 for (PackageParser.Package p : mPackages.values()) { 6631 if (p.mExtras != null) { 6632 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6633 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6634 if (ai != null) { 6635 list.add(ai); 6636 } 6637 } 6638 } 6639 } 6640 6641 return new ParceledListSlice<ApplicationInfo>(list); 6642 } 6643 } 6644 6645 @Override 6646 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6647 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6648 return null; 6649 } 6650 6651 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6652 "getEphemeralApplications"); 6653 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6654 true /* requireFullPermission */, false /* checkShell */, 6655 "getEphemeralApplications"); 6656 synchronized (mPackages) { 6657 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6658 .getEphemeralApplicationsLPw(userId); 6659 if (ephemeralApps != null) { 6660 return new ParceledListSlice<>(ephemeralApps); 6661 } 6662 } 6663 return null; 6664 } 6665 6666 @Override 6667 public boolean isEphemeralApplication(String packageName, int userId) { 6668 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6669 true /* requireFullPermission */, false /* checkShell */, 6670 "isEphemeral"); 6671 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6672 return false; 6673 } 6674 6675 if (!isCallerSameApp(packageName)) { 6676 return false; 6677 } 6678 synchronized (mPackages) { 6679 PackageParser.Package pkg = mPackages.get(packageName); 6680 if (pkg != null) { 6681 return pkg.applicationInfo.isEphemeralApp(); 6682 } 6683 } 6684 return false; 6685 } 6686 6687 @Override 6688 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6689 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6690 return null; 6691 } 6692 6693 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6694 true /* requireFullPermission */, false /* checkShell */, 6695 "getCookie"); 6696 if (!isCallerSameApp(packageName)) { 6697 return null; 6698 } 6699 synchronized (mPackages) { 6700 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6701 packageName, userId); 6702 } 6703 } 6704 6705 @Override 6706 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6707 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6708 return true; 6709 } 6710 6711 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6712 true /* requireFullPermission */, true /* checkShell */, 6713 "setCookie"); 6714 if (!isCallerSameApp(packageName)) { 6715 return false; 6716 } 6717 synchronized (mPackages) { 6718 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6719 packageName, cookie, userId); 6720 } 6721 } 6722 6723 @Override 6724 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6725 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6726 return null; 6727 } 6728 6729 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6730 "getEphemeralApplicationIcon"); 6731 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6732 true /* requireFullPermission */, false /* checkShell */, 6733 "getEphemeralApplicationIcon"); 6734 synchronized (mPackages) { 6735 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6736 packageName, userId); 6737 } 6738 } 6739 6740 private boolean isCallerSameApp(String packageName) { 6741 PackageParser.Package pkg = mPackages.get(packageName); 6742 return pkg != null 6743 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6744 } 6745 6746 @Override 6747 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6748 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6749 } 6750 6751 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6752 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6753 6754 // reader 6755 synchronized (mPackages) { 6756 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6757 final int userId = UserHandle.getCallingUserId(); 6758 while (i.hasNext()) { 6759 final PackageParser.Package p = i.next(); 6760 if (p.applicationInfo == null) continue; 6761 6762 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6763 && !p.applicationInfo.isDirectBootAware(); 6764 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6765 && p.applicationInfo.isDirectBootAware(); 6766 6767 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6768 && (!mSafeMode || isSystemApp(p)) 6769 && (matchesUnaware || matchesAware)) { 6770 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6771 if (ps != null) { 6772 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6773 ps.readUserState(userId), userId); 6774 if (ai != null) { 6775 finalList.add(ai); 6776 } 6777 } 6778 } 6779 } 6780 } 6781 6782 return finalList; 6783 } 6784 6785 @Override 6786 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6787 if (!sUserManager.exists(userId)) return null; 6788 flags = updateFlagsForComponent(flags, userId, name); 6789 // reader 6790 synchronized (mPackages) { 6791 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6792 PackageSetting ps = provider != null 6793 ? mSettings.mPackages.get(provider.owner.packageName) 6794 : null; 6795 return ps != null 6796 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6797 ? PackageParser.generateProviderInfo(provider, flags, 6798 ps.readUserState(userId), userId) 6799 : null; 6800 } 6801 } 6802 6803 /** 6804 * @deprecated 6805 */ 6806 @Deprecated 6807 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6808 // reader 6809 synchronized (mPackages) { 6810 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6811 .entrySet().iterator(); 6812 final int userId = UserHandle.getCallingUserId(); 6813 while (i.hasNext()) { 6814 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6815 PackageParser.Provider p = entry.getValue(); 6816 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6817 6818 if (ps != null && p.syncable 6819 && (!mSafeMode || (p.info.applicationInfo.flags 6820 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6821 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6822 ps.readUserState(userId), userId); 6823 if (info != null) { 6824 outNames.add(entry.getKey()); 6825 outInfo.add(info); 6826 } 6827 } 6828 } 6829 } 6830 } 6831 6832 @Override 6833 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6834 int uid, int flags) { 6835 final int userId = processName != null ? UserHandle.getUserId(uid) 6836 : UserHandle.getCallingUserId(); 6837 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6838 flags = updateFlagsForComponent(flags, userId, processName); 6839 6840 ArrayList<ProviderInfo> finalList = null; 6841 // reader 6842 synchronized (mPackages) { 6843 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6844 while (i.hasNext()) { 6845 final PackageParser.Provider p = i.next(); 6846 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6847 if (ps != null && p.info.authority != null 6848 && (processName == null 6849 || (p.info.processName.equals(processName) 6850 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6851 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6852 if (finalList == null) { 6853 finalList = new ArrayList<ProviderInfo>(3); 6854 } 6855 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6856 ps.readUserState(userId), userId); 6857 if (info != null) { 6858 finalList.add(info); 6859 } 6860 } 6861 } 6862 } 6863 6864 if (finalList != null) { 6865 Collections.sort(finalList, mProviderInitOrderSorter); 6866 return new ParceledListSlice<ProviderInfo>(finalList); 6867 } 6868 6869 return ParceledListSlice.emptyList(); 6870 } 6871 6872 @Override 6873 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6874 // reader 6875 synchronized (mPackages) { 6876 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6877 return PackageParser.generateInstrumentationInfo(i, flags); 6878 } 6879 } 6880 6881 @Override 6882 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6883 String targetPackage, int flags) { 6884 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6885 } 6886 6887 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6888 int flags) { 6889 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6890 6891 // reader 6892 synchronized (mPackages) { 6893 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6894 while (i.hasNext()) { 6895 final PackageParser.Instrumentation p = i.next(); 6896 if (targetPackage == null 6897 || targetPackage.equals(p.info.targetPackage)) { 6898 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6899 flags); 6900 if (ii != null) { 6901 finalList.add(ii); 6902 } 6903 } 6904 } 6905 } 6906 6907 return finalList; 6908 } 6909 6910 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6911 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6912 if (overlays == null) { 6913 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6914 return; 6915 } 6916 for (PackageParser.Package opkg : overlays.values()) { 6917 // Not much to do if idmap fails: we already logged the error 6918 // and we certainly don't want to abort installation of pkg simply 6919 // because an overlay didn't fit properly. For these reasons, 6920 // ignore the return value of createIdmapForPackagePairLI. 6921 createIdmapForPackagePairLI(pkg, opkg); 6922 } 6923 } 6924 6925 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6926 PackageParser.Package opkg) { 6927 if (!opkg.mTrustedOverlay) { 6928 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6929 opkg.baseCodePath + ": overlay not trusted"); 6930 return false; 6931 } 6932 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6933 if (overlaySet == null) { 6934 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6935 opkg.baseCodePath + " but target package has no known overlays"); 6936 return false; 6937 } 6938 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6939 // TODO: generate idmap for split APKs 6940 try { 6941 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6942 } catch (InstallerException e) { 6943 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6944 + opkg.baseCodePath); 6945 return false; 6946 } 6947 PackageParser.Package[] overlayArray = 6948 overlaySet.values().toArray(new PackageParser.Package[0]); 6949 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6950 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6951 return p1.mOverlayPriority - p2.mOverlayPriority; 6952 } 6953 }; 6954 Arrays.sort(overlayArray, cmp); 6955 6956 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6957 int i = 0; 6958 for (PackageParser.Package p : overlayArray) { 6959 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6960 } 6961 return true; 6962 } 6963 6964 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6965 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6966 try { 6967 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6968 } finally { 6969 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6970 } 6971 } 6972 6973 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6974 final File[] files = dir.listFiles(); 6975 if (ArrayUtils.isEmpty(files)) { 6976 Log.d(TAG, "No files in app dir " + dir); 6977 return; 6978 } 6979 6980 if (DEBUG_PACKAGE_SCANNING) { 6981 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6982 + " flags=0x" + Integer.toHexString(parseFlags)); 6983 } 6984 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6985 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 6986 6987 // Submit files for parsing in parallel 6988 int fileCount = 0; 6989 for (File file : files) { 6990 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6991 && !PackageInstallerService.isStageName(file.getName()); 6992 if (!isPackage) { 6993 // Ignore entries which are not packages 6994 continue; 6995 } 6996 parallelPackageParser.submit(file, parseFlags); 6997 fileCount++; 6998 } 6999 7000 // Process results one by one 7001 for (; fileCount > 0; fileCount--) { 7002 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7003 Throwable throwable = parseResult.throwable; 7004 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7005 7006 if (throwable == null) { 7007 try { 7008 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7009 currentTime, null); 7010 } catch (PackageManagerException e) { 7011 errorCode = e.error; 7012 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7013 } 7014 } else if (throwable instanceof PackageParser.PackageParserException) { 7015 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7016 throwable; 7017 errorCode = e.error; 7018 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7019 } else { 7020 throw new IllegalStateException("Unexpected exception occurred while parsing " 7021 + parseResult.scanFile, throwable); 7022 } 7023 7024 // Delete invalid userdata apps 7025 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7026 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7027 logCriticalInfo(Log.WARN, 7028 "Deleting invalid package at " + parseResult.scanFile); 7029 removeCodePathLI(parseResult.scanFile); 7030 } 7031 } 7032 parallelPackageParser.close(); 7033 } 7034 7035 private static File getSettingsProblemFile() { 7036 File dataDir = Environment.getDataDirectory(); 7037 File systemDir = new File(dataDir, "system"); 7038 File fname = new File(systemDir, "uiderrors.txt"); 7039 return fname; 7040 } 7041 7042 static void reportSettingsProblem(int priority, String msg) { 7043 logCriticalInfo(priority, msg); 7044 } 7045 7046 static void logCriticalInfo(int priority, String msg) { 7047 Slog.println(priority, TAG, msg); 7048 EventLogTags.writePmCriticalInfo(msg); 7049 try { 7050 File fname = getSettingsProblemFile(); 7051 FileOutputStream out = new FileOutputStream(fname, true); 7052 PrintWriter pw = new FastPrintWriter(out); 7053 SimpleDateFormat formatter = new SimpleDateFormat(); 7054 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7055 pw.println(dateString + ": " + msg); 7056 pw.close(); 7057 FileUtils.setPermissions( 7058 fname.toString(), 7059 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7060 -1, -1); 7061 } catch (java.io.IOException e) { 7062 } 7063 } 7064 7065 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7066 if (srcFile.isDirectory()) { 7067 final File baseFile = new File(pkg.baseCodePath); 7068 long maxModifiedTime = baseFile.lastModified(); 7069 if (pkg.splitCodePaths != null) { 7070 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7071 final File splitFile = new File(pkg.splitCodePaths[i]); 7072 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7073 } 7074 } 7075 return maxModifiedTime; 7076 } 7077 return srcFile.lastModified(); 7078 } 7079 7080 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7081 final int policyFlags) throws PackageManagerException { 7082 // When upgrading from pre-N MR1, verify the package time stamp using the package 7083 // directory and not the APK file. 7084 final long lastModifiedTime = mIsPreNMR1Upgrade 7085 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7086 if (ps != null 7087 && ps.codePath.equals(srcFile) 7088 && ps.timeStamp == lastModifiedTime 7089 && !isCompatSignatureUpdateNeeded(pkg) 7090 && !isRecoverSignatureUpdateNeeded(pkg)) { 7091 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7092 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7093 ArraySet<PublicKey> signingKs; 7094 synchronized (mPackages) { 7095 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7096 } 7097 if (ps.signatures.mSignatures != null 7098 && ps.signatures.mSignatures.length != 0 7099 && signingKs != null) { 7100 // Optimization: reuse the existing cached certificates 7101 // if the package appears to be unchanged. 7102 pkg.mSignatures = ps.signatures.mSignatures; 7103 pkg.mSigningKeys = signingKs; 7104 return; 7105 } 7106 7107 Slog.w(TAG, "PackageSetting for " + ps.name 7108 + " is missing signatures. Collecting certs again to recover them."); 7109 } else { 7110 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7111 } 7112 7113 try { 7114 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7115 PackageParser.collectCertificates(pkg, policyFlags); 7116 } catch (PackageParserException e) { 7117 throw PackageManagerException.from(e); 7118 } finally { 7119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7120 } 7121 } 7122 7123 /** 7124 * Traces a package scan. 7125 * @see #scanPackageLI(File, int, int, long, UserHandle) 7126 */ 7127 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7128 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7129 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7130 try { 7131 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7132 } finally { 7133 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7134 } 7135 } 7136 7137 /** 7138 * Scans a package and returns the newly parsed package. 7139 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7140 */ 7141 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7142 long currentTime, UserHandle user) throws PackageManagerException { 7143 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7144 PackageParser pp = new PackageParser(); 7145 pp.setSeparateProcesses(mSeparateProcesses); 7146 pp.setOnlyCoreApps(mOnlyCore); 7147 pp.setDisplayMetrics(mMetrics); 7148 7149 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7150 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7151 } 7152 7153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7154 final PackageParser.Package pkg; 7155 try { 7156 pkg = pp.parsePackage(scanFile, parseFlags); 7157 } catch (PackageParserException e) { 7158 throw PackageManagerException.from(e); 7159 } finally { 7160 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7161 } 7162 7163 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7164 } 7165 7166 /** 7167 * Scans a package and returns the newly parsed package. 7168 * @throws PackageManagerException on a parse error. 7169 */ 7170 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7171 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7172 throws PackageManagerException { 7173 // If the package has children and this is the first dive in the function 7174 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7175 // packages (parent and children) would be successfully scanned before the 7176 // actual scan since scanning mutates internal state and we want to atomically 7177 // install the package and its children. 7178 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7179 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7180 scanFlags |= SCAN_CHECK_ONLY; 7181 } 7182 } else { 7183 scanFlags &= ~SCAN_CHECK_ONLY; 7184 } 7185 7186 // Scan the parent 7187 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7188 scanFlags, currentTime, user); 7189 7190 // Scan the children 7191 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7192 for (int i = 0; i < childCount; i++) { 7193 PackageParser.Package childPackage = pkg.childPackages.get(i); 7194 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7195 currentTime, user); 7196 } 7197 7198 7199 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7200 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7201 } 7202 7203 return scannedPkg; 7204 } 7205 7206 /** 7207 * Scans a package and returns the newly parsed package. 7208 * @throws PackageManagerException on a parse error. 7209 */ 7210 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7211 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7212 throws PackageManagerException { 7213 PackageSetting ps = null; 7214 PackageSetting updatedPkg; 7215 // reader 7216 synchronized (mPackages) { 7217 // Look to see if we already know about this package. 7218 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7219 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7220 // This package has been renamed to its original name. Let's 7221 // use that. 7222 ps = mSettings.getPackageLPr(oldName); 7223 } 7224 // If there was no original package, see one for the real package name. 7225 if (ps == null) { 7226 ps = mSettings.getPackageLPr(pkg.packageName); 7227 } 7228 // Check to see if this package could be hiding/updating a system 7229 // package. Must look for it either under the original or real 7230 // package name depending on our state. 7231 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7232 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7233 7234 // If this is a package we don't know about on the system partition, we 7235 // may need to remove disabled child packages on the system partition 7236 // or may need to not add child packages if the parent apk is updated 7237 // on the data partition and no longer defines this child package. 7238 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7239 // If this is a parent package for an updated system app and this system 7240 // app got an OTA update which no longer defines some of the child packages 7241 // we have to prune them from the disabled system packages. 7242 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7243 if (disabledPs != null) { 7244 final int scannedChildCount = (pkg.childPackages != null) 7245 ? pkg.childPackages.size() : 0; 7246 final int disabledChildCount = disabledPs.childPackageNames != null 7247 ? disabledPs.childPackageNames.size() : 0; 7248 for (int i = 0; i < disabledChildCount; i++) { 7249 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7250 boolean disabledPackageAvailable = false; 7251 for (int j = 0; j < scannedChildCount; j++) { 7252 PackageParser.Package childPkg = pkg.childPackages.get(j); 7253 if (childPkg.packageName.equals(disabledChildPackageName)) { 7254 disabledPackageAvailable = true; 7255 break; 7256 } 7257 } 7258 if (!disabledPackageAvailable) { 7259 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7260 } 7261 } 7262 } 7263 } 7264 } 7265 7266 boolean updatedPkgBetter = false; 7267 // First check if this is a system package that may involve an update 7268 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7269 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7270 // it needs to drop FLAG_PRIVILEGED. 7271 if (locationIsPrivileged(scanFile)) { 7272 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7273 } else { 7274 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7275 } 7276 7277 if (ps != null && !ps.codePath.equals(scanFile)) { 7278 // The path has changed from what was last scanned... check the 7279 // version of the new path against what we have stored to determine 7280 // what to do. 7281 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7282 if (pkg.mVersionCode <= ps.versionCode) { 7283 // The system package has been updated and the code path does not match 7284 // Ignore entry. Skip it. 7285 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7286 + " ignored: updated version " + ps.versionCode 7287 + " better than this " + pkg.mVersionCode); 7288 if (!updatedPkg.codePath.equals(scanFile)) { 7289 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7290 + ps.name + " changing from " + updatedPkg.codePathString 7291 + " to " + scanFile); 7292 updatedPkg.codePath = scanFile; 7293 updatedPkg.codePathString = scanFile.toString(); 7294 updatedPkg.resourcePath = scanFile; 7295 updatedPkg.resourcePathString = scanFile.toString(); 7296 } 7297 updatedPkg.pkg = pkg; 7298 updatedPkg.versionCode = pkg.mVersionCode; 7299 7300 // Update the disabled system child packages to point to the package too. 7301 final int childCount = updatedPkg.childPackageNames != null 7302 ? updatedPkg.childPackageNames.size() : 0; 7303 for (int i = 0; i < childCount; i++) { 7304 String childPackageName = updatedPkg.childPackageNames.get(i); 7305 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7306 childPackageName); 7307 if (updatedChildPkg != null) { 7308 updatedChildPkg.pkg = pkg; 7309 updatedChildPkg.versionCode = pkg.mVersionCode; 7310 } 7311 } 7312 7313 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7314 + scanFile + " ignored: updated version " + ps.versionCode 7315 + " better than this " + pkg.mVersionCode); 7316 } else { 7317 // The current app on the system partition is better than 7318 // what we have updated to on the data partition; switch 7319 // back to the system partition version. 7320 // At this point, its safely assumed that package installation for 7321 // apps in system partition will go through. If not there won't be a working 7322 // version of the app 7323 // writer 7324 synchronized (mPackages) { 7325 // Just remove the loaded entries from package lists. 7326 mPackages.remove(ps.name); 7327 } 7328 7329 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7330 + " reverting from " + ps.codePathString 7331 + ": new version " + pkg.mVersionCode 7332 + " better than installed " + ps.versionCode); 7333 7334 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7335 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7336 synchronized (mInstallLock) { 7337 args.cleanUpResourcesLI(); 7338 } 7339 synchronized (mPackages) { 7340 mSettings.enableSystemPackageLPw(ps.name); 7341 } 7342 updatedPkgBetter = true; 7343 } 7344 } 7345 } 7346 7347 if (updatedPkg != null) { 7348 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7349 // initially 7350 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7351 7352 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7353 // flag set initially 7354 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7355 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7356 } 7357 } 7358 7359 // Verify certificates against what was last scanned 7360 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7361 7362 /* 7363 * A new system app appeared, but we already had a non-system one of the 7364 * same name installed earlier. 7365 */ 7366 boolean shouldHideSystemApp = false; 7367 if (updatedPkg == null && ps != null 7368 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7369 /* 7370 * Check to make sure the signatures match first. If they don't, 7371 * wipe the installed application and its data. 7372 */ 7373 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7374 != PackageManager.SIGNATURE_MATCH) { 7375 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7376 + " signatures don't match existing userdata copy; removing"); 7377 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7378 "scanPackageInternalLI")) { 7379 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7380 } 7381 ps = null; 7382 } else { 7383 /* 7384 * If the newly-added system app is an older version than the 7385 * already installed version, hide it. It will be scanned later 7386 * and re-added like an update. 7387 */ 7388 if (pkg.mVersionCode <= ps.versionCode) { 7389 shouldHideSystemApp = true; 7390 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7391 + " but new version " + pkg.mVersionCode + " better than installed " 7392 + ps.versionCode + "; hiding system"); 7393 } else { 7394 /* 7395 * The newly found system app is a newer version that the 7396 * one previously installed. Simply remove the 7397 * already-installed application and replace it with our own 7398 * while keeping the application data. 7399 */ 7400 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7401 + " reverting from " + ps.codePathString + ": new version " 7402 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7403 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7404 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7405 synchronized (mInstallLock) { 7406 args.cleanUpResourcesLI(); 7407 } 7408 } 7409 } 7410 } 7411 7412 // The apk is forward locked (not public) if its code and resources 7413 // are kept in different files. (except for app in either system or 7414 // vendor path). 7415 // TODO grab this value from PackageSettings 7416 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7417 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7418 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7419 } 7420 } 7421 7422 // TODO: extend to support forward-locked splits 7423 String resourcePath = null; 7424 String baseResourcePath = null; 7425 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7426 if (ps != null && ps.resourcePathString != null) { 7427 resourcePath = ps.resourcePathString; 7428 baseResourcePath = ps.resourcePathString; 7429 } else { 7430 // Should not happen at all. Just log an error. 7431 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7432 } 7433 } else { 7434 resourcePath = pkg.codePath; 7435 baseResourcePath = pkg.baseCodePath; 7436 } 7437 7438 // Set application objects path explicitly. 7439 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7440 pkg.setApplicationInfoCodePath(pkg.codePath); 7441 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7442 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7443 pkg.setApplicationInfoResourcePath(resourcePath); 7444 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7445 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7446 7447 // Note that we invoke the following method only if we are about to unpack an application 7448 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7449 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7450 7451 /* 7452 * If the system app should be overridden by a previously installed 7453 * data, hide the system app now and let the /data/app scan pick it up 7454 * again. 7455 */ 7456 if (shouldHideSystemApp) { 7457 synchronized (mPackages) { 7458 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7459 } 7460 } 7461 7462 return scannedPkg; 7463 } 7464 7465 private static String fixProcessName(String defProcessName, 7466 String processName) { 7467 if (processName == null) { 7468 return defProcessName; 7469 } 7470 return processName; 7471 } 7472 7473 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7474 throws PackageManagerException { 7475 if (pkgSetting.signatures.mSignatures != null) { 7476 // Already existing package. Make sure signatures match 7477 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7478 == PackageManager.SIGNATURE_MATCH; 7479 if (!match) { 7480 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7481 == PackageManager.SIGNATURE_MATCH; 7482 } 7483 if (!match) { 7484 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7485 == PackageManager.SIGNATURE_MATCH; 7486 } 7487 if (!match) { 7488 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7489 + pkg.packageName + " signatures do not match the " 7490 + "previously installed version; ignoring!"); 7491 } 7492 } 7493 7494 // Check for shared user signatures 7495 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7496 // Already existing package. Make sure signatures match 7497 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7498 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7499 if (!match) { 7500 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7501 == PackageManager.SIGNATURE_MATCH; 7502 } 7503 if (!match) { 7504 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7505 == PackageManager.SIGNATURE_MATCH; 7506 } 7507 if (!match) { 7508 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7509 "Package " + pkg.packageName 7510 + " has no signatures that match those in shared user " 7511 + pkgSetting.sharedUser.name + "; ignoring!"); 7512 } 7513 } 7514 } 7515 7516 /** 7517 * Enforces that only the system UID or root's UID can call a method exposed 7518 * via Binder. 7519 * 7520 * @param message used as message if SecurityException is thrown 7521 * @throws SecurityException if the caller is not system or root 7522 */ 7523 private static final void enforceSystemOrRoot(String message) { 7524 final int uid = Binder.getCallingUid(); 7525 if (uid != Process.SYSTEM_UID && uid != 0) { 7526 throw new SecurityException(message); 7527 } 7528 } 7529 7530 @Override 7531 public void performFstrimIfNeeded() { 7532 enforceSystemOrRoot("Only the system can request fstrim"); 7533 7534 // Before everything else, see whether we need to fstrim. 7535 try { 7536 IStorageManager sm = PackageHelper.getStorageManager(); 7537 if (sm != null) { 7538 boolean doTrim = false; 7539 final long interval = android.provider.Settings.Global.getLong( 7540 mContext.getContentResolver(), 7541 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7542 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7543 if (interval > 0) { 7544 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7545 if (timeSinceLast > interval) { 7546 doTrim = true; 7547 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7548 + "; running immediately"); 7549 } 7550 } 7551 if (doTrim) { 7552 final boolean dexOptDialogShown; 7553 synchronized (mPackages) { 7554 dexOptDialogShown = mDexOptDialogShown; 7555 } 7556 if (!isFirstBoot() && dexOptDialogShown) { 7557 try { 7558 ActivityManager.getService().showBootMessage( 7559 mContext.getResources().getString( 7560 R.string.android_upgrading_fstrim), true); 7561 } catch (RemoteException e) { 7562 } 7563 } 7564 sm.runMaintenance(); 7565 } 7566 } else { 7567 Slog.e(TAG, "storageManager service unavailable!"); 7568 } 7569 } catch (RemoteException e) { 7570 // Can't happen; StorageManagerService is local 7571 } 7572 } 7573 7574 @Override 7575 public void updatePackagesIfNeeded() { 7576 enforceSystemOrRoot("Only the system can request package update"); 7577 7578 // We need to re-extract after an OTA. 7579 boolean causeUpgrade = isUpgrade(); 7580 7581 // First boot or factory reset. 7582 // Note: we also handle devices that are upgrading to N right now as if it is their 7583 // first boot, as they do not have profile data. 7584 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7585 7586 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7587 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7588 7589 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7590 return; 7591 } 7592 7593 List<PackageParser.Package> pkgs; 7594 synchronized (mPackages) { 7595 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7596 } 7597 7598 final long startTime = System.nanoTime(); 7599 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7600 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7601 7602 final int elapsedTimeSeconds = 7603 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7604 7605 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7606 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7607 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7608 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7609 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7610 } 7611 7612 /** 7613 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7614 * containing statistics about the invocation. The array consists of three elements, 7615 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7616 * and {@code numberOfPackagesFailed}. 7617 */ 7618 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7619 String compilerFilter) { 7620 7621 int numberOfPackagesVisited = 0; 7622 int numberOfPackagesOptimized = 0; 7623 int numberOfPackagesSkipped = 0; 7624 int numberOfPackagesFailed = 0; 7625 final int numberOfPackagesToDexopt = pkgs.size(); 7626 7627 for (PackageParser.Package pkg : pkgs) { 7628 numberOfPackagesVisited++; 7629 7630 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7631 if (DEBUG_DEXOPT) { 7632 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7633 } 7634 numberOfPackagesSkipped++; 7635 continue; 7636 } 7637 7638 if (DEBUG_DEXOPT) { 7639 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7640 numberOfPackagesToDexopt + ": " + pkg.packageName); 7641 } 7642 7643 if (showDialog) { 7644 try { 7645 ActivityManager.getService().showBootMessage( 7646 mContext.getResources().getString(R.string.android_upgrading_apk, 7647 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7648 } catch (RemoteException e) { 7649 } 7650 synchronized (mPackages) { 7651 mDexOptDialogShown = true; 7652 } 7653 } 7654 7655 // If the OTA updates a system app which was previously preopted to a non-preopted state 7656 // the app might end up being verified at runtime. That's because by default the apps 7657 // are verify-profile but for preopted apps there's no profile. 7658 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7659 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7660 // filter (by default interpret-only). 7661 // Note that at this stage unused apps are already filtered. 7662 if (isSystemApp(pkg) && 7663 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7664 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7665 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7666 } 7667 7668 // checkProfiles is false to avoid merging profiles during boot which 7669 // might interfere with background compilation (b/28612421). 7670 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7671 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7672 // trade-off worth doing to save boot time work. 7673 int dexOptStatus = performDexOptTraced(pkg.packageName, 7674 false /* checkProfiles */, 7675 compilerFilter, 7676 false /* force */); 7677 switch (dexOptStatus) { 7678 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7679 numberOfPackagesOptimized++; 7680 break; 7681 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7682 numberOfPackagesSkipped++; 7683 break; 7684 case PackageDexOptimizer.DEX_OPT_FAILED: 7685 numberOfPackagesFailed++; 7686 break; 7687 default: 7688 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7689 break; 7690 } 7691 } 7692 7693 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7694 numberOfPackagesFailed }; 7695 } 7696 7697 @Override 7698 public void notifyPackageUse(String packageName, int reason) { 7699 synchronized (mPackages) { 7700 PackageParser.Package p = mPackages.get(packageName); 7701 if (p == null) { 7702 return; 7703 } 7704 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7705 } 7706 } 7707 7708 @Override 7709 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7710 int userId = UserHandle.getCallingUserId(); 7711 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7712 if (ai == null) { 7713 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7714 + loadingPackageName + ", user=" + userId); 7715 return; 7716 } 7717 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7718 } 7719 7720 // TODO: this is not used nor needed. Delete it. 7721 @Override 7722 public boolean performDexOptIfNeeded(String packageName) { 7723 int dexOptStatus = performDexOptTraced(packageName, 7724 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7725 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7726 } 7727 7728 @Override 7729 public boolean performDexOpt(String packageName, 7730 boolean checkProfiles, int compileReason, boolean force) { 7731 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7732 getCompilerFilterForReason(compileReason), force); 7733 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7734 } 7735 7736 @Override 7737 public boolean performDexOptMode(String packageName, 7738 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7739 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7740 targetCompilerFilter, force); 7741 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7742 } 7743 7744 private int performDexOptTraced(String packageName, 7745 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7746 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7747 try { 7748 return performDexOptInternal(packageName, checkProfiles, 7749 targetCompilerFilter, force); 7750 } finally { 7751 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7752 } 7753 } 7754 7755 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7756 // if the package can now be considered up to date for the given filter. 7757 private int performDexOptInternal(String packageName, 7758 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7759 PackageParser.Package p; 7760 synchronized (mPackages) { 7761 p = mPackages.get(packageName); 7762 if (p == null) { 7763 // Package could not be found. Report failure. 7764 return PackageDexOptimizer.DEX_OPT_FAILED; 7765 } 7766 mPackageUsage.maybeWriteAsync(mPackages); 7767 mCompilerStats.maybeWriteAsync(); 7768 } 7769 long callingId = Binder.clearCallingIdentity(); 7770 try { 7771 synchronized (mInstallLock) { 7772 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7773 targetCompilerFilter, force); 7774 } 7775 } finally { 7776 Binder.restoreCallingIdentity(callingId); 7777 } 7778 } 7779 7780 public ArraySet<String> getOptimizablePackages() { 7781 ArraySet<String> pkgs = new ArraySet<String>(); 7782 synchronized (mPackages) { 7783 for (PackageParser.Package p : mPackages.values()) { 7784 if (PackageDexOptimizer.canOptimizePackage(p)) { 7785 pkgs.add(p.packageName); 7786 } 7787 } 7788 } 7789 return pkgs; 7790 } 7791 7792 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7793 boolean checkProfiles, String targetCompilerFilter, 7794 boolean force) { 7795 // Select the dex optimizer based on the force parameter. 7796 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7797 // allocate an object here. 7798 PackageDexOptimizer pdo = force 7799 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7800 : mPackageDexOptimizer; 7801 7802 // Optimize all dependencies first. Note: we ignore the return value and march on 7803 // on errors. 7804 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7805 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7806 if (!deps.isEmpty()) { 7807 for (PackageParser.Package depPackage : deps) { 7808 // TODO: Analyze and investigate if we (should) profile libraries. 7809 // Currently this will do a full compilation of the library by default. 7810 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7811 false /* checkProfiles */, 7812 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7813 getOrCreateCompilerPackageStats(depPackage)); 7814 } 7815 } 7816 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7817 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7818 } 7819 7820 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7821 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7822 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7823 Set<String> collectedNames = new HashSet<>(); 7824 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7825 7826 retValue.remove(p); 7827 7828 return retValue; 7829 } else { 7830 return Collections.emptyList(); 7831 } 7832 } 7833 7834 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7835 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7836 if (!collectedNames.contains(p.packageName)) { 7837 collectedNames.add(p.packageName); 7838 collected.add(p); 7839 7840 if (p.usesLibraries != null) { 7841 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7842 } 7843 if (p.usesOptionalLibraries != null) { 7844 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7845 collectedNames); 7846 } 7847 } 7848 } 7849 7850 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7851 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7852 for (String libName : libs) { 7853 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7854 if (libPkg != null) { 7855 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7856 } 7857 } 7858 } 7859 7860 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7861 synchronized (mPackages) { 7862 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7863 if (lib != null && lib.apk != null) { 7864 return mPackages.get(lib.apk); 7865 } 7866 } 7867 return null; 7868 } 7869 7870 public void shutdown() { 7871 mPackageUsage.writeNow(mPackages); 7872 mCompilerStats.writeNow(); 7873 } 7874 7875 @Override 7876 public void dumpProfiles(String packageName) { 7877 PackageParser.Package pkg; 7878 synchronized (mPackages) { 7879 pkg = mPackages.get(packageName); 7880 if (pkg == null) { 7881 throw new IllegalArgumentException("Unknown package: " + packageName); 7882 } 7883 } 7884 /* Only the shell, root, or the app user should be able to dump profiles. */ 7885 int callingUid = Binder.getCallingUid(); 7886 if (callingUid != Process.SHELL_UID && 7887 callingUid != Process.ROOT_UID && 7888 callingUid != pkg.applicationInfo.uid) { 7889 throw new SecurityException("dumpProfiles"); 7890 } 7891 7892 synchronized (mInstallLock) { 7893 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7894 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7895 try { 7896 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7897 String codePaths = TextUtils.join(";", allCodePaths); 7898 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7899 } catch (InstallerException e) { 7900 Slog.w(TAG, "Failed to dump profiles", e); 7901 } 7902 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7903 } 7904 } 7905 7906 @Override 7907 public void forceDexOpt(String packageName) { 7908 enforceSystemOrRoot("forceDexOpt"); 7909 7910 PackageParser.Package pkg; 7911 synchronized (mPackages) { 7912 pkg = mPackages.get(packageName); 7913 if (pkg == null) { 7914 throw new IllegalArgumentException("Unknown package: " + packageName); 7915 } 7916 } 7917 7918 synchronized (mInstallLock) { 7919 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7920 7921 // Whoever is calling forceDexOpt wants a fully compiled package. 7922 // Don't use profiles since that may cause compilation to be skipped. 7923 final int res = performDexOptInternalWithDependenciesLI(pkg, 7924 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7925 true /* force */); 7926 7927 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7928 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7929 throw new IllegalStateException("Failed to dexopt: " + res); 7930 } 7931 } 7932 } 7933 7934 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7935 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7936 Slog.w(TAG, "Unable to update from " + oldPkg.name 7937 + " to " + newPkg.packageName 7938 + ": old package not in system partition"); 7939 return false; 7940 } else if (mPackages.get(oldPkg.name) != null) { 7941 Slog.w(TAG, "Unable to update from " + oldPkg.name 7942 + " to " + newPkg.packageName 7943 + ": old package still exists"); 7944 return false; 7945 } 7946 return true; 7947 } 7948 7949 void removeCodePathLI(File codePath) { 7950 if (codePath.isDirectory()) { 7951 try { 7952 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7953 } catch (InstallerException e) { 7954 Slog.w(TAG, "Failed to remove code path", e); 7955 } 7956 } else { 7957 codePath.delete(); 7958 } 7959 } 7960 7961 private int[] resolveUserIds(int userId) { 7962 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7963 } 7964 7965 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7966 if (pkg == null) { 7967 Slog.wtf(TAG, "Package was null!", new Throwable()); 7968 return; 7969 } 7970 clearAppDataLeafLIF(pkg, userId, flags); 7971 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7972 for (int i = 0; i < childCount; i++) { 7973 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7974 } 7975 } 7976 7977 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7978 final PackageSetting ps; 7979 synchronized (mPackages) { 7980 ps = mSettings.mPackages.get(pkg.packageName); 7981 } 7982 for (int realUserId : resolveUserIds(userId)) { 7983 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7984 try { 7985 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7986 ceDataInode); 7987 } catch (InstallerException e) { 7988 Slog.w(TAG, String.valueOf(e)); 7989 } 7990 } 7991 } 7992 7993 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7994 if (pkg == null) { 7995 Slog.wtf(TAG, "Package was null!", new Throwable()); 7996 return; 7997 } 7998 destroyAppDataLeafLIF(pkg, userId, flags); 7999 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8000 for (int i = 0; i < childCount; i++) { 8001 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8002 } 8003 } 8004 8005 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8006 final PackageSetting ps; 8007 synchronized (mPackages) { 8008 ps = mSettings.mPackages.get(pkg.packageName); 8009 } 8010 for (int realUserId : resolveUserIds(userId)) { 8011 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8012 try { 8013 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8014 ceDataInode); 8015 } catch (InstallerException e) { 8016 Slog.w(TAG, String.valueOf(e)); 8017 } 8018 } 8019 } 8020 8021 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8022 if (pkg == null) { 8023 Slog.wtf(TAG, "Package was null!", new Throwable()); 8024 return; 8025 } 8026 destroyAppProfilesLeafLIF(pkg); 8027 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8028 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8029 for (int i = 0; i < childCount; i++) { 8030 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8031 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8032 true /* removeBaseMarker */); 8033 } 8034 } 8035 8036 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8037 boolean removeBaseMarker) { 8038 if (pkg.isForwardLocked()) { 8039 return; 8040 } 8041 8042 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8043 try { 8044 path = PackageManagerServiceUtils.realpath(new File(path)); 8045 } catch (IOException e) { 8046 // TODO: Should we return early here ? 8047 Slog.w(TAG, "Failed to get canonical path", e); 8048 continue; 8049 } 8050 8051 final String useMarker = path.replace('/', '@'); 8052 for (int realUserId : resolveUserIds(userId)) { 8053 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8054 if (removeBaseMarker) { 8055 File foreignUseMark = new File(profileDir, useMarker); 8056 if (foreignUseMark.exists()) { 8057 if (!foreignUseMark.delete()) { 8058 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8059 + pkg.packageName); 8060 } 8061 } 8062 } 8063 8064 File[] markers = profileDir.listFiles(); 8065 if (markers != null) { 8066 final String searchString = "@" + pkg.packageName + "@"; 8067 // We also delete all markers that contain the package name we're 8068 // uninstalling. These are associated with secondary dex-files belonging 8069 // to the package. Reconstructing the path of these dex files is messy 8070 // in general. 8071 for (File marker : markers) { 8072 if (marker.getName().indexOf(searchString) > 0) { 8073 if (!marker.delete()) { 8074 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8075 + pkg.packageName); 8076 } 8077 } 8078 } 8079 } 8080 } 8081 } 8082 } 8083 8084 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8085 try { 8086 mInstaller.destroyAppProfiles(pkg.packageName); 8087 } catch (InstallerException e) { 8088 Slog.w(TAG, String.valueOf(e)); 8089 } 8090 } 8091 8092 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8093 if (pkg == null) { 8094 Slog.wtf(TAG, "Package was null!", new Throwable()); 8095 return; 8096 } 8097 clearAppProfilesLeafLIF(pkg); 8098 // We don't remove the base foreign use marker when clearing profiles because 8099 // we will rename it when the app is updated. Unlike the actual profile contents, 8100 // the foreign use marker is good across installs. 8101 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8102 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8103 for (int i = 0; i < childCount; i++) { 8104 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8105 } 8106 } 8107 8108 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8109 try { 8110 mInstaller.clearAppProfiles(pkg.packageName); 8111 } catch (InstallerException e) { 8112 Slog.w(TAG, String.valueOf(e)); 8113 } 8114 } 8115 8116 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8117 long lastUpdateTime) { 8118 // Set parent install/update time 8119 PackageSetting ps = (PackageSetting) pkg.mExtras; 8120 if (ps != null) { 8121 ps.firstInstallTime = firstInstallTime; 8122 ps.lastUpdateTime = lastUpdateTime; 8123 } 8124 // Set children install/update time 8125 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8126 for (int i = 0; i < childCount; i++) { 8127 PackageParser.Package childPkg = pkg.childPackages.get(i); 8128 ps = (PackageSetting) childPkg.mExtras; 8129 if (ps != null) { 8130 ps.firstInstallTime = firstInstallTime; 8131 ps.lastUpdateTime = lastUpdateTime; 8132 } 8133 } 8134 } 8135 8136 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8137 PackageParser.Package changingLib) { 8138 if (file.path != null) { 8139 usesLibraryFiles.add(file.path); 8140 return; 8141 } 8142 PackageParser.Package p = mPackages.get(file.apk); 8143 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8144 // If we are doing this while in the middle of updating a library apk, 8145 // then we need to make sure to use that new apk for determining the 8146 // dependencies here. (We haven't yet finished committing the new apk 8147 // to the package manager state.) 8148 if (p == null || p.packageName.equals(changingLib.packageName)) { 8149 p = changingLib; 8150 } 8151 } 8152 if (p != null) { 8153 usesLibraryFiles.addAll(p.getAllCodePaths()); 8154 } 8155 } 8156 8157 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8158 PackageParser.Package changingLib) throws PackageManagerException { 8159 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8160 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8161 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8162 for (int i=0; i<N; i++) { 8163 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8164 if (file == null) { 8165 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8166 "Package " + pkg.packageName + " requires unavailable shared library " 8167 + pkg.usesLibraries.get(i) + "; failing!"); 8168 } 8169 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8170 } 8171 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8172 for (int i=0; i<N; i++) { 8173 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8174 if (file == null) { 8175 Slog.w(TAG, "Package " + pkg.packageName 8176 + " desires unavailable shared library " 8177 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8178 } else { 8179 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8180 } 8181 } 8182 N = usesLibraryFiles.size(); 8183 if (N > 0) { 8184 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8185 } else { 8186 pkg.usesLibraryFiles = null; 8187 } 8188 } 8189 } 8190 8191 private static boolean hasString(List<String> list, List<String> which) { 8192 if (list == null) { 8193 return false; 8194 } 8195 for (int i=list.size()-1; i>=0; i--) { 8196 for (int j=which.size()-1; j>=0; j--) { 8197 if (which.get(j).equals(list.get(i))) { 8198 return true; 8199 } 8200 } 8201 } 8202 return false; 8203 } 8204 8205 private void updateAllSharedLibrariesLPw() { 8206 for (PackageParser.Package pkg : mPackages.values()) { 8207 try { 8208 updateSharedLibrariesLPr(pkg, null); 8209 } catch (PackageManagerException e) { 8210 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8211 } 8212 } 8213 } 8214 8215 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8216 PackageParser.Package changingPkg) { 8217 ArrayList<PackageParser.Package> res = null; 8218 for (PackageParser.Package pkg : mPackages.values()) { 8219 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8220 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8221 if (res == null) { 8222 res = new ArrayList<PackageParser.Package>(); 8223 } 8224 res.add(pkg); 8225 try { 8226 updateSharedLibrariesLPr(pkg, changingPkg); 8227 } catch (PackageManagerException e) { 8228 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8229 } 8230 } 8231 } 8232 return res; 8233 } 8234 8235 /** 8236 * Derive the value of the {@code cpuAbiOverride} based on the provided 8237 * value and an optional stored value from the package settings. 8238 */ 8239 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8240 String cpuAbiOverride = null; 8241 8242 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8243 cpuAbiOverride = null; 8244 } else if (abiOverride != null) { 8245 cpuAbiOverride = abiOverride; 8246 } else if (settings != null) { 8247 cpuAbiOverride = settings.cpuAbiOverrideString; 8248 } 8249 8250 return cpuAbiOverride; 8251 } 8252 8253 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8254 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8255 throws PackageManagerException { 8256 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8257 // If the package has children and this is the first dive in the function 8258 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8259 // whether all packages (parent and children) would be successfully scanned 8260 // before the actual scan since scanning mutates internal state and we want 8261 // to atomically install the package and its children. 8262 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8263 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8264 scanFlags |= SCAN_CHECK_ONLY; 8265 } 8266 } else { 8267 scanFlags &= ~SCAN_CHECK_ONLY; 8268 } 8269 8270 final PackageParser.Package scannedPkg; 8271 try { 8272 // Scan the parent 8273 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8274 // Scan the children 8275 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8276 for (int i = 0; i < childCount; i++) { 8277 PackageParser.Package childPkg = pkg.childPackages.get(i); 8278 scanPackageLI(childPkg, policyFlags, 8279 scanFlags, currentTime, user); 8280 } 8281 } finally { 8282 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8283 } 8284 8285 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8286 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8287 } 8288 8289 return scannedPkg; 8290 } 8291 8292 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8293 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8294 boolean success = false; 8295 try { 8296 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8297 currentTime, user); 8298 success = true; 8299 return res; 8300 } finally { 8301 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8302 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8303 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8304 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8305 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8306 } 8307 } 8308 } 8309 8310 /** 8311 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8312 */ 8313 private static boolean apkHasCode(String fileName) { 8314 StrictJarFile jarFile = null; 8315 try { 8316 jarFile = new StrictJarFile(fileName, 8317 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8318 return jarFile.findEntry("classes.dex") != null; 8319 } catch (IOException ignore) { 8320 } finally { 8321 try { 8322 if (jarFile != null) { 8323 jarFile.close(); 8324 } 8325 } catch (IOException ignore) {} 8326 } 8327 return false; 8328 } 8329 8330 /** 8331 * Enforces code policy for the package. This ensures that if an APK has 8332 * declared hasCode="true" in its manifest that the APK actually contains 8333 * code. 8334 * 8335 * @throws PackageManagerException If bytecode could not be found when it should exist 8336 */ 8337 private static void assertCodePolicy(PackageParser.Package pkg) 8338 throws PackageManagerException { 8339 final boolean shouldHaveCode = 8340 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8341 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8342 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8343 "Package " + pkg.baseCodePath + " code is missing"); 8344 } 8345 8346 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8347 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8348 final boolean splitShouldHaveCode = 8349 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8350 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8351 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8352 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8353 } 8354 } 8355 } 8356 } 8357 8358 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8359 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8360 throws PackageManagerException { 8361 if (DEBUG_PACKAGE_SCANNING) { 8362 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8363 Log.d(TAG, "Scanning package " + pkg.packageName); 8364 } 8365 8366 applyPolicy(pkg, policyFlags); 8367 8368 assertPackageIsValid(pkg, policyFlags, scanFlags); 8369 8370 // Initialize package source and resource directories 8371 final File scanFile = new File(pkg.codePath); 8372 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8373 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8374 8375 SharedUserSetting suid = null; 8376 PackageSetting pkgSetting = null; 8377 8378 // Getting the package setting may have a side-effect, so if we 8379 // are only checking if scan would succeed, stash a copy of the 8380 // old setting to restore at the end. 8381 PackageSetting nonMutatedPs = null; 8382 8383 // We keep references to the derived CPU Abis from settings in oder to reuse 8384 // them in the case where we're not upgrading or booting for the first time. 8385 String primaryCpuAbiFromSettings = null; 8386 String secondaryCpuAbiFromSettings = null; 8387 8388 // writer 8389 synchronized (mPackages) { 8390 if (pkg.mSharedUserId != null) { 8391 // SIDE EFFECTS; may potentially allocate a new shared user 8392 suid = mSettings.getSharedUserLPw( 8393 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8394 if (DEBUG_PACKAGE_SCANNING) { 8395 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8396 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8397 + "): packages=" + suid.packages); 8398 } 8399 } 8400 8401 // Check if we are renaming from an original package name. 8402 PackageSetting origPackage = null; 8403 String realName = null; 8404 if (pkg.mOriginalPackages != null) { 8405 // This package may need to be renamed to a previously 8406 // installed name. Let's check on that... 8407 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8408 if (pkg.mOriginalPackages.contains(renamed)) { 8409 // This package had originally been installed as the 8410 // original name, and we have already taken care of 8411 // transitioning to the new one. Just update the new 8412 // one to continue using the old name. 8413 realName = pkg.mRealPackage; 8414 if (!pkg.packageName.equals(renamed)) { 8415 // Callers into this function may have already taken 8416 // care of renaming the package; only do it here if 8417 // it is not already done. 8418 pkg.setPackageName(renamed); 8419 } 8420 } else { 8421 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8422 if ((origPackage = mSettings.getPackageLPr( 8423 pkg.mOriginalPackages.get(i))) != null) { 8424 // We do have the package already installed under its 8425 // original name... should we use it? 8426 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8427 // New package is not compatible with original. 8428 origPackage = null; 8429 continue; 8430 } else if (origPackage.sharedUser != null) { 8431 // Make sure uid is compatible between packages. 8432 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8433 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8434 + " to " + pkg.packageName + ": old uid " 8435 + origPackage.sharedUser.name 8436 + " differs from " + pkg.mSharedUserId); 8437 origPackage = null; 8438 continue; 8439 } 8440 // TODO: Add case when shared user id is added [b/28144775] 8441 } else { 8442 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8443 + pkg.packageName + " to old name " + origPackage.name); 8444 } 8445 break; 8446 } 8447 } 8448 } 8449 } 8450 8451 if (mTransferedPackages.contains(pkg.packageName)) { 8452 Slog.w(TAG, "Package " + pkg.packageName 8453 + " was transferred to another, but its .apk remains"); 8454 } 8455 8456 // See comments in nonMutatedPs declaration 8457 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8458 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8459 if (foundPs != null) { 8460 nonMutatedPs = new PackageSetting(foundPs); 8461 } 8462 } 8463 8464 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8465 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8466 if (foundPs != null) { 8467 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8468 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8469 } 8470 } 8471 8472 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8473 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8474 PackageManagerService.reportSettingsProblem(Log.WARN, 8475 "Package " + pkg.packageName + " shared user changed from " 8476 + (pkgSetting.sharedUser != null 8477 ? pkgSetting.sharedUser.name : "<nothing>") 8478 + " to " 8479 + (suid != null ? suid.name : "<nothing>") 8480 + "; replacing with new"); 8481 pkgSetting = null; 8482 } 8483 final PackageSetting oldPkgSetting = 8484 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8485 final PackageSetting disabledPkgSetting = 8486 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8487 if (pkgSetting == null) { 8488 final String parentPackageName = (pkg.parentPackage != null) 8489 ? pkg.parentPackage.packageName : null; 8490 // REMOVE SharedUserSetting from method; update in a separate call 8491 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8492 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8493 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8494 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8495 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8496 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8497 UserManagerService.getInstance()); 8498 // SIDE EFFECTS; updates system state; move elsewhere 8499 if (origPackage != null) { 8500 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8501 } 8502 mSettings.addUserToSettingLPw(pkgSetting); 8503 } else { 8504 // REMOVE SharedUserSetting from method; update in a separate call. 8505 // 8506 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8507 // secondaryCpuAbi are not known at this point so we always update them 8508 // to null here, only to reset them at a later point. 8509 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8510 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8511 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8512 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8513 UserManagerService.getInstance()); 8514 } 8515 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8516 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8517 8518 // SIDE EFFECTS; modifies system state; move elsewhere 8519 if (pkgSetting.origPackage != null) { 8520 // If we are first transitioning from an original package, 8521 // fix up the new package's name now. We need to do this after 8522 // looking up the package under its new name, so getPackageLP 8523 // can take care of fiddling things correctly. 8524 pkg.setPackageName(origPackage.name); 8525 8526 // File a report about this. 8527 String msg = "New package " + pkgSetting.realName 8528 + " renamed to replace old package " + pkgSetting.name; 8529 reportSettingsProblem(Log.WARN, msg); 8530 8531 // Make a note of it. 8532 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8533 mTransferedPackages.add(origPackage.name); 8534 } 8535 8536 // No longer need to retain this. 8537 pkgSetting.origPackage = null; 8538 } 8539 8540 // SIDE EFFECTS; modifies system state; move elsewhere 8541 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8542 // Make a note of it. 8543 mTransferedPackages.add(pkg.packageName); 8544 } 8545 8546 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8547 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8548 } 8549 8550 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8551 // Check all shared libraries and map to their actual file path. 8552 // We only do this here for apps not on a system dir, because those 8553 // are the only ones that can fail an install due to this. We 8554 // will take care of the system apps by updating all of their 8555 // library paths after the scan is done. 8556 updateSharedLibrariesLPr(pkg, null); 8557 } 8558 8559 if (mFoundPolicyFile) { 8560 SELinuxMMAC.assignSeinfoValue(pkg); 8561 } 8562 8563 pkg.applicationInfo.uid = pkgSetting.appId; 8564 pkg.mExtras = pkgSetting; 8565 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8566 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8567 // We just determined the app is signed correctly, so bring 8568 // over the latest parsed certs. 8569 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8570 } else { 8571 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8572 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8573 "Package " + pkg.packageName + " upgrade keys do not match the " 8574 + "previously installed version"); 8575 } else { 8576 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8577 String msg = "System package " + pkg.packageName 8578 + " signature changed; retaining data."; 8579 reportSettingsProblem(Log.WARN, msg); 8580 } 8581 } 8582 } else { 8583 try { 8584 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8585 verifySignaturesLP(pkgSetting, pkg); 8586 // We just determined the app is signed correctly, so bring 8587 // over the latest parsed certs. 8588 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8589 } catch (PackageManagerException e) { 8590 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8591 throw e; 8592 } 8593 // The signature has changed, but this package is in the system 8594 // image... let's recover! 8595 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8596 // However... if this package is part of a shared user, but it 8597 // doesn't match the signature of the shared user, let's fail. 8598 // What this means is that you can't change the signatures 8599 // associated with an overall shared user, which doesn't seem all 8600 // that unreasonable. 8601 if (pkgSetting.sharedUser != null) { 8602 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8603 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8604 throw new PackageManagerException( 8605 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8606 "Signature mismatch for shared user: " 8607 + pkgSetting.sharedUser); 8608 } 8609 } 8610 // File a report about this. 8611 String msg = "System package " + pkg.packageName 8612 + " signature changed; retaining data."; 8613 reportSettingsProblem(Log.WARN, msg); 8614 } 8615 } 8616 8617 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8618 // This package wants to adopt ownership of permissions from 8619 // another package. 8620 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8621 final String origName = pkg.mAdoptPermissions.get(i); 8622 final PackageSetting orig = mSettings.getPackageLPr(origName); 8623 if (orig != null) { 8624 if (verifyPackageUpdateLPr(orig, pkg)) { 8625 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8626 + pkg.packageName); 8627 // SIDE EFFECTS; updates permissions system state; move elsewhere 8628 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8629 } 8630 } 8631 } 8632 } 8633 } 8634 8635 pkg.applicationInfo.processName = fixProcessName( 8636 pkg.applicationInfo.packageName, 8637 pkg.applicationInfo.processName); 8638 8639 if (pkg != mPlatformPackage) { 8640 // Get all of our default paths setup 8641 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8642 } 8643 8644 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8645 8646 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8647 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8648 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8649 derivePackageAbi( 8650 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8652 8653 // Some system apps still use directory structure for native libraries 8654 // in which case we might end up not detecting abi solely based on apk 8655 // structure. Try to detect abi based on directory structure. 8656 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8657 pkg.applicationInfo.primaryCpuAbi == null) { 8658 setBundledAppAbisAndRoots(pkg, pkgSetting); 8659 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8660 } 8661 } else { 8662 // This is not a first boot or an upgrade, don't bother deriving the 8663 // ABI during the scan. Instead, trust the value that was stored in the 8664 // package setting. 8665 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8666 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8667 8668 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8669 8670 if (DEBUG_ABI_SELECTION) { 8671 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8672 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8673 pkg.applicationInfo.secondaryCpuAbi); 8674 } 8675 } 8676 } else { 8677 if ((scanFlags & SCAN_MOVE) != 0) { 8678 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8679 // but we already have this packages package info in the PackageSetting. We just 8680 // use that and derive the native library path based on the new codepath. 8681 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8682 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8683 } 8684 8685 // Set native library paths again. For moves, the path will be updated based on the 8686 // ABIs we've determined above. For non-moves, the path will be updated based on the 8687 // ABIs we determined during compilation, but the path will depend on the final 8688 // package path (after the rename away from the stage path). 8689 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8690 } 8691 8692 // This is a special case for the "system" package, where the ABI is 8693 // dictated by the zygote configuration (and init.rc). We should keep track 8694 // of this ABI so that we can deal with "normal" applications that run under 8695 // the same UID correctly. 8696 if (mPlatformPackage == pkg) { 8697 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8698 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8699 } 8700 8701 // If there's a mismatch between the abi-override in the package setting 8702 // and the abiOverride specified for the install. Warn about this because we 8703 // would've already compiled the app without taking the package setting into 8704 // account. 8705 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8706 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8707 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8708 " for package " + pkg.packageName); 8709 } 8710 } 8711 8712 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8713 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8714 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8715 8716 // Copy the derived override back to the parsed package, so that we can 8717 // update the package settings accordingly. 8718 pkg.cpuAbiOverride = cpuAbiOverride; 8719 8720 if (DEBUG_ABI_SELECTION) { 8721 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8722 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8723 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8724 } 8725 8726 // Push the derived path down into PackageSettings so we know what to 8727 // clean up at uninstall time. 8728 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8729 8730 if (DEBUG_ABI_SELECTION) { 8731 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8732 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8733 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8734 } 8735 8736 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8737 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8738 // We don't do this here during boot because we can do it all 8739 // at once after scanning all existing packages. 8740 // 8741 // We also do this *before* we perform dexopt on this package, so that 8742 // we can avoid redundant dexopts, and also to make sure we've got the 8743 // code and package path correct. 8744 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8745 } 8746 8747 if (mFactoryTest && pkg.requestedPermissions.contains( 8748 android.Manifest.permission.FACTORY_TEST)) { 8749 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8750 } 8751 8752 if (isSystemApp(pkg)) { 8753 pkgSetting.isOrphaned = true; 8754 } 8755 8756 // Take care of first install / last update times. 8757 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8758 if (currentTime != 0) { 8759 if (pkgSetting.firstInstallTime == 0) { 8760 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8761 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8762 pkgSetting.lastUpdateTime = currentTime; 8763 } 8764 } else if (pkgSetting.firstInstallTime == 0) { 8765 // We need *something*. Take time time stamp of the file. 8766 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8767 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8768 if (scanFileTime != pkgSetting.timeStamp) { 8769 // A package on the system image has changed; consider this 8770 // to be an update. 8771 pkgSetting.lastUpdateTime = scanFileTime; 8772 } 8773 } 8774 pkgSetting.setTimeStamp(scanFileTime); 8775 8776 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8777 if (nonMutatedPs != null) { 8778 synchronized (mPackages) { 8779 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8780 } 8781 } 8782 } else { 8783 // Modify state for the given package setting 8784 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8785 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8786 } 8787 return pkg; 8788 } 8789 8790 /** 8791 * Applies policy to the parsed package based upon the given policy flags. 8792 * Ensures the package is in a good state. 8793 * <p> 8794 * Implementation detail: This method must NOT have any side effect. It would 8795 * ideally be static, but, it requires locks to read system state. 8796 */ 8797 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8798 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8799 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8800 if (pkg.applicationInfo.isDirectBootAware()) { 8801 // we're direct boot aware; set for all components 8802 for (PackageParser.Service s : pkg.services) { 8803 s.info.encryptionAware = s.info.directBootAware = true; 8804 } 8805 for (PackageParser.Provider p : pkg.providers) { 8806 p.info.encryptionAware = p.info.directBootAware = true; 8807 } 8808 for (PackageParser.Activity a : pkg.activities) { 8809 a.info.encryptionAware = a.info.directBootAware = true; 8810 } 8811 for (PackageParser.Activity r : pkg.receivers) { 8812 r.info.encryptionAware = r.info.directBootAware = true; 8813 } 8814 } 8815 } else { 8816 // Only allow system apps to be flagged as core apps. 8817 pkg.coreApp = false; 8818 // clear flags not applicable to regular apps 8819 pkg.applicationInfo.privateFlags &= 8820 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8821 pkg.applicationInfo.privateFlags &= 8822 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8823 } 8824 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8825 8826 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8827 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8828 } 8829 8830 if (!isSystemApp(pkg)) { 8831 // Only system apps can use these features. 8832 pkg.mOriginalPackages = null; 8833 pkg.mRealPackage = null; 8834 pkg.mAdoptPermissions = null; 8835 } 8836 } 8837 8838 /** 8839 * Asserts the parsed package is valid according to teh given policy. If the 8840 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8841 * <p> 8842 * Implementation detail: This method must NOT have any side effects. It would 8843 * ideally be static, but, it requires locks to read system state. 8844 * 8845 * @throws PackageManagerException If the package fails any of the validation checks 8846 */ 8847 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8848 throws PackageManagerException { 8849 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8850 assertCodePolicy(pkg); 8851 } 8852 8853 if (pkg.applicationInfo.getCodePath() == null || 8854 pkg.applicationInfo.getResourcePath() == null) { 8855 // Bail out. The resource and code paths haven't been set. 8856 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8857 "Code and resource paths haven't been set correctly"); 8858 } 8859 8860 // Make sure we're not adding any bogus keyset info 8861 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8862 ksms.assertScannedPackageValid(pkg); 8863 8864 synchronized (mPackages) { 8865 // The special "android" package can only be defined once 8866 if (pkg.packageName.equals("android")) { 8867 if (mAndroidApplication != null) { 8868 Slog.w(TAG, "*************************************************"); 8869 Slog.w(TAG, "Core android package being redefined. Skipping."); 8870 Slog.w(TAG, " codePath=" + pkg.codePath); 8871 Slog.w(TAG, "*************************************************"); 8872 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8873 "Core android package being redefined. Skipping."); 8874 } 8875 } 8876 8877 // A package name must be unique; don't allow duplicates 8878 if (mPackages.containsKey(pkg.packageName) 8879 || mSharedLibraries.containsKey(pkg.packageName)) { 8880 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8881 "Application package " + pkg.packageName 8882 + " already installed. Skipping duplicate."); 8883 } 8884 8885 // Only privileged apps and updated privileged apps can add child packages. 8886 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8887 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8888 throw new PackageManagerException("Only privileged apps can add child " 8889 + "packages. Ignoring package " + pkg.packageName); 8890 } 8891 final int childCount = pkg.childPackages.size(); 8892 for (int i = 0; i < childCount; i++) { 8893 PackageParser.Package childPkg = pkg.childPackages.get(i); 8894 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8895 childPkg.packageName)) { 8896 throw new PackageManagerException("Can't override child of " 8897 + "another disabled app. Ignoring package " + pkg.packageName); 8898 } 8899 } 8900 } 8901 8902 // If we're only installing presumed-existing packages, require that the 8903 // scanned APK is both already known and at the path previously established 8904 // for it. Previously unknown packages we pick up normally, but if we have an 8905 // a priori expectation about this package's install presence, enforce it. 8906 // With a singular exception for new system packages. When an OTA contains 8907 // a new system package, we allow the codepath to change from a system location 8908 // to the user-installed location. If we don't allow this change, any newer, 8909 // user-installed version of the application will be ignored. 8910 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8911 if (mExpectingBetter.containsKey(pkg.packageName)) { 8912 logCriticalInfo(Log.WARN, 8913 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8914 } else { 8915 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8916 if (known != null) { 8917 if (DEBUG_PACKAGE_SCANNING) { 8918 Log.d(TAG, "Examining " + pkg.codePath 8919 + " and requiring known paths " + known.codePathString 8920 + " & " + known.resourcePathString); 8921 } 8922 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8923 || !pkg.applicationInfo.getResourcePath().equals( 8924 known.resourcePathString)) { 8925 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8926 "Application package " + pkg.packageName 8927 + " found at " + pkg.applicationInfo.getCodePath() 8928 + " but expected at " + known.codePathString 8929 + "; ignoring."); 8930 } 8931 } 8932 } 8933 } 8934 8935 // Verify that this new package doesn't have any content providers 8936 // that conflict with existing packages. Only do this if the 8937 // package isn't already installed, since we don't want to break 8938 // things that are installed. 8939 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8940 final int N = pkg.providers.size(); 8941 int i; 8942 for (i=0; i<N; i++) { 8943 PackageParser.Provider p = pkg.providers.get(i); 8944 if (p.info.authority != null) { 8945 String names[] = p.info.authority.split(";"); 8946 for (int j = 0; j < names.length; j++) { 8947 if (mProvidersByAuthority.containsKey(names[j])) { 8948 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8949 final String otherPackageName = 8950 ((other != null && other.getComponentName() != null) ? 8951 other.getComponentName().getPackageName() : "?"); 8952 throw new PackageManagerException( 8953 INSTALL_FAILED_CONFLICTING_PROVIDER, 8954 "Can't install because provider name " + names[j] 8955 + " (in package " + pkg.applicationInfo.packageName 8956 + ") is already used by " + otherPackageName); 8957 } 8958 } 8959 } 8960 } 8961 } 8962 } 8963 } 8964 8965 /** 8966 * Adds a scanned package to the system. When this method is finished, the package will 8967 * be available for query, resolution, etc... 8968 */ 8969 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8970 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8971 final String pkgName = pkg.packageName; 8972 if (mCustomResolverComponentName != null && 8973 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8974 setUpCustomResolverActivity(pkg); 8975 } 8976 8977 if (pkg.packageName.equals("android")) { 8978 synchronized (mPackages) { 8979 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8980 // Set up information for our fall-back user intent resolution activity. 8981 mPlatformPackage = pkg; 8982 pkg.mVersionCode = mSdkVersion; 8983 mAndroidApplication = pkg.applicationInfo; 8984 8985 if (!mResolverReplaced) { 8986 mResolveActivity.applicationInfo = mAndroidApplication; 8987 mResolveActivity.name = ResolverActivity.class.getName(); 8988 mResolveActivity.packageName = mAndroidApplication.packageName; 8989 mResolveActivity.processName = "system:ui"; 8990 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8991 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8992 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8993 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8994 mResolveActivity.exported = true; 8995 mResolveActivity.enabled = true; 8996 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8997 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8998 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8999 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9000 | ActivityInfo.CONFIG_ORIENTATION 9001 | ActivityInfo.CONFIG_KEYBOARD 9002 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9003 mResolveInfo.activityInfo = mResolveActivity; 9004 mResolveInfo.priority = 0; 9005 mResolveInfo.preferredOrder = 0; 9006 mResolveInfo.match = 0; 9007 mResolveComponentName = new ComponentName( 9008 mAndroidApplication.packageName, mResolveActivity.name); 9009 } 9010 } 9011 } 9012 } 9013 9014 ArrayList<PackageParser.Package> clientLibPkgs = null; 9015 // writer 9016 synchronized (mPackages) { 9017 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9018 // Only system apps can add new shared libraries. 9019 if (pkg.libraryNames != null) { 9020 for (int i=0; i<pkg.libraryNames.size(); i++) { 9021 String name = pkg.libraryNames.get(i); 9022 boolean allowed = false; 9023 if (pkg.isUpdatedSystemApp()) { 9024 // New library entries can only be added through the 9025 // system image. This is important to get rid of a lot 9026 // of nasty edge cases: for example if we allowed a non- 9027 // system update of the app to add a library, then uninstalling 9028 // the update would make the library go away, and assumptions 9029 // we made such as through app install filtering would now 9030 // have allowed apps on the device which aren't compatible 9031 // with it. Better to just have the restriction here, be 9032 // conservative, and create many fewer cases that can negatively 9033 // impact the user experience. 9034 final PackageSetting sysPs = mSettings 9035 .getDisabledSystemPkgLPr(pkg.packageName); 9036 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9037 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 9038 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9039 allowed = true; 9040 break; 9041 } 9042 } 9043 } 9044 } else { 9045 allowed = true; 9046 } 9047 if (allowed) { 9048 if (!mSharedLibraries.containsKey(name)) { 9049 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 9050 } else if (!name.equals(pkg.packageName)) { 9051 Slog.w(TAG, "Package " + pkg.packageName + " library " 9052 + name + " already exists; skipping"); 9053 } 9054 } else { 9055 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9056 + name + " that is not declared on system image; skipping"); 9057 } 9058 } 9059 if ((scanFlags & SCAN_BOOTING) == 0) { 9060 // If we are not booting, we need to update any applications 9061 // that are clients of our shared library. If we are booting, 9062 // this will all be done once the scan is complete. 9063 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9064 } 9065 } 9066 } 9067 } 9068 9069 if ((scanFlags & SCAN_BOOTING) != 0) { 9070 // No apps can run during boot scan, so they don't need to be frozen 9071 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9072 // Caller asked to not kill app, so it's probably not frozen 9073 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9074 // Caller asked us to ignore frozen check for some reason; they 9075 // probably didn't know the package name 9076 } else { 9077 // We're doing major surgery on this package, so it better be frozen 9078 // right now to keep it from launching 9079 checkPackageFrozen(pkgName); 9080 } 9081 9082 // Also need to kill any apps that are dependent on the library. 9083 if (clientLibPkgs != null) { 9084 for (int i=0; i<clientLibPkgs.size(); i++) { 9085 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9086 killApplication(clientPkg.applicationInfo.packageName, 9087 clientPkg.applicationInfo.uid, "update lib"); 9088 } 9089 } 9090 9091 // writer 9092 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9093 9094 boolean createIdmapFailed = false; 9095 synchronized (mPackages) { 9096 // We don't expect installation to fail beyond this point 9097 9098 if (pkgSetting.pkg != null) { 9099 // Note that |user| might be null during the initial boot scan. If a codePath 9100 // for an app has changed during a boot scan, it's due to an app update that's 9101 // part of the system partition and marker changes must be applied to all users. 9102 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9103 final int[] userIds = resolveUserIds(userId); 9104 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9105 } 9106 9107 // Add the new setting to mSettings 9108 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9109 // Add the new setting to mPackages 9110 mPackages.put(pkg.applicationInfo.packageName, pkg); 9111 // Make sure we don't accidentally delete its data. 9112 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9113 while (iter.hasNext()) { 9114 PackageCleanItem item = iter.next(); 9115 if (pkgName.equals(item.packageName)) { 9116 iter.remove(); 9117 } 9118 } 9119 9120 // Add the package's KeySets to the global KeySetManagerService 9121 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9122 ksms.addScannedPackageLPw(pkg); 9123 9124 int N = pkg.providers.size(); 9125 StringBuilder r = null; 9126 int i; 9127 for (i=0; i<N; i++) { 9128 PackageParser.Provider p = pkg.providers.get(i); 9129 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9130 p.info.processName); 9131 mProviders.addProvider(p); 9132 p.syncable = p.info.isSyncable; 9133 if (p.info.authority != null) { 9134 String names[] = p.info.authority.split(";"); 9135 p.info.authority = null; 9136 for (int j = 0; j < names.length; j++) { 9137 if (j == 1 && p.syncable) { 9138 // We only want the first authority for a provider to possibly be 9139 // syncable, so if we already added this provider using a different 9140 // authority clear the syncable flag. We copy the provider before 9141 // changing it because the mProviders object contains a reference 9142 // to a provider that we don't want to change. 9143 // Only do this for the second authority since the resulting provider 9144 // object can be the same for all future authorities for this provider. 9145 p = new PackageParser.Provider(p); 9146 p.syncable = false; 9147 } 9148 if (!mProvidersByAuthority.containsKey(names[j])) { 9149 mProvidersByAuthority.put(names[j], p); 9150 if (p.info.authority == null) { 9151 p.info.authority = names[j]; 9152 } else { 9153 p.info.authority = p.info.authority + ";" + names[j]; 9154 } 9155 if (DEBUG_PACKAGE_SCANNING) { 9156 if (chatty) 9157 Log.d(TAG, "Registered content provider: " + names[j] 9158 + ", className = " + p.info.name + ", isSyncable = " 9159 + p.info.isSyncable); 9160 } 9161 } else { 9162 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9163 Slog.w(TAG, "Skipping provider name " + names[j] + 9164 " (in package " + pkg.applicationInfo.packageName + 9165 "): name already used by " 9166 + ((other != null && other.getComponentName() != null) 9167 ? other.getComponentName().getPackageName() : "?")); 9168 } 9169 } 9170 } 9171 if (chatty) { 9172 if (r == null) { 9173 r = new StringBuilder(256); 9174 } else { 9175 r.append(' '); 9176 } 9177 r.append(p.info.name); 9178 } 9179 } 9180 if (r != null) { 9181 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9182 } 9183 9184 N = pkg.services.size(); 9185 r = null; 9186 for (i=0; i<N; i++) { 9187 PackageParser.Service s = pkg.services.get(i); 9188 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9189 s.info.processName); 9190 mServices.addService(s); 9191 if (chatty) { 9192 if (r == null) { 9193 r = new StringBuilder(256); 9194 } else { 9195 r.append(' '); 9196 } 9197 r.append(s.info.name); 9198 } 9199 } 9200 if (r != null) { 9201 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9202 } 9203 9204 N = pkg.receivers.size(); 9205 r = null; 9206 for (i=0; i<N; i++) { 9207 PackageParser.Activity a = pkg.receivers.get(i); 9208 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9209 a.info.processName); 9210 mReceivers.addActivity(a, "receiver"); 9211 if (chatty) { 9212 if (r == null) { 9213 r = new StringBuilder(256); 9214 } else { 9215 r.append(' '); 9216 } 9217 r.append(a.info.name); 9218 } 9219 } 9220 if (r != null) { 9221 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9222 } 9223 9224 N = pkg.activities.size(); 9225 r = null; 9226 for (i=0; i<N; i++) { 9227 PackageParser.Activity a = pkg.activities.get(i); 9228 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9229 a.info.processName); 9230 mActivities.addActivity(a, "activity"); 9231 if (chatty) { 9232 if (r == null) { 9233 r = new StringBuilder(256); 9234 } else { 9235 r.append(' '); 9236 } 9237 r.append(a.info.name); 9238 } 9239 } 9240 if (r != null) { 9241 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9242 } 9243 9244 N = pkg.permissionGroups.size(); 9245 r = null; 9246 for (i=0; i<N; i++) { 9247 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9248 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9249 final String curPackageName = cur == null ? null : cur.info.packageName; 9250 // Dont allow ephemeral apps to define new permission groups. 9251 if (pkg.applicationInfo.isEphemeralApp()) { 9252 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9253 + pg.info.packageName 9254 + " ignored: ephemeral apps cannot define new permission groups."); 9255 continue; 9256 } 9257 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9258 if (cur == null || isPackageUpdate) { 9259 mPermissionGroups.put(pg.info.name, pg); 9260 if (chatty) { 9261 if (r == null) { 9262 r = new StringBuilder(256); 9263 } else { 9264 r.append(' '); 9265 } 9266 if (isPackageUpdate) { 9267 r.append("UPD:"); 9268 } 9269 r.append(pg.info.name); 9270 } 9271 } else { 9272 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9273 + pg.info.packageName + " ignored: original from " 9274 + cur.info.packageName); 9275 if (chatty) { 9276 if (r == null) { 9277 r = new StringBuilder(256); 9278 } else { 9279 r.append(' '); 9280 } 9281 r.append("DUP:"); 9282 r.append(pg.info.name); 9283 } 9284 } 9285 } 9286 if (r != null) { 9287 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9288 } 9289 9290 N = pkg.permissions.size(); 9291 r = null; 9292 for (i=0; i<N; i++) { 9293 PackageParser.Permission p = pkg.permissions.get(i); 9294 9295 // Dont allow ephemeral apps to define new permissions. 9296 if (pkg.applicationInfo.isEphemeralApp()) { 9297 Slog.w(TAG, "Permission " + p.info.name + " from package " 9298 + p.info.packageName 9299 + " ignored: ephemeral apps cannot define new permissions."); 9300 continue; 9301 } 9302 9303 // Assume by default that we did not install this permission into the system. 9304 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9305 9306 // Now that permission groups have a special meaning, we ignore permission 9307 // groups for legacy apps to prevent unexpected behavior. In particular, 9308 // permissions for one app being granted to someone just becase they happen 9309 // to be in a group defined by another app (before this had no implications). 9310 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9311 p.group = mPermissionGroups.get(p.info.group); 9312 // Warn for a permission in an unknown group. 9313 if (p.info.group != null && p.group == null) { 9314 Slog.w(TAG, "Permission " + p.info.name + " from package " 9315 + p.info.packageName + " in an unknown group " + p.info.group); 9316 } 9317 } 9318 9319 ArrayMap<String, BasePermission> permissionMap = 9320 p.tree ? mSettings.mPermissionTrees 9321 : mSettings.mPermissions; 9322 BasePermission bp = permissionMap.get(p.info.name); 9323 9324 // Allow system apps to redefine non-system permissions 9325 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9326 final boolean currentOwnerIsSystem = (bp.perm != null 9327 && isSystemApp(bp.perm.owner)); 9328 if (isSystemApp(p.owner)) { 9329 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9330 // It's a built-in permission and no owner, take ownership now 9331 bp.packageSetting = pkgSetting; 9332 bp.perm = p; 9333 bp.uid = pkg.applicationInfo.uid; 9334 bp.sourcePackage = p.info.packageName; 9335 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9336 } else if (!currentOwnerIsSystem) { 9337 String msg = "New decl " + p.owner + " of permission " 9338 + p.info.name + " is system; overriding " + bp.sourcePackage; 9339 reportSettingsProblem(Log.WARN, msg); 9340 bp = null; 9341 } 9342 } 9343 } 9344 9345 if (bp == null) { 9346 bp = new BasePermission(p.info.name, p.info.packageName, 9347 BasePermission.TYPE_NORMAL); 9348 permissionMap.put(p.info.name, bp); 9349 } 9350 9351 if (bp.perm == null) { 9352 if (bp.sourcePackage == null 9353 || bp.sourcePackage.equals(p.info.packageName)) { 9354 BasePermission tree = findPermissionTreeLP(p.info.name); 9355 if (tree == null 9356 || tree.sourcePackage.equals(p.info.packageName)) { 9357 bp.packageSetting = pkgSetting; 9358 bp.perm = p; 9359 bp.uid = pkg.applicationInfo.uid; 9360 bp.sourcePackage = p.info.packageName; 9361 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9362 if (chatty) { 9363 if (r == null) { 9364 r = new StringBuilder(256); 9365 } else { 9366 r.append(' '); 9367 } 9368 r.append(p.info.name); 9369 } 9370 } else { 9371 Slog.w(TAG, "Permission " + p.info.name + " from package " 9372 + p.info.packageName + " ignored: base tree " 9373 + tree.name + " is from package " 9374 + tree.sourcePackage); 9375 } 9376 } else { 9377 Slog.w(TAG, "Permission " + p.info.name + " from package " 9378 + p.info.packageName + " ignored: original from " 9379 + bp.sourcePackage); 9380 } 9381 } else if (chatty) { 9382 if (r == null) { 9383 r = new StringBuilder(256); 9384 } else { 9385 r.append(' '); 9386 } 9387 r.append("DUP:"); 9388 r.append(p.info.name); 9389 } 9390 if (bp.perm == p) { 9391 bp.protectionLevel = p.info.protectionLevel; 9392 } 9393 } 9394 9395 if (r != null) { 9396 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9397 } 9398 9399 N = pkg.instrumentation.size(); 9400 r = null; 9401 for (i=0; i<N; i++) { 9402 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9403 a.info.packageName = pkg.applicationInfo.packageName; 9404 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9405 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9406 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9407 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9408 a.info.dataDir = pkg.applicationInfo.dataDir; 9409 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9410 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9411 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9412 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9413 mInstrumentation.put(a.getComponentName(), a); 9414 if (chatty) { 9415 if (r == null) { 9416 r = new StringBuilder(256); 9417 } else { 9418 r.append(' '); 9419 } 9420 r.append(a.info.name); 9421 } 9422 } 9423 if (r != null) { 9424 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9425 } 9426 9427 if (pkg.protectedBroadcasts != null) { 9428 N = pkg.protectedBroadcasts.size(); 9429 for (i=0; i<N; i++) { 9430 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9431 } 9432 } 9433 9434 // Create idmap files for pairs of (packages, overlay packages). 9435 // Note: "android", ie framework-res.apk, is handled by native layers. 9436 if (pkg.mOverlayTarget != null) { 9437 // This is an overlay package. 9438 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9439 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9440 mOverlays.put(pkg.mOverlayTarget, 9441 new ArrayMap<String, PackageParser.Package>()); 9442 } 9443 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9444 map.put(pkg.packageName, pkg); 9445 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9446 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9447 createIdmapFailed = true; 9448 } 9449 } 9450 } else if (mOverlays.containsKey(pkg.packageName) && 9451 !pkg.packageName.equals("android")) { 9452 // This is a regular package, with one or more known overlay packages. 9453 createIdmapsForPackageLI(pkg); 9454 } 9455 } 9456 9457 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9458 9459 if (createIdmapFailed) { 9460 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9461 "scanPackageLI failed to createIdmap"); 9462 } 9463 } 9464 9465 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9466 PackageParser.Package update, int[] userIds) { 9467 if (existing.applicationInfo == null || update.applicationInfo == null) { 9468 // This isn't due to an app installation. 9469 return; 9470 } 9471 9472 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9473 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9474 9475 // The codePath hasn't changed, so there's nothing for us to do. 9476 if (Objects.equals(oldCodePath, newCodePath)) { 9477 return; 9478 } 9479 9480 File canonicalNewCodePath; 9481 try { 9482 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9483 } catch (IOException e) { 9484 Slog.w(TAG, "Failed to get canonical path.", e); 9485 return; 9486 } 9487 9488 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9489 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9490 // that the last component of the path (i.e, the name) doesn't need canonicalization 9491 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9492 // but may change in the future. Hopefully this function won't exist at that point. 9493 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9494 oldCodePath.getName()); 9495 9496 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9497 // with "@". 9498 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9499 if (!oldMarkerPrefix.endsWith("@")) { 9500 oldMarkerPrefix += "@"; 9501 } 9502 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9503 if (!newMarkerPrefix.endsWith("@")) { 9504 newMarkerPrefix += "@"; 9505 } 9506 9507 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9508 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9509 for (String updatedPath : updatedPaths) { 9510 String updatedPathName = new File(updatedPath).getName(); 9511 markerSuffixes.add(updatedPathName.replace('/', '@')); 9512 } 9513 9514 for (int userId : userIds) { 9515 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9516 9517 for (String markerSuffix : markerSuffixes) { 9518 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9519 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9520 if (oldForeignUseMark.exists()) { 9521 try { 9522 Os.rename(oldForeignUseMark.getAbsolutePath(), 9523 newForeignUseMark.getAbsolutePath()); 9524 } catch (ErrnoException e) { 9525 Slog.w(TAG, "Failed to rename foreign use marker", e); 9526 oldForeignUseMark.delete(); 9527 } 9528 } 9529 } 9530 } 9531 } 9532 9533 /** 9534 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9535 * is derived purely on the basis of the contents of {@code scanFile} and 9536 * {@code cpuAbiOverride}. 9537 * 9538 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9539 */ 9540 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9541 String cpuAbiOverride, boolean extractLibs, 9542 File appLib32InstallDir) 9543 throws PackageManagerException { 9544 // Give ourselves some initial paths; we'll come back for another 9545 // pass once we've determined ABI below. 9546 setNativeLibraryPaths(pkg, appLib32InstallDir); 9547 9548 // We would never need to extract libs for forward-locked and external packages, 9549 // since the container service will do it for us. We shouldn't attempt to 9550 // extract libs from system app when it was not updated. 9551 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9552 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9553 extractLibs = false; 9554 } 9555 9556 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9557 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9558 9559 NativeLibraryHelper.Handle handle = null; 9560 try { 9561 handle = NativeLibraryHelper.Handle.create(pkg); 9562 // TODO(multiArch): This can be null for apps that didn't go through the 9563 // usual installation process. We can calculate it again, like we 9564 // do during install time. 9565 // 9566 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9567 // unnecessary. 9568 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9569 9570 // Null out the abis so that they can be recalculated. 9571 pkg.applicationInfo.primaryCpuAbi = null; 9572 pkg.applicationInfo.secondaryCpuAbi = null; 9573 if (isMultiArch(pkg.applicationInfo)) { 9574 // Warn if we've set an abiOverride for multi-lib packages.. 9575 // By definition, we need to copy both 32 and 64 bit libraries for 9576 // such packages. 9577 if (pkg.cpuAbiOverride != null 9578 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9579 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9580 } 9581 9582 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9583 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9584 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9585 if (extractLibs) { 9586 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9587 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9588 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9589 useIsaSpecificSubdirs); 9590 } else { 9591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9592 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9593 } 9594 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9595 } 9596 9597 maybeThrowExceptionForMultiArchCopy( 9598 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9599 9600 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9601 if (extractLibs) { 9602 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9603 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9604 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9605 useIsaSpecificSubdirs); 9606 } else { 9607 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9608 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9609 } 9610 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9611 } 9612 9613 maybeThrowExceptionForMultiArchCopy( 9614 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9615 9616 if (abi64 >= 0) { 9617 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9618 } 9619 9620 if (abi32 >= 0) { 9621 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9622 if (abi64 >= 0) { 9623 if (pkg.use32bitAbi) { 9624 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9625 pkg.applicationInfo.primaryCpuAbi = abi; 9626 } else { 9627 pkg.applicationInfo.secondaryCpuAbi = abi; 9628 } 9629 } else { 9630 pkg.applicationInfo.primaryCpuAbi = abi; 9631 } 9632 } 9633 9634 } else { 9635 String[] abiList = (cpuAbiOverride != null) ? 9636 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9637 9638 // Enable gross and lame hacks for apps that are built with old 9639 // SDK tools. We must scan their APKs for renderscript bitcode and 9640 // not launch them if it's present. Don't bother checking on devices 9641 // that don't have 64 bit support. 9642 boolean needsRenderScriptOverride = false; 9643 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9644 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9645 abiList = Build.SUPPORTED_32_BIT_ABIS; 9646 needsRenderScriptOverride = true; 9647 } 9648 9649 final int copyRet; 9650 if (extractLibs) { 9651 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9652 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9653 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9654 } else { 9655 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9656 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9657 } 9658 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9659 9660 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9661 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9662 "Error unpackaging native libs for app, errorCode=" + copyRet); 9663 } 9664 9665 if (copyRet >= 0) { 9666 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9667 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9668 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9669 } else if (needsRenderScriptOverride) { 9670 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9671 } 9672 } 9673 } catch (IOException ioe) { 9674 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9675 } finally { 9676 IoUtils.closeQuietly(handle); 9677 } 9678 9679 // Now that we've calculated the ABIs and determined if it's an internal app, 9680 // we will go ahead and populate the nativeLibraryPath. 9681 setNativeLibraryPaths(pkg, appLib32InstallDir); 9682 } 9683 9684 /** 9685 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9686 * i.e, so that all packages can be run inside a single process if required. 9687 * 9688 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9689 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9690 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9691 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9692 * updating a package that belongs to a shared user. 9693 * 9694 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9695 * adds unnecessary complexity. 9696 */ 9697 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9698 PackageParser.Package scannedPackage) { 9699 String requiredInstructionSet = null; 9700 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9701 requiredInstructionSet = VMRuntime.getInstructionSet( 9702 scannedPackage.applicationInfo.primaryCpuAbi); 9703 } 9704 9705 PackageSetting requirer = null; 9706 for (PackageSetting ps : packagesForUser) { 9707 // If packagesForUser contains scannedPackage, we skip it. This will happen 9708 // when scannedPackage is an update of an existing package. Without this check, 9709 // we will never be able to change the ABI of any package belonging to a shared 9710 // user, even if it's compatible with other packages. 9711 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9712 if (ps.primaryCpuAbiString == null) { 9713 continue; 9714 } 9715 9716 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9717 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9718 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9719 // this but there's not much we can do. 9720 String errorMessage = "Instruction set mismatch, " 9721 + ((requirer == null) ? "[caller]" : requirer) 9722 + " requires " + requiredInstructionSet + " whereas " + ps 9723 + " requires " + instructionSet; 9724 Slog.w(TAG, errorMessage); 9725 } 9726 9727 if (requiredInstructionSet == null) { 9728 requiredInstructionSet = instructionSet; 9729 requirer = ps; 9730 } 9731 } 9732 } 9733 9734 if (requiredInstructionSet != null) { 9735 String adjustedAbi; 9736 if (requirer != null) { 9737 // requirer != null implies that either scannedPackage was null or that scannedPackage 9738 // did not require an ABI, in which case we have to adjust scannedPackage to match 9739 // the ABI of the set (which is the same as requirer's ABI) 9740 adjustedAbi = requirer.primaryCpuAbiString; 9741 if (scannedPackage != null) { 9742 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9743 } 9744 } else { 9745 // requirer == null implies that we're updating all ABIs in the set to 9746 // match scannedPackage. 9747 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9748 } 9749 9750 for (PackageSetting ps : packagesForUser) { 9751 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9752 if (ps.primaryCpuAbiString != null) { 9753 continue; 9754 } 9755 9756 ps.primaryCpuAbiString = adjustedAbi; 9757 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9758 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9759 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9760 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9761 + " (requirer=" 9762 + (requirer == null ? "null" : requirer.pkg.packageName) 9763 + ", scannedPackage=" 9764 + (scannedPackage != null ? scannedPackage.packageName : "null") 9765 + ")"); 9766 try { 9767 mInstaller.rmdex(ps.codePathString, 9768 getDexCodeInstructionSet(getPreferredInstructionSet())); 9769 } catch (InstallerException ignored) { 9770 } 9771 } 9772 } 9773 } 9774 } 9775 } 9776 9777 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9778 synchronized (mPackages) { 9779 mResolverReplaced = true; 9780 // Set up information for custom user intent resolution activity. 9781 mResolveActivity.applicationInfo = pkg.applicationInfo; 9782 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9783 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9784 mResolveActivity.processName = pkg.applicationInfo.packageName; 9785 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9786 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9787 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9788 mResolveActivity.theme = 0; 9789 mResolveActivity.exported = true; 9790 mResolveActivity.enabled = true; 9791 mResolveInfo.activityInfo = mResolveActivity; 9792 mResolveInfo.priority = 0; 9793 mResolveInfo.preferredOrder = 0; 9794 mResolveInfo.match = 0; 9795 mResolveComponentName = mCustomResolverComponentName; 9796 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9797 mResolveComponentName); 9798 } 9799 } 9800 9801 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9802 if (installerComponent == null) { 9803 if (DEBUG_EPHEMERAL) { 9804 Slog.d(TAG, "Clear ephemeral installer activity"); 9805 } 9806 mEphemeralInstallerActivity.applicationInfo = null; 9807 return; 9808 } 9809 9810 if (DEBUG_EPHEMERAL) { 9811 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9812 } 9813 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9814 // Set up information for ephemeral installer activity 9815 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9816 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9817 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9818 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9819 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9820 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9821 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9822 mEphemeralInstallerActivity.theme = 0; 9823 mEphemeralInstallerActivity.exported = true; 9824 mEphemeralInstallerActivity.enabled = true; 9825 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9826 mEphemeralInstallerInfo.priority = 0; 9827 mEphemeralInstallerInfo.preferredOrder = 1; 9828 mEphemeralInstallerInfo.isDefault = true; 9829 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9830 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9831 } 9832 9833 private static String calculateBundledApkRoot(final String codePathString) { 9834 final File codePath = new File(codePathString); 9835 final File codeRoot; 9836 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9837 codeRoot = Environment.getRootDirectory(); 9838 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9839 codeRoot = Environment.getOemDirectory(); 9840 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9841 codeRoot = Environment.getVendorDirectory(); 9842 } else { 9843 // Unrecognized code path; take its top real segment as the apk root: 9844 // e.g. /something/app/blah.apk => /something 9845 try { 9846 File f = codePath.getCanonicalFile(); 9847 File parent = f.getParentFile(); // non-null because codePath is a file 9848 File tmp; 9849 while ((tmp = parent.getParentFile()) != null) { 9850 f = parent; 9851 parent = tmp; 9852 } 9853 codeRoot = f; 9854 Slog.w(TAG, "Unrecognized code path " 9855 + codePath + " - using " + codeRoot); 9856 } catch (IOException e) { 9857 // Can't canonicalize the code path -- shenanigans? 9858 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9859 return Environment.getRootDirectory().getPath(); 9860 } 9861 } 9862 return codeRoot.getPath(); 9863 } 9864 9865 /** 9866 * Derive and set the location of native libraries for the given package, 9867 * which varies depending on where and how the package was installed. 9868 */ 9869 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9870 final ApplicationInfo info = pkg.applicationInfo; 9871 final String codePath = pkg.codePath; 9872 final File codeFile = new File(codePath); 9873 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9874 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9875 9876 info.nativeLibraryRootDir = null; 9877 info.nativeLibraryRootRequiresIsa = false; 9878 info.nativeLibraryDir = null; 9879 info.secondaryNativeLibraryDir = null; 9880 9881 if (isApkFile(codeFile)) { 9882 // Monolithic install 9883 if (bundledApp) { 9884 // If "/system/lib64/apkname" exists, assume that is the per-package 9885 // native library directory to use; otherwise use "/system/lib/apkname". 9886 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9887 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9888 getPrimaryInstructionSet(info)); 9889 9890 // This is a bundled system app so choose the path based on the ABI. 9891 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9892 // is just the default path. 9893 final String apkName = deriveCodePathName(codePath); 9894 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9895 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9896 apkName).getAbsolutePath(); 9897 9898 if (info.secondaryCpuAbi != null) { 9899 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9900 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9901 secondaryLibDir, apkName).getAbsolutePath(); 9902 } 9903 } else if (asecApp) { 9904 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9905 .getAbsolutePath(); 9906 } else { 9907 final String apkName = deriveCodePathName(codePath); 9908 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9909 .getAbsolutePath(); 9910 } 9911 9912 info.nativeLibraryRootRequiresIsa = false; 9913 info.nativeLibraryDir = info.nativeLibraryRootDir; 9914 } else { 9915 // Cluster install 9916 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9917 info.nativeLibraryRootRequiresIsa = true; 9918 9919 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9920 getPrimaryInstructionSet(info)).getAbsolutePath(); 9921 9922 if (info.secondaryCpuAbi != null) { 9923 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9924 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9925 } 9926 } 9927 } 9928 9929 /** 9930 * Calculate the abis and roots for a bundled app. These can uniquely 9931 * be determined from the contents of the system partition, i.e whether 9932 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9933 * of this information, and instead assume that the system was built 9934 * sensibly. 9935 */ 9936 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9937 PackageSetting pkgSetting) { 9938 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9939 9940 // If "/system/lib64/apkname" exists, assume that is the per-package 9941 // native library directory to use; otherwise use "/system/lib/apkname". 9942 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9943 setBundledAppAbi(pkg, apkRoot, apkName); 9944 // pkgSetting might be null during rescan following uninstall of updates 9945 // to a bundled app, so accommodate that possibility. The settings in 9946 // that case will be established later from the parsed package. 9947 // 9948 // If the settings aren't null, sync them up with what we've just derived. 9949 // note that apkRoot isn't stored in the package settings. 9950 if (pkgSetting != null) { 9951 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9952 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9953 } 9954 } 9955 9956 /** 9957 * Deduces the ABI of a bundled app and sets the relevant fields on the 9958 * parsed pkg object. 9959 * 9960 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9961 * under which system libraries are installed. 9962 * @param apkName the name of the installed package. 9963 */ 9964 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9965 final File codeFile = new File(pkg.codePath); 9966 9967 final boolean has64BitLibs; 9968 final boolean has32BitLibs; 9969 if (isApkFile(codeFile)) { 9970 // Monolithic install 9971 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9972 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9973 } else { 9974 // Cluster install 9975 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9976 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9977 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9978 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9979 has64BitLibs = (new File(rootDir, isa)).exists(); 9980 } else { 9981 has64BitLibs = false; 9982 } 9983 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9984 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9985 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9986 has32BitLibs = (new File(rootDir, isa)).exists(); 9987 } else { 9988 has32BitLibs = false; 9989 } 9990 } 9991 9992 if (has64BitLibs && !has32BitLibs) { 9993 // The package has 64 bit libs, but not 32 bit libs. Its primary 9994 // ABI should be 64 bit. We can safely assume here that the bundled 9995 // native libraries correspond to the most preferred ABI in the list. 9996 9997 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9998 pkg.applicationInfo.secondaryCpuAbi = null; 9999 } else if (has32BitLibs && !has64BitLibs) { 10000 // The package has 32 bit libs but not 64 bit libs. Its primary 10001 // ABI should be 32 bit. 10002 10003 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10004 pkg.applicationInfo.secondaryCpuAbi = null; 10005 } else if (has32BitLibs && has64BitLibs) { 10006 // The application has both 64 and 32 bit bundled libraries. We check 10007 // here that the app declares multiArch support, and warn if it doesn't. 10008 // 10009 // We will be lenient here and record both ABIs. The primary will be the 10010 // ABI that's higher on the list, i.e, a device that's configured to prefer 10011 // 64 bit apps will see a 64 bit primary ABI, 10012 10013 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10014 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10015 } 10016 10017 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10018 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10019 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10020 } else { 10021 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10022 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10023 } 10024 } else { 10025 pkg.applicationInfo.primaryCpuAbi = null; 10026 pkg.applicationInfo.secondaryCpuAbi = null; 10027 } 10028 } 10029 10030 private void killApplication(String pkgName, int appId, String reason) { 10031 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10032 } 10033 10034 private void killApplication(String pkgName, int appId, int userId, String reason) { 10035 // Request the ActivityManager to kill the process(only for existing packages) 10036 // so that we do not end up in a confused state while the user is still using the older 10037 // version of the application while the new one gets installed. 10038 final long token = Binder.clearCallingIdentity(); 10039 try { 10040 IActivityManager am = ActivityManager.getService(); 10041 if (am != null) { 10042 try { 10043 am.killApplication(pkgName, appId, userId, reason); 10044 } catch (RemoteException e) { 10045 } 10046 } 10047 } finally { 10048 Binder.restoreCallingIdentity(token); 10049 } 10050 } 10051 10052 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10053 // Remove the parent package setting 10054 PackageSetting ps = (PackageSetting) pkg.mExtras; 10055 if (ps != null) { 10056 removePackageLI(ps, chatty); 10057 } 10058 // Remove the child package setting 10059 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10060 for (int i = 0; i < childCount; i++) { 10061 PackageParser.Package childPkg = pkg.childPackages.get(i); 10062 ps = (PackageSetting) childPkg.mExtras; 10063 if (ps != null) { 10064 removePackageLI(ps, chatty); 10065 } 10066 } 10067 } 10068 10069 void removePackageLI(PackageSetting ps, boolean chatty) { 10070 if (DEBUG_INSTALL) { 10071 if (chatty) 10072 Log.d(TAG, "Removing package " + ps.name); 10073 } 10074 10075 // writer 10076 synchronized (mPackages) { 10077 mPackages.remove(ps.name); 10078 final PackageParser.Package pkg = ps.pkg; 10079 if (pkg != null) { 10080 cleanPackageDataStructuresLILPw(pkg, chatty); 10081 } 10082 } 10083 } 10084 10085 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10086 if (DEBUG_INSTALL) { 10087 if (chatty) 10088 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10089 } 10090 10091 // writer 10092 synchronized (mPackages) { 10093 // Remove the parent package 10094 mPackages.remove(pkg.applicationInfo.packageName); 10095 cleanPackageDataStructuresLILPw(pkg, chatty); 10096 10097 // Remove the child packages 10098 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10099 for (int i = 0; i < childCount; i++) { 10100 PackageParser.Package childPkg = pkg.childPackages.get(i); 10101 mPackages.remove(childPkg.applicationInfo.packageName); 10102 cleanPackageDataStructuresLILPw(childPkg, chatty); 10103 } 10104 } 10105 } 10106 10107 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10108 int N = pkg.providers.size(); 10109 StringBuilder r = null; 10110 int i; 10111 for (i=0; i<N; i++) { 10112 PackageParser.Provider p = pkg.providers.get(i); 10113 mProviders.removeProvider(p); 10114 if (p.info.authority == null) { 10115 10116 /* There was another ContentProvider with this authority when 10117 * this app was installed so this authority is null, 10118 * Ignore it as we don't have to unregister the provider. 10119 */ 10120 continue; 10121 } 10122 String names[] = p.info.authority.split(";"); 10123 for (int j = 0; j < names.length; j++) { 10124 if (mProvidersByAuthority.get(names[j]) == p) { 10125 mProvidersByAuthority.remove(names[j]); 10126 if (DEBUG_REMOVE) { 10127 if (chatty) 10128 Log.d(TAG, "Unregistered content provider: " + names[j] 10129 + ", className = " + p.info.name + ", isSyncable = " 10130 + p.info.isSyncable); 10131 } 10132 } 10133 } 10134 if (DEBUG_REMOVE && chatty) { 10135 if (r == null) { 10136 r = new StringBuilder(256); 10137 } else { 10138 r.append(' '); 10139 } 10140 r.append(p.info.name); 10141 } 10142 } 10143 if (r != null) { 10144 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10145 } 10146 10147 N = pkg.services.size(); 10148 r = null; 10149 for (i=0; i<N; i++) { 10150 PackageParser.Service s = pkg.services.get(i); 10151 mServices.removeService(s); 10152 if (chatty) { 10153 if (r == null) { 10154 r = new StringBuilder(256); 10155 } else { 10156 r.append(' '); 10157 } 10158 r.append(s.info.name); 10159 } 10160 } 10161 if (r != null) { 10162 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10163 } 10164 10165 N = pkg.receivers.size(); 10166 r = null; 10167 for (i=0; i<N; i++) { 10168 PackageParser.Activity a = pkg.receivers.get(i); 10169 mReceivers.removeActivity(a, "receiver"); 10170 if (DEBUG_REMOVE && chatty) { 10171 if (r == null) { 10172 r = new StringBuilder(256); 10173 } else { 10174 r.append(' '); 10175 } 10176 r.append(a.info.name); 10177 } 10178 } 10179 if (r != null) { 10180 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10181 } 10182 10183 N = pkg.activities.size(); 10184 r = null; 10185 for (i=0; i<N; i++) { 10186 PackageParser.Activity a = pkg.activities.get(i); 10187 mActivities.removeActivity(a, "activity"); 10188 if (DEBUG_REMOVE && chatty) { 10189 if (r == null) { 10190 r = new StringBuilder(256); 10191 } else { 10192 r.append(' '); 10193 } 10194 r.append(a.info.name); 10195 } 10196 } 10197 if (r != null) { 10198 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10199 } 10200 10201 N = pkg.permissions.size(); 10202 r = null; 10203 for (i=0; i<N; i++) { 10204 PackageParser.Permission p = pkg.permissions.get(i); 10205 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10206 if (bp == null) { 10207 bp = mSettings.mPermissionTrees.get(p.info.name); 10208 } 10209 if (bp != null && bp.perm == p) { 10210 bp.perm = null; 10211 if (DEBUG_REMOVE && chatty) { 10212 if (r == null) { 10213 r = new StringBuilder(256); 10214 } else { 10215 r.append(' '); 10216 } 10217 r.append(p.info.name); 10218 } 10219 } 10220 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10221 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10222 if (appOpPkgs != null) { 10223 appOpPkgs.remove(pkg.packageName); 10224 } 10225 } 10226 } 10227 if (r != null) { 10228 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10229 } 10230 10231 N = pkg.requestedPermissions.size(); 10232 r = null; 10233 for (i=0; i<N; i++) { 10234 String perm = pkg.requestedPermissions.get(i); 10235 BasePermission bp = mSettings.mPermissions.get(perm); 10236 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10237 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10238 if (appOpPkgs != null) { 10239 appOpPkgs.remove(pkg.packageName); 10240 if (appOpPkgs.isEmpty()) { 10241 mAppOpPermissionPackages.remove(perm); 10242 } 10243 } 10244 } 10245 } 10246 if (r != null) { 10247 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10248 } 10249 10250 N = pkg.instrumentation.size(); 10251 r = null; 10252 for (i=0; i<N; i++) { 10253 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10254 mInstrumentation.remove(a.getComponentName()); 10255 if (DEBUG_REMOVE && chatty) { 10256 if (r == null) { 10257 r = new StringBuilder(256); 10258 } else { 10259 r.append(' '); 10260 } 10261 r.append(a.info.name); 10262 } 10263 } 10264 if (r != null) { 10265 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10266 } 10267 10268 r = null; 10269 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10270 // Only system apps can hold shared libraries. 10271 if (pkg.libraryNames != null) { 10272 for (i=0; i<pkg.libraryNames.size(); i++) { 10273 String name = pkg.libraryNames.get(i); 10274 SharedLibraryEntry cur = mSharedLibraries.get(name); 10275 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10276 mSharedLibraries.remove(name); 10277 if (DEBUG_REMOVE && chatty) { 10278 if (r == null) { 10279 r = new StringBuilder(256); 10280 } else { 10281 r.append(' '); 10282 } 10283 r.append(name); 10284 } 10285 } 10286 } 10287 } 10288 } 10289 if (r != null) { 10290 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10291 } 10292 } 10293 10294 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10295 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10296 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10297 return true; 10298 } 10299 } 10300 return false; 10301 } 10302 10303 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10304 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10305 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10306 10307 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10308 // Update the parent permissions 10309 updatePermissionsLPw(pkg.packageName, pkg, flags); 10310 // Update the child permissions 10311 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10312 for (int i = 0; i < childCount; i++) { 10313 PackageParser.Package childPkg = pkg.childPackages.get(i); 10314 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10315 } 10316 } 10317 10318 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10319 int flags) { 10320 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10321 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10322 } 10323 10324 private void updatePermissionsLPw(String changingPkg, 10325 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10326 // Make sure there are no dangling permission trees. 10327 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10328 while (it.hasNext()) { 10329 final BasePermission bp = it.next(); 10330 if (bp.packageSetting == null) { 10331 // We may not yet have parsed the package, so just see if 10332 // we still know about its settings. 10333 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10334 } 10335 if (bp.packageSetting == null) { 10336 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10337 + " from package " + bp.sourcePackage); 10338 it.remove(); 10339 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10340 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10341 Slog.i(TAG, "Removing old permission tree: " + bp.name 10342 + " from package " + bp.sourcePackage); 10343 flags |= UPDATE_PERMISSIONS_ALL; 10344 it.remove(); 10345 } 10346 } 10347 } 10348 10349 // Make sure all dynamic permissions have been assigned to a package, 10350 // and make sure there are no dangling permissions. 10351 it = mSettings.mPermissions.values().iterator(); 10352 while (it.hasNext()) { 10353 final BasePermission bp = it.next(); 10354 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10355 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10356 + bp.name + " pkg=" + bp.sourcePackage 10357 + " info=" + bp.pendingInfo); 10358 if (bp.packageSetting == null && bp.pendingInfo != null) { 10359 final BasePermission tree = findPermissionTreeLP(bp.name); 10360 if (tree != null && tree.perm != null) { 10361 bp.packageSetting = tree.packageSetting; 10362 bp.perm = new PackageParser.Permission(tree.perm.owner, 10363 new PermissionInfo(bp.pendingInfo)); 10364 bp.perm.info.packageName = tree.perm.info.packageName; 10365 bp.perm.info.name = bp.name; 10366 bp.uid = tree.uid; 10367 } 10368 } 10369 } 10370 if (bp.packageSetting == null) { 10371 // We may not yet have parsed the package, so just see if 10372 // we still know about its settings. 10373 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10374 } 10375 if (bp.packageSetting == null) { 10376 Slog.w(TAG, "Removing dangling permission: " + bp.name 10377 + " from package " + bp.sourcePackage); 10378 it.remove(); 10379 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10380 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10381 Slog.i(TAG, "Removing old permission: " + bp.name 10382 + " from package " + bp.sourcePackage); 10383 flags |= UPDATE_PERMISSIONS_ALL; 10384 it.remove(); 10385 } 10386 } 10387 } 10388 10389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10390 // Now update the permissions for all packages, in particular 10391 // replace the granted permissions of the system packages. 10392 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10393 for (PackageParser.Package pkg : mPackages.values()) { 10394 if (pkg != pkgInfo) { 10395 // Only replace for packages on requested volume 10396 final String volumeUuid = getVolumeUuidForPackage(pkg); 10397 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10398 && Objects.equals(replaceVolumeUuid, volumeUuid); 10399 grantPermissionsLPw(pkg, replace, changingPkg); 10400 } 10401 } 10402 } 10403 10404 if (pkgInfo != null) { 10405 // Only replace for packages on requested volume 10406 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10407 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10408 && Objects.equals(replaceVolumeUuid, volumeUuid); 10409 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10410 } 10411 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10412 } 10413 10414 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10415 String packageOfInterest) { 10416 // IMPORTANT: There are two types of permissions: install and runtime. 10417 // Install time permissions are granted when the app is installed to 10418 // all device users and users added in the future. Runtime permissions 10419 // are granted at runtime explicitly to specific users. Normal and signature 10420 // protected permissions are install time permissions. Dangerous permissions 10421 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10422 // otherwise they are runtime permissions. This function does not manage 10423 // runtime permissions except for the case an app targeting Lollipop MR1 10424 // being upgraded to target a newer SDK, in which case dangerous permissions 10425 // are transformed from install time to runtime ones. 10426 10427 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10428 if (ps == null) { 10429 return; 10430 } 10431 10432 PermissionsState permissionsState = ps.getPermissionsState(); 10433 PermissionsState origPermissions = permissionsState; 10434 10435 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10436 10437 boolean runtimePermissionsRevoked = false; 10438 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10439 10440 boolean changedInstallPermission = false; 10441 10442 if (replace) { 10443 ps.installPermissionsFixed = false; 10444 if (!ps.isSharedUser()) { 10445 origPermissions = new PermissionsState(permissionsState); 10446 permissionsState.reset(); 10447 } else { 10448 // We need to know only about runtime permission changes since the 10449 // calling code always writes the install permissions state but 10450 // the runtime ones are written only if changed. The only cases of 10451 // changed runtime permissions here are promotion of an install to 10452 // runtime and revocation of a runtime from a shared user. 10453 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10454 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10455 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10456 runtimePermissionsRevoked = true; 10457 } 10458 } 10459 } 10460 10461 permissionsState.setGlobalGids(mGlobalGids); 10462 10463 final int N = pkg.requestedPermissions.size(); 10464 for (int i=0; i<N; i++) { 10465 final String name = pkg.requestedPermissions.get(i); 10466 final BasePermission bp = mSettings.mPermissions.get(name); 10467 10468 if (DEBUG_INSTALL) { 10469 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10470 } 10471 10472 if (bp == null || bp.packageSetting == null) { 10473 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10474 Slog.w(TAG, "Unknown permission " + name 10475 + " in package " + pkg.packageName); 10476 } 10477 continue; 10478 } 10479 10480 10481 // Limit ephemeral apps to ephemeral allowed permissions. 10482 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10483 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10484 + pkg.packageName); 10485 continue; 10486 } 10487 10488 final String perm = bp.name; 10489 boolean allowedSig = false; 10490 int grant = GRANT_DENIED; 10491 10492 // Keep track of app op permissions. 10493 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10494 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10495 if (pkgs == null) { 10496 pkgs = new ArraySet<>(); 10497 mAppOpPermissionPackages.put(bp.name, pkgs); 10498 } 10499 pkgs.add(pkg.packageName); 10500 } 10501 10502 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10503 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10504 >= Build.VERSION_CODES.M; 10505 switch (level) { 10506 case PermissionInfo.PROTECTION_NORMAL: { 10507 // For all apps normal permissions are install time ones. 10508 grant = GRANT_INSTALL; 10509 } break; 10510 10511 case PermissionInfo.PROTECTION_DANGEROUS: { 10512 // If a permission review is required for legacy apps we represent 10513 // their permissions as always granted runtime ones since we need 10514 // to keep the review required permission flag per user while an 10515 // install permission's state is shared across all users. 10516 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10517 // For legacy apps dangerous permissions are install time ones. 10518 grant = GRANT_INSTALL; 10519 } else if (origPermissions.hasInstallPermission(bp.name)) { 10520 // For legacy apps that became modern, install becomes runtime. 10521 grant = GRANT_UPGRADE; 10522 } else if (mPromoteSystemApps 10523 && isSystemApp(ps) 10524 && mExistingSystemPackages.contains(ps.name)) { 10525 // For legacy system apps, install becomes runtime. 10526 // We cannot check hasInstallPermission() for system apps since those 10527 // permissions were granted implicitly and not persisted pre-M. 10528 grant = GRANT_UPGRADE; 10529 } else { 10530 // For modern apps keep runtime permissions unchanged. 10531 grant = GRANT_RUNTIME; 10532 } 10533 } break; 10534 10535 case PermissionInfo.PROTECTION_SIGNATURE: { 10536 // For all apps signature permissions are install time ones. 10537 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10538 if (allowedSig) { 10539 grant = GRANT_INSTALL; 10540 } 10541 } break; 10542 } 10543 10544 if (DEBUG_INSTALL) { 10545 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10546 } 10547 10548 if (grant != GRANT_DENIED) { 10549 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10550 // If this is an existing, non-system package, then 10551 // we can't add any new permissions to it. 10552 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10553 // Except... if this is a permission that was added 10554 // to the platform (note: need to only do this when 10555 // updating the platform). 10556 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10557 grant = GRANT_DENIED; 10558 } 10559 } 10560 } 10561 10562 switch (grant) { 10563 case GRANT_INSTALL: { 10564 // Revoke this as runtime permission to handle the case of 10565 // a runtime permission being downgraded to an install one. 10566 // Also in permission review mode we keep dangerous permissions 10567 // for legacy apps 10568 for (int userId : UserManagerService.getInstance().getUserIds()) { 10569 if (origPermissions.getRuntimePermissionState( 10570 bp.name, userId) != null) { 10571 // Revoke the runtime permission and clear the flags. 10572 origPermissions.revokeRuntimePermission(bp, userId); 10573 origPermissions.updatePermissionFlags(bp, userId, 10574 PackageManager.MASK_PERMISSION_FLAGS, 0); 10575 // If we revoked a permission permission, we have to write. 10576 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10577 changedRuntimePermissionUserIds, userId); 10578 } 10579 } 10580 // Grant an install permission. 10581 if (permissionsState.grantInstallPermission(bp) != 10582 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10583 changedInstallPermission = true; 10584 } 10585 } break; 10586 10587 case GRANT_RUNTIME: { 10588 // Grant previously granted runtime permissions. 10589 for (int userId : UserManagerService.getInstance().getUserIds()) { 10590 PermissionState permissionState = origPermissions 10591 .getRuntimePermissionState(bp.name, userId); 10592 int flags = permissionState != null 10593 ? permissionState.getFlags() : 0; 10594 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10595 if (permissionsState.grantRuntimePermission(bp, userId) == 10596 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10597 // If we cannot put the permission as it was, we have to write. 10598 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10599 changedRuntimePermissionUserIds, userId); 10600 } 10601 // If the app supports runtime permissions no need for a review. 10602 if (mPermissionReviewRequired 10603 && appSupportsRuntimePermissions 10604 && (flags & PackageManager 10605 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10606 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10607 // Since we changed the flags, we have to write. 10608 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10609 changedRuntimePermissionUserIds, userId); 10610 } 10611 } else if (mPermissionReviewRequired 10612 && !appSupportsRuntimePermissions) { 10613 // For legacy apps that need a permission review, every new 10614 // runtime permission is granted but it is pending a review. 10615 // We also need to review only platform defined runtime 10616 // permissions as these are the only ones the platform knows 10617 // how to disable the API to simulate revocation as legacy 10618 // apps don't expect to run with revoked permissions. 10619 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10620 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10621 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10622 // We changed the flags, hence have to write. 10623 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10624 changedRuntimePermissionUserIds, userId); 10625 } 10626 } 10627 if (permissionsState.grantRuntimePermission(bp, userId) 10628 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10629 // We changed the permission, hence have to write. 10630 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10631 changedRuntimePermissionUserIds, userId); 10632 } 10633 } 10634 // Propagate the permission flags. 10635 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10636 } 10637 } break; 10638 10639 case GRANT_UPGRADE: { 10640 // Grant runtime permissions for a previously held install permission. 10641 PermissionState permissionState = origPermissions 10642 .getInstallPermissionState(bp.name); 10643 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10644 10645 if (origPermissions.revokeInstallPermission(bp) 10646 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10647 // We will be transferring the permission flags, so clear them. 10648 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10649 PackageManager.MASK_PERMISSION_FLAGS, 0); 10650 changedInstallPermission = true; 10651 } 10652 10653 // If the permission is not to be promoted to runtime we ignore it and 10654 // also its other flags as they are not applicable to install permissions. 10655 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10656 for (int userId : currentUserIds) { 10657 if (permissionsState.grantRuntimePermission(bp, userId) != 10658 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10659 // Transfer the permission flags. 10660 permissionsState.updatePermissionFlags(bp, userId, 10661 flags, flags); 10662 // If we granted the permission, we have to write. 10663 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10664 changedRuntimePermissionUserIds, userId); 10665 } 10666 } 10667 } 10668 } break; 10669 10670 default: { 10671 if (packageOfInterest == null 10672 || packageOfInterest.equals(pkg.packageName)) { 10673 Slog.w(TAG, "Not granting permission " + perm 10674 + " to package " + pkg.packageName 10675 + " because it was previously installed without"); 10676 } 10677 } break; 10678 } 10679 } else { 10680 if (permissionsState.revokeInstallPermission(bp) != 10681 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10682 // Also drop the permission flags. 10683 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10684 PackageManager.MASK_PERMISSION_FLAGS, 0); 10685 changedInstallPermission = true; 10686 Slog.i(TAG, "Un-granting permission " + perm 10687 + " from package " + pkg.packageName 10688 + " (protectionLevel=" + bp.protectionLevel 10689 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10690 + ")"); 10691 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10692 // Don't print warning for app op permissions, since it is fine for them 10693 // not to be granted, there is a UI for the user to decide. 10694 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10695 Slog.w(TAG, "Not granting permission " + perm 10696 + " to package " + pkg.packageName 10697 + " (protectionLevel=" + bp.protectionLevel 10698 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10699 + ")"); 10700 } 10701 } 10702 } 10703 } 10704 10705 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10706 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10707 // This is the first that we have heard about this package, so the 10708 // permissions we have now selected are fixed until explicitly 10709 // changed. 10710 ps.installPermissionsFixed = true; 10711 } 10712 10713 // Persist the runtime permissions state for users with changes. If permissions 10714 // were revoked because no app in the shared user declares them we have to 10715 // write synchronously to avoid losing runtime permissions state. 10716 for (int userId : changedRuntimePermissionUserIds) { 10717 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10718 } 10719 } 10720 10721 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10722 boolean allowed = false; 10723 final int NP = PackageParser.NEW_PERMISSIONS.length; 10724 for (int ip=0; ip<NP; ip++) { 10725 final PackageParser.NewPermissionInfo npi 10726 = PackageParser.NEW_PERMISSIONS[ip]; 10727 if (npi.name.equals(perm) 10728 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10729 allowed = true; 10730 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10731 + pkg.packageName); 10732 break; 10733 } 10734 } 10735 return allowed; 10736 } 10737 10738 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10739 BasePermission bp, PermissionsState origPermissions) { 10740 boolean privilegedPermission = (bp.protectionLevel 10741 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10742 boolean privappPermissionsDisable = 10743 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10744 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10745 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10746 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10747 && !platformPackage && platformPermission) { 10748 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10749 .getPrivAppPermissions(pkg.packageName); 10750 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10751 if (!whitelisted) { 10752 Slog.w(TAG, "Privileged permission " + perm + " for package " 10753 + pkg.packageName + " - not in privapp-permissions whitelist"); 10754 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10755 return false; 10756 } 10757 } 10758 } 10759 boolean allowed = (compareSignatures( 10760 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10761 == PackageManager.SIGNATURE_MATCH) 10762 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10763 == PackageManager.SIGNATURE_MATCH); 10764 if (!allowed && privilegedPermission) { 10765 if (isSystemApp(pkg)) { 10766 // For updated system applications, a system permission 10767 // is granted only if it had been defined by the original application. 10768 if (pkg.isUpdatedSystemApp()) { 10769 final PackageSetting sysPs = mSettings 10770 .getDisabledSystemPkgLPr(pkg.packageName); 10771 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10772 // If the original was granted this permission, we take 10773 // that grant decision as read and propagate it to the 10774 // update. 10775 if (sysPs.isPrivileged()) { 10776 allowed = true; 10777 } 10778 } else { 10779 // The system apk may have been updated with an older 10780 // version of the one on the data partition, but which 10781 // granted a new system permission that it didn't have 10782 // before. In this case we do want to allow the app to 10783 // now get the new permission if the ancestral apk is 10784 // privileged to get it. 10785 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10786 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10787 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10788 allowed = true; 10789 break; 10790 } 10791 } 10792 } 10793 // Also if a privileged parent package on the system image or any of 10794 // its children requested a privileged permission, the updated child 10795 // packages can also get the permission. 10796 if (pkg.parentPackage != null) { 10797 final PackageSetting disabledSysParentPs = mSettings 10798 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10799 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10800 && disabledSysParentPs.isPrivileged()) { 10801 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10802 allowed = true; 10803 } else if (disabledSysParentPs.pkg.childPackages != null) { 10804 final int count = disabledSysParentPs.pkg.childPackages.size(); 10805 for (int i = 0; i < count; i++) { 10806 PackageParser.Package disabledSysChildPkg = 10807 disabledSysParentPs.pkg.childPackages.get(i); 10808 if (isPackageRequestingPermission(disabledSysChildPkg, 10809 perm)) { 10810 allowed = true; 10811 break; 10812 } 10813 } 10814 } 10815 } 10816 } 10817 } 10818 } else { 10819 allowed = isPrivilegedApp(pkg); 10820 } 10821 } 10822 } 10823 if (!allowed) { 10824 if (!allowed && (bp.protectionLevel 10825 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10826 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10827 // If this was a previously normal/dangerous permission that got moved 10828 // to a system permission as part of the runtime permission redesign, then 10829 // we still want to blindly grant it to old apps. 10830 allowed = true; 10831 } 10832 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10833 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10834 // If this permission is to be granted to the system installer and 10835 // this app is an installer, then it gets the permission. 10836 allowed = true; 10837 } 10838 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10839 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10840 // If this permission is to be granted to the system verifier and 10841 // this app is a verifier, then it gets the permission. 10842 allowed = true; 10843 } 10844 if (!allowed && (bp.protectionLevel 10845 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10846 && isSystemApp(pkg)) { 10847 // Any pre-installed system app is allowed to get this permission. 10848 allowed = true; 10849 } 10850 if (!allowed && (bp.protectionLevel 10851 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10852 // For development permissions, a development permission 10853 // is granted only if it was already granted. 10854 allowed = origPermissions.hasInstallPermission(perm); 10855 } 10856 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10857 && pkg.packageName.equals(mSetupWizardPackage)) { 10858 // If this permission is to be granted to the system setup wizard and 10859 // this app is a setup wizard, then it gets the permission. 10860 allowed = true; 10861 } 10862 } 10863 return allowed; 10864 } 10865 10866 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10867 final int permCount = pkg.requestedPermissions.size(); 10868 for (int j = 0; j < permCount; j++) { 10869 String requestedPermission = pkg.requestedPermissions.get(j); 10870 if (permission.equals(requestedPermission)) { 10871 return true; 10872 } 10873 } 10874 return false; 10875 } 10876 10877 final class ActivityIntentResolver 10878 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10879 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10880 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 10881 if (!sUserManager.exists(userId)) return null; 10882 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 10883 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 10884 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 10885 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 10886 isEphemeral, userId); 10887 } 10888 10889 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10890 int userId) { 10891 if (!sUserManager.exists(userId)) return null; 10892 mFlags = flags; 10893 return super.queryIntent(intent, resolvedType, 10894 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 10895 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 10896 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 10897 } 10898 10899 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10900 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10901 if (!sUserManager.exists(userId)) return null; 10902 if (packageActivities == null) { 10903 return null; 10904 } 10905 mFlags = flags; 10906 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10907 final boolean vislbleToEphemeral = 10908 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 10909 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 10910 final int N = packageActivities.size(); 10911 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10912 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10913 10914 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10915 for (int i = 0; i < N; ++i) { 10916 intentFilters = packageActivities.get(i).intents; 10917 if (intentFilters != null && intentFilters.size() > 0) { 10918 PackageParser.ActivityIntentInfo[] array = 10919 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10920 intentFilters.toArray(array); 10921 listCut.add(array); 10922 } 10923 } 10924 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 10925 vislbleToEphemeral, isEphemeral, listCut, userId); 10926 } 10927 10928 /** 10929 * Finds a privileged activity that matches the specified activity names. 10930 */ 10931 private PackageParser.Activity findMatchingActivity( 10932 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10933 for (PackageParser.Activity sysActivity : activityList) { 10934 if (sysActivity.info.name.equals(activityInfo.name)) { 10935 return sysActivity; 10936 } 10937 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10938 return sysActivity; 10939 } 10940 if (sysActivity.info.targetActivity != null) { 10941 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10942 return sysActivity; 10943 } 10944 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10945 return sysActivity; 10946 } 10947 } 10948 } 10949 return null; 10950 } 10951 10952 public class IterGenerator<E> { 10953 public Iterator<E> generate(ActivityIntentInfo info) { 10954 return null; 10955 } 10956 } 10957 10958 public class ActionIterGenerator extends IterGenerator<String> { 10959 @Override 10960 public Iterator<String> generate(ActivityIntentInfo info) { 10961 return info.actionsIterator(); 10962 } 10963 } 10964 10965 public class CategoriesIterGenerator extends IterGenerator<String> { 10966 @Override 10967 public Iterator<String> generate(ActivityIntentInfo info) { 10968 return info.categoriesIterator(); 10969 } 10970 } 10971 10972 public class SchemesIterGenerator extends IterGenerator<String> { 10973 @Override 10974 public Iterator<String> generate(ActivityIntentInfo info) { 10975 return info.schemesIterator(); 10976 } 10977 } 10978 10979 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10980 @Override 10981 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10982 return info.authoritiesIterator(); 10983 } 10984 } 10985 10986 /** 10987 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10988 * MODIFIED. Do not pass in a list that should not be changed. 10989 */ 10990 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10991 IterGenerator<T> generator, Iterator<T> searchIterator) { 10992 // loop through the set of actions; every one must be found in the intent filter 10993 while (searchIterator.hasNext()) { 10994 // we must have at least one filter in the list to consider a match 10995 if (intentList.size() == 0) { 10996 break; 10997 } 10998 10999 final T searchAction = searchIterator.next(); 11000 11001 // loop through the set of intent filters 11002 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11003 while (intentIter.hasNext()) { 11004 final ActivityIntentInfo intentInfo = intentIter.next(); 11005 boolean selectionFound = false; 11006 11007 // loop through the intent filter's selection criteria; at least one 11008 // of them must match the searched criteria 11009 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11010 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11011 final T intentSelection = intentSelectionIter.next(); 11012 if (intentSelection != null && intentSelection.equals(searchAction)) { 11013 selectionFound = true; 11014 break; 11015 } 11016 } 11017 11018 // the selection criteria wasn't found in this filter's set; this filter 11019 // is not a potential match 11020 if (!selectionFound) { 11021 intentIter.remove(); 11022 } 11023 } 11024 } 11025 } 11026 11027 private boolean isProtectedAction(ActivityIntentInfo filter) { 11028 final Iterator<String> actionsIter = filter.actionsIterator(); 11029 while (actionsIter != null && actionsIter.hasNext()) { 11030 final String filterAction = actionsIter.next(); 11031 if (PROTECTED_ACTIONS.contains(filterAction)) { 11032 return true; 11033 } 11034 } 11035 return false; 11036 } 11037 11038 /** 11039 * Adjusts the priority of the given intent filter according to policy. 11040 * <p> 11041 * <ul> 11042 * <li>The priority for non privileged applications is capped to '0'</li> 11043 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11044 * <li>The priority for unbundled updates to privileged applications is capped to the 11045 * priority defined on the system partition</li> 11046 * </ul> 11047 * <p> 11048 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11049 * allowed to obtain any priority on any action. 11050 */ 11051 private void adjustPriority( 11052 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11053 // nothing to do; priority is fine as-is 11054 if (intent.getPriority() <= 0) { 11055 return; 11056 } 11057 11058 final ActivityInfo activityInfo = intent.activity.info; 11059 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11060 11061 final boolean privilegedApp = 11062 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11063 if (!privilegedApp) { 11064 // non-privileged applications can never define a priority >0 11065 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11066 + " package: " + applicationInfo.packageName 11067 + " activity: " + intent.activity.className 11068 + " origPrio: " + intent.getPriority()); 11069 intent.setPriority(0); 11070 return; 11071 } 11072 11073 if (systemActivities == null) { 11074 // the system package is not disabled; we're parsing the system partition 11075 if (isProtectedAction(intent)) { 11076 if (mDeferProtectedFilters) { 11077 // We can't deal with these just yet. No component should ever obtain a 11078 // >0 priority for a protected actions, with ONE exception -- the setup 11079 // wizard. The setup wizard, however, cannot be known until we're able to 11080 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11081 // until all intent filters have been processed. Chicken, meet egg. 11082 // Let the filter temporarily have a high priority and rectify the 11083 // priorities after all system packages have been scanned. 11084 mProtectedFilters.add(intent); 11085 if (DEBUG_FILTERS) { 11086 Slog.i(TAG, "Protected action; save for later;" 11087 + " package: " + applicationInfo.packageName 11088 + " activity: " + intent.activity.className 11089 + " origPrio: " + intent.getPriority()); 11090 } 11091 return; 11092 } else { 11093 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11094 Slog.i(TAG, "No setup wizard;" 11095 + " All protected intents capped to priority 0"); 11096 } 11097 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11098 if (DEBUG_FILTERS) { 11099 Slog.i(TAG, "Found setup wizard;" 11100 + " allow priority " + intent.getPriority() + ";" 11101 + " package: " + intent.activity.info.packageName 11102 + " activity: " + intent.activity.className 11103 + " priority: " + intent.getPriority()); 11104 } 11105 // setup wizard gets whatever it wants 11106 return; 11107 } 11108 Slog.w(TAG, "Protected action; cap priority to 0;" 11109 + " package: " + intent.activity.info.packageName 11110 + " activity: " + intent.activity.className 11111 + " origPrio: " + intent.getPriority()); 11112 intent.setPriority(0); 11113 return; 11114 } 11115 } 11116 // privileged apps on the system image get whatever priority they request 11117 return; 11118 } 11119 11120 // privileged app unbundled update ... try to find the same activity 11121 final PackageParser.Activity foundActivity = 11122 findMatchingActivity(systemActivities, activityInfo); 11123 if (foundActivity == null) { 11124 // this is a new activity; it cannot obtain >0 priority 11125 if (DEBUG_FILTERS) { 11126 Slog.i(TAG, "New activity; cap priority to 0;" 11127 + " package: " + applicationInfo.packageName 11128 + " activity: " + intent.activity.className 11129 + " origPrio: " + intent.getPriority()); 11130 } 11131 intent.setPriority(0); 11132 return; 11133 } 11134 11135 // found activity, now check for filter equivalence 11136 11137 // a shallow copy is enough; we modify the list, not its contents 11138 final List<ActivityIntentInfo> intentListCopy = 11139 new ArrayList<>(foundActivity.intents); 11140 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11141 11142 // find matching action subsets 11143 final Iterator<String> actionsIterator = intent.actionsIterator(); 11144 if (actionsIterator != null) { 11145 getIntentListSubset( 11146 intentListCopy, new ActionIterGenerator(), actionsIterator); 11147 if (intentListCopy.size() == 0) { 11148 // no more intents to match; we're not equivalent 11149 if (DEBUG_FILTERS) { 11150 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11151 + " package: " + applicationInfo.packageName 11152 + " activity: " + intent.activity.className 11153 + " origPrio: " + intent.getPriority()); 11154 } 11155 intent.setPriority(0); 11156 return; 11157 } 11158 } 11159 11160 // find matching category subsets 11161 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11162 if (categoriesIterator != null) { 11163 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11164 categoriesIterator); 11165 if (intentListCopy.size() == 0) { 11166 // no more intents to match; we're not equivalent 11167 if (DEBUG_FILTERS) { 11168 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11169 + " package: " + applicationInfo.packageName 11170 + " activity: " + intent.activity.className 11171 + " origPrio: " + intent.getPriority()); 11172 } 11173 intent.setPriority(0); 11174 return; 11175 } 11176 } 11177 11178 // find matching schemes subsets 11179 final Iterator<String> schemesIterator = intent.schemesIterator(); 11180 if (schemesIterator != null) { 11181 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11182 schemesIterator); 11183 if (intentListCopy.size() == 0) { 11184 // no more intents to match; we're not equivalent 11185 if (DEBUG_FILTERS) { 11186 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11187 + " package: " + applicationInfo.packageName 11188 + " activity: " + intent.activity.className 11189 + " origPrio: " + intent.getPriority()); 11190 } 11191 intent.setPriority(0); 11192 return; 11193 } 11194 } 11195 11196 // find matching authorities subsets 11197 final Iterator<IntentFilter.AuthorityEntry> 11198 authoritiesIterator = intent.authoritiesIterator(); 11199 if (authoritiesIterator != null) { 11200 getIntentListSubset(intentListCopy, 11201 new AuthoritiesIterGenerator(), 11202 authoritiesIterator); 11203 if (intentListCopy.size() == 0) { 11204 // no more intents to match; we're not equivalent 11205 if (DEBUG_FILTERS) { 11206 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11207 + " package: " + applicationInfo.packageName 11208 + " activity: " + intent.activity.className 11209 + " origPrio: " + intent.getPriority()); 11210 } 11211 intent.setPriority(0); 11212 return; 11213 } 11214 } 11215 11216 // we found matching filter(s); app gets the max priority of all intents 11217 int cappedPriority = 0; 11218 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11219 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11220 } 11221 if (intent.getPriority() > cappedPriority) { 11222 if (DEBUG_FILTERS) { 11223 Slog.i(TAG, "Found matching filter(s);" 11224 + " cap priority to " + cappedPriority + ";" 11225 + " package: " + applicationInfo.packageName 11226 + " activity: " + intent.activity.className 11227 + " origPrio: " + intent.getPriority()); 11228 } 11229 intent.setPriority(cappedPriority); 11230 return; 11231 } 11232 // all this for nothing; the requested priority was <= what was on the system 11233 } 11234 11235 public final void addActivity(PackageParser.Activity a, String type) { 11236 mActivities.put(a.getComponentName(), a); 11237 if (DEBUG_SHOW_INFO) 11238 Log.v( 11239 TAG, " " + type + " " + 11240 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11241 if (DEBUG_SHOW_INFO) 11242 Log.v(TAG, " Class=" + a.info.name); 11243 final int NI = a.intents.size(); 11244 for (int j=0; j<NI; j++) { 11245 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11246 if ("activity".equals(type)) { 11247 final PackageSetting ps = 11248 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11249 final List<PackageParser.Activity> systemActivities = 11250 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11251 adjustPriority(systemActivities, intent); 11252 } 11253 if (DEBUG_SHOW_INFO) { 11254 Log.v(TAG, " IntentFilter:"); 11255 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11256 } 11257 if (!intent.debugCheck()) { 11258 Log.w(TAG, "==> For Activity " + a.info.name); 11259 } 11260 addFilter(intent); 11261 } 11262 } 11263 11264 public final void removeActivity(PackageParser.Activity a, String type) { 11265 mActivities.remove(a.getComponentName()); 11266 if (DEBUG_SHOW_INFO) { 11267 Log.v(TAG, " " + type + " " 11268 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11269 : a.info.name) + ":"); 11270 Log.v(TAG, " Class=" + a.info.name); 11271 } 11272 final int NI = a.intents.size(); 11273 for (int j=0; j<NI; j++) { 11274 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11275 if (DEBUG_SHOW_INFO) { 11276 Log.v(TAG, " IntentFilter:"); 11277 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11278 } 11279 removeFilter(intent); 11280 } 11281 } 11282 11283 @Override 11284 protected boolean allowFilterResult( 11285 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11286 ActivityInfo filterAi = filter.activity.info; 11287 for (int i=dest.size()-1; i>=0; i--) { 11288 ActivityInfo destAi = dest.get(i).activityInfo; 11289 if (destAi.name == filterAi.name 11290 && destAi.packageName == filterAi.packageName) { 11291 return false; 11292 } 11293 } 11294 return true; 11295 } 11296 11297 @Override 11298 protected ActivityIntentInfo[] newArray(int size) { 11299 return new ActivityIntentInfo[size]; 11300 } 11301 11302 @Override 11303 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11304 if (!sUserManager.exists(userId)) return true; 11305 PackageParser.Package p = filter.activity.owner; 11306 if (p != null) { 11307 PackageSetting ps = (PackageSetting)p.mExtras; 11308 if (ps != null) { 11309 // System apps are never considered stopped for purposes of 11310 // filtering, because there may be no way for the user to 11311 // actually re-launch them. 11312 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11313 && ps.getStopped(userId); 11314 } 11315 } 11316 return false; 11317 } 11318 11319 @Override 11320 protected boolean isPackageForFilter(String packageName, 11321 PackageParser.ActivityIntentInfo info) { 11322 return packageName.equals(info.activity.owner.packageName); 11323 } 11324 11325 @Override 11326 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11327 int match, int userId) { 11328 if (!sUserManager.exists(userId)) return null; 11329 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11330 return null; 11331 } 11332 final PackageParser.Activity activity = info.activity; 11333 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11334 if (ps == null) { 11335 return null; 11336 } 11337 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11338 ps.readUserState(userId), userId); 11339 if (ai == null) { 11340 return null; 11341 } 11342 final ResolveInfo res = new ResolveInfo(); 11343 res.activityInfo = ai; 11344 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11345 res.filter = info; 11346 } 11347 if (info != null) { 11348 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11349 } 11350 res.priority = info.getPriority(); 11351 res.preferredOrder = activity.owner.mPreferredOrder; 11352 //System.out.println("Result: " + res.activityInfo.className + 11353 // " = " + res.priority); 11354 res.match = match; 11355 res.isDefault = info.hasDefault; 11356 res.labelRes = info.labelRes; 11357 res.nonLocalizedLabel = info.nonLocalizedLabel; 11358 if (userNeedsBadging(userId)) { 11359 res.noResourceId = true; 11360 } else { 11361 res.icon = info.icon; 11362 } 11363 res.iconResourceId = info.icon; 11364 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11365 return res; 11366 } 11367 11368 @Override 11369 protected void sortResults(List<ResolveInfo> results) { 11370 Collections.sort(results, mResolvePrioritySorter); 11371 } 11372 11373 @Override 11374 protected void dumpFilter(PrintWriter out, String prefix, 11375 PackageParser.ActivityIntentInfo filter) { 11376 out.print(prefix); out.print( 11377 Integer.toHexString(System.identityHashCode(filter.activity))); 11378 out.print(' '); 11379 filter.activity.printComponentShortName(out); 11380 out.print(" filter "); 11381 out.println(Integer.toHexString(System.identityHashCode(filter))); 11382 } 11383 11384 @Override 11385 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11386 return filter.activity; 11387 } 11388 11389 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11390 PackageParser.Activity activity = (PackageParser.Activity)label; 11391 out.print(prefix); out.print( 11392 Integer.toHexString(System.identityHashCode(activity))); 11393 out.print(' '); 11394 activity.printComponentShortName(out); 11395 if (count > 1) { 11396 out.print(" ("); out.print(count); out.print(" filters)"); 11397 } 11398 out.println(); 11399 } 11400 11401 // Keys are String (activity class name), values are Activity. 11402 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11403 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11404 private int mFlags; 11405 } 11406 11407 private final class ServiceIntentResolver 11408 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11409 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11410 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11411 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11412 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11413 isEphemeral, userId); 11414 } 11415 11416 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11417 int userId) { 11418 if (!sUserManager.exists(userId)) return null; 11419 mFlags = flags; 11420 return super.queryIntent(intent, resolvedType, 11421 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11422 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11423 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11424 } 11425 11426 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11427 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11428 if (!sUserManager.exists(userId)) return null; 11429 if (packageServices == null) { 11430 return null; 11431 } 11432 mFlags = flags; 11433 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11434 final boolean vislbleToEphemeral = 11435 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11436 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11437 final int N = packageServices.size(); 11438 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11439 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11440 11441 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11442 for (int i = 0; i < N; ++i) { 11443 intentFilters = packageServices.get(i).intents; 11444 if (intentFilters != null && intentFilters.size() > 0) { 11445 PackageParser.ServiceIntentInfo[] array = 11446 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11447 intentFilters.toArray(array); 11448 listCut.add(array); 11449 } 11450 } 11451 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11452 vislbleToEphemeral, isEphemeral, listCut, userId); 11453 } 11454 11455 public final void addService(PackageParser.Service s) { 11456 mServices.put(s.getComponentName(), s); 11457 if (DEBUG_SHOW_INFO) { 11458 Log.v(TAG, " " 11459 + (s.info.nonLocalizedLabel != null 11460 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11461 Log.v(TAG, " Class=" + s.info.name); 11462 } 11463 final int NI = s.intents.size(); 11464 int j; 11465 for (j=0; j<NI; j++) { 11466 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11467 if (DEBUG_SHOW_INFO) { 11468 Log.v(TAG, " IntentFilter:"); 11469 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11470 } 11471 if (!intent.debugCheck()) { 11472 Log.w(TAG, "==> For Service " + s.info.name); 11473 } 11474 addFilter(intent); 11475 } 11476 } 11477 11478 public final void removeService(PackageParser.Service s) { 11479 mServices.remove(s.getComponentName()); 11480 if (DEBUG_SHOW_INFO) { 11481 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11482 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11483 Log.v(TAG, " Class=" + s.info.name); 11484 } 11485 final int NI = s.intents.size(); 11486 int j; 11487 for (j=0; j<NI; j++) { 11488 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11489 if (DEBUG_SHOW_INFO) { 11490 Log.v(TAG, " IntentFilter:"); 11491 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11492 } 11493 removeFilter(intent); 11494 } 11495 } 11496 11497 @Override 11498 protected boolean allowFilterResult( 11499 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11500 ServiceInfo filterSi = filter.service.info; 11501 for (int i=dest.size()-1; i>=0; i--) { 11502 ServiceInfo destAi = dest.get(i).serviceInfo; 11503 if (destAi.name == filterSi.name 11504 && destAi.packageName == filterSi.packageName) { 11505 return false; 11506 } 11507 } 11508 return true; 11509 } 11510 11511 @Override 11512 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11513 return new PackageParser.ServiceIntentInfo[size]; 11514 } 11515 11516 @Override 11517 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11518 if (!sUserManager.exists(userId)) return true; 11519 PackageParser.Package p = filter.service.owner; 11520 if (p != null) { 11521 PackageSetting ps = (PackageSetting)p.mExtras; 11522 if (ps != null) { 11523 // System apps are never considered stopped for purposes of 11524 // filtering, because there may be no way for the user to 11525 // actually re-launch them. 11526 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11527 && ps.getStopped(userId); 11528 } 11529 } 11530 return false; 11531 } 11532 11533 @Override 11534 protected boolean isPackageForFilter(String packageName, 11535 PackageParser.ServiceIntentInfo info) { 11536 return packageName.equals(info.service.owner.packageName); 11537 } 11538 11539 @Override 11540 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11541 int match, int userId) { 11542 if (!sUserManager.exists(userId)) return null; 11543 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11544 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11545 return null; 11546 } 11547 final PackageParser.Service service = info.service; 11548 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11549 if (ps == null) { 11550 return null; 11551 } 11552 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11553 ps.readUserState(userId), userId); 11554 if (si == null) { 11555 return null; 11556 } 11557 final ResolveInfo res = new ResolveInfo(); 11558 res.serviceInfo = si; 11559 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11560 res.filter = filter; 11561 } 11562 res.priority = info.getPriority(); 11563 res.preferredOrder = service.owner.mPreferredOrder; 11564 res.match = match; 11565 res.isDefault = info.hasDefault; 11566 res.labelRes = info.labelRes; 11567 res.nonLocalizedLabel = info.nonLocalizedLabel; 11568 res.icon = info.icon; 11569 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11570 return res; 11571 } 11572 11573 @Override 11574 protected void sortResults(List<ResolveInfo> results) { 11575 Collections.sort(results, mResolvePrioritySorter); 11576 } 11577 11578 @Override 11579 protected void dumpFilter(PrintWriter out, String prefix, 11580 PackageParser.ServiceIntentInfo filter) { 11581 out.print(prefix); out.print( 11582 Integer.toHexString(System.identityHashCode(filter.service))); 11583 out.print(' '); 11584 filter.service.printComponentShortName(out); 11585 out.print(" filter "); 11586 out.println(Integer.toHexString(System.identityHashCode(filter))); 11587 } 11588 11589 @Override 11590 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11591 return filter.service; 11592 } 11593 11594 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11595 PackageParser.Service service = (PackageParser.Service)label; 11596 out.print(prefix); out.print( 11597 Integer.toHexString(System.identityHashCode(service))); 11598 out.print(' '); 11599 service.printComponentShortName(out); 11600 if (count > 1) { 11601 out.print(" ("); out.print(count); out.print(" filters)"); 11602 } 11603 out.println(); 11604 } 11605 11606// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11607// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11608// final List<ResolveInfo> retList = Lists.newArrayList(); 11609// while (i.hasNext()) { 11610// final ResolveInfo resolveInfo = (ResolveInfo) i; 11611// if (isEnabledLP(resolveInfo.serviceInfo)) { 11612// retList.add(resolveInfo); 11613// } 11614// } 11615// return retList; 11616// } 11617 11618 // Keys are String (activity class name), values are Activity. 11619 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11620 = new ArrayMap<ComponentName, PackageParser.Service>(); 11621 private int mFlags; 11622 } 11623 11624 private final class ProviderIntentResolver 11625 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11626 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11627 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11628 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11629 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11630 isEphemeral, userId); 11631 } 11632 11633 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11634 int userId) { 11635 if (!sUserManager.exists(userId)) 11636 return null; 11637 mFlags = flags; 11638 return super.queryIntent(intent, resolvedType, 11639 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11640 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11641 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11642 } 11643 11644 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11645 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11646 if (!sUserManager.exists(userId)) 11647 return null; 11648 if (packageProviders == null) { 11649 return null; 11650 } 11651 mFlags = flags; 11652 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11653 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11654 final boolean vislbleToEphemeral = 11655 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11656 final int N = packageProviders.size(); 11657 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11658 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11659 11660 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11661 for (int i = 0; i < N; ++i) { 11662 intentFilters = packageProviders.get(i).intents; 11663 if (intentFilters != null && intentFilters.size() > 0) { 11664 PackageParser.ProviderIntentInfo[] array = 11665 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11666 intentFilters.toArray(array); 11667 listCut.add(array); 11668 } 11669 } 11670 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11671 vislbleToEphemeral, isEphemeral, listCut, userId); 11672 } 11673 11674 public final void addProvider(PackageParser.Provider p) { 11675 if (mProviders.containsKey(p.getComponentName())) { 11676 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11677 return; 11678 } 11679 11680 mProviders.put(p.getComponentName(), p); 11681 if (DEBUG_SHOW_INFO) { 11682 Log.v(TAG, " " 11683 + (p.info.nonLocalizedLabel != null 11684 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11685 Log.v(TAG, " Class=" + p.info.name); 11686 } 11687 final int NI = p.intents.size(); 11688 int j; 11689 for (j = 0; j < NI; j++) { 11690 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11691 if (DEBUG_SHOW_INFO) { 11692 Log.v(TAG, " IntentFilter:"); 11693 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11694 } 11695 if (!intent.debugCheck()) { 11696 Log.w(TAG, "==> For Provider " + p.info.name); 11697 } 11698 addFilter(intent); 11699 } 11700 } 11701 11702 public final void removeProvider(PackageParser.Provider p) { 11703 mProviders.remove(p.getComponentName()); 11704 if (DEBUG_SHOW_INFO) { 11705 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11706 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11707 Log.v(TAG, " Class=" + p.info.name); 11708 } 11709 final int NI = p.intents.size(); 11710 int j; 11711 for (j = 0; j < NI; j++) { 11712 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11713 if (DEBUG_SHOW_INFO) { 11714 Log.v(TAG, " IntentFilter:"); 11715 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11716 } 11717 removeFilter(intent); 11718 } 11719 } 11720 11721 @Override 11722 protected boolean allowFilterResult( 11723 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11724 ProviderInfo filterPi = filter.provider.info; 11725 for (int i = dest.size() - 1; i >= 0; i--) { 11726 ProviderInfo destPi = dest.get(i).providerInfo; 11727 if (destPi.name == filterPi.name 11728 && destPi.packageName == filterPi.packageName) { 11729 return false; 11730 } 11731 } 11732 return true; 11733 } 11734 11735 @Override 11736 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11737 return new PackageParser.ProviderIntentInfo[size]; 11738 } 11739 11740 @Override 11741 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11742 if (!sUserManager.exists(userId)) 11743 return true; 11744 PackageParser.Package p = filter.provider.owner; 11745 if (p != null) { 11746 PackageSetting ps = (PackageSetting) p.mExtras; 11747 if (ps != null) { 11748 // System apps are never considered stopped for purposes of 11749 // filtering, because there may be no way for the user to 11750 // actually re-launch them. 11751 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11752 && ps.getStopped(userId); 11753 } 11754 } 11755 return false; 11756 } 11757 11758 @Override 11759 protected boolean isPackageForFilter(String packageName, 11760 PackageParser.ProviderIntentInfo info) { 11761 return packageName.equals(info.provider.owner.packageName); 11762 } 11763 11764 @Override 11765 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11766 int match, int userId) { 11767 if (!sUserManager.exists(userId)) 11768 return null; 11769 final PackageParser.ProviderIntentInfo info = filter; 11770 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11771 return null; 11772 } 11773 final PackageParser.Provider provider = info.provider; 11774 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11775 if (ps == null) { 11776 return null; 11777 } 11778 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11779 ps.readUserState(userId), userId); 11780 if (pi == null) { 11781 return null; 11782 } 11783 final ResolveInfo res = new ResolveInfo(); 11784 res.providerInfo = pi; 11785 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11786 res.filter = filter; 11787 } 11788 res.priority = info.getPriority(); 11789 res.preferredOrder = provider.owner.mPreferredOrder; 11790 res.match = match; 11791 res.isDefault = info.hasDefault; 11792 res.labelRes = info.labelRes; 11793 res.nonLocalizedLabel = info.nonLocalizedLabel; 11794 res.icon = info.icon; 11795 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11796 return res; 11797 } 11798 11799 @Override 11800 protected void sortResults(List<ResolveInfo> results) { 11801 Collections.sort(results, mResolvePrioritySorter); 11802 } 11803 11804 @Override 11805 protected void dumpFilter(PrintWriter out, String prefix, 11806 PackageParser.ProviderIntentInfo filter) { 11807 out.print(prefix); 11808 out.print( 11809 Integer.toHexString(System.identityHashCode(filter.provider))); 11810 out.print(' '); 11811 filter.provider.printComponentShortName(out); 11812 out.print(" filter "); 11813 out.println(Integer.toHexString(System.identityHashCode(filter))); 11814 } 11815 11816 @Override 11817 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11818 return filter.provider; 11819 } 11820 11821 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11822 PackageParser.Provider provider = (PackageParser.Provider)label; 11823 out.print(prefix); out.print( 11824 Integer.toHexString(System.identityHashCode(provider))); 11825 out.print(' '); 11826 provider.printComponentShortName(out); 11827 if (count > 1) { 11828 out.print(" ("); out.print(count); out.print(" filters)"); 11829 } 11830 out.println(); 11831 } 11832 11833 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11834 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11835 private int mFlags; 11836 } 11837 11838 static final class EphemeralIntentResolver 11839 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11840 /** 11841 * The result that has the highest defined order. Ordering applies on a 11842 * per-package basis. Mapping is from package name to Pair of order and 11843 * EphemeralResolveInfo. 11844 * <p> 11845 * NOTE: This is implemented as a field variable for convenience and efficiency. 11846 * By having a field variable, we're able to track filter ordering as soon as 11847 * a non-zero order is defined. Otherwise, multiple loops across the result set 11848 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11849 * this needs to be contained entirely within {@link #filterResults()}. 11850 */ 11851 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11852 11853 @Override 11854 protected EphemeralResponse[] newArray(int size) { 11855 return new EphemeralResponse[size]; 11856 } 11857 11858 @Override 11859 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11860 return true; 11861 } 11862 11863 @Override 11864 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11865 int userId) { 11866 if (!sUserManager.exists(userId)) { 11867 return null; 11868 } 11869 final String packageName = responseObj.resolveInfo.getPackageName(); 11870 final Integer order = responseObj.getOrder(); 11871 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11872 mOrderResult.get(packageName); 11873 // ordering is enabled and this item's order isn't high enough 11874 if (lastOrderResult != null && lastOrderResult.first >= order) { 11875 return null; 11876 } 11877 final EphemeralResolveInfo res = responseObj.resolveInfo; 11878 if (order > 0) { 11879 // non-zero order, enable ordering 11880 mOrderResult.put(packageName, new Pair<>(order, res)); 11881 } 11882 return responseObj; 11883 } 11884 11885 @Override 11886 protected void filterResults(List<EphemeralResponse> results) { 11887 // only do work if ordering is enabled [most of the time it won't be] 11888 if (mOrderResult.size() == 0) { 11889 return; 11890 } 11891 int resultSize = results.size(); 11892 for (int i = 0; i < resultSize; i++) { 11893 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11894 final String packageName = info.getPackageName(); 11895 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11896 if (savedInfo == null) { 11897 // package doesn't having ordering 11898 continue; 11899 } 11900 if (savedInfo.second == info) { 11901 // circled back to the highest ordered item; remove from order list 11902 mOrderResult.remove(savedInfo); 11903 if (mOrderResult.size() == 0) { 11904 // no more ordered items 11905 break; 11906 } 11907 continue; 11908 } 11909 // item has a worse order, remove it from the result list 11910 results.remove(i); 11911 resultSize--; 11912 i--; 11913 } 11914 } 11915 } 11916 11917 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11918 new Comparator<ResolveInfo>() { 11919 public int compare(ResolveInfo r1, ResolveInfo r2) { 11920 int v1 = r1.priority; 11921 int v2 = r2.priority; 11922 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11923 if (v1 != v2) { 11924 return (v1 > v2) ? -1 : 1; 11925 } 11926 v1 = r1.preferredOrder; 11927 v2 = r2.preferredOrder; 11928 if (v1 != v2) { 11929 return (v1 > v2) ? -1 : 1; 11930 } 11931 if (r1.isDefault != r2.isDefault) { 11932 return r1.isDefault ? -1 : 1; 11933 } 11934 v1 = r1.match; 11935 v2 = r2.match; 11936 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11937 if (v1 != v2) { 11938 return (v1 > v2) ? -1 : 1; 11939 } 11940 if (r1.system != r2.system) { 11941 return r1.system ? -1 : 1; 11942 } 11943 if (r1.activityInfo != null) { 11944 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11945 } 11946 if (r1.serviceInfo != null) { 11947 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11948 } 11949 if (r1.providerInfo != null) { 11950 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11951 } 11952 return 0; 11953 } 11954 }; 11955 11956 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11957 new Comparator<ProviderInfo>() { 11958 public int compare(ProviderInfo p1, ProviderInfo p2) { 11959 final int v1 = p1.initOrder; 11960 final int v2 = p2.initOrder; 11961 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11962 } 11963 }; 11964 11965 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11966 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11967 final int[] userIds) { 11968 mHandler.post(new Runnable() { 11969 @Override 11970 public void run() { 11971 try { 11972 final IActivityManager am = ActivityManager.getService(); 11973 if (am == null) return; 11974 final int[] resolvedUserIds; 11975 if (userIds == null) { 11976 resolvedUserIds = am.getRunningUserIds(); 11977 } else { 11978 resolvedUserIds = userIds; 11979 } 11980 for (int id : resolvedUserIds) { 11981 final Intent intent = new Intent(action, 11982 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11983 if (extras != null) { 11984 intent.putExtras(extras); 11985 } 11986 if (targetPkg != null) { 11987 intent.setPackage(targetPkg); 11988 } 11989 // Modify the UID when posting to other users 11990 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11991 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11992 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11993 intent.putExtra(Intent.EXTRA_UID, uid); 11994 } 11995 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11996 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11997 if (DEBUG_BROADCASTS) { 11998 RuntimeException here = new RuntimeException("here"); 11999 here.fillInStackTrace(); 12000 Slog.d(TAG, "Sending to user " + id + ": " 12001 + intent.toShortString(false, true, false, false) 12002 + " " + intent.getExtras(), here); 12003 } 12004 am.broadcastIntent(null, intent, null, finishedReceiver, 12005 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12006 null, finishedReceiver != null, false, id); 12007 } 12008 } catch (RemoteException ex) { 12009 } 12010 } 12011 }); 12012 } 12013 12014 /** 12015 * Check if the external storage media is available. This is true if there 12016 * is a mounted external storage medium or if the external storage is 12017 * emulated. 12018 */ 12019 private boolean isExternalMediaAvailable() { 12020 return mMediaMounted || Environment.isExternalStorageEmulated(); 12021 } 12022 12023 @Override 12024 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12025 // writer 12026 synchronized (mPackages) { 12027 if (!isExternalMediaAvailable()) { 12028 // If the external storage is no longer mounted at this point, 12029 // the caller may not have been able to delete all of this 12030 // packages files and can not delete any more. Bail. 12031 return null; 12032 } 12033 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12034 if (lastPackage != null) { 12035 pkgs.remove(lastPackage); 12036 } 12037 if (pkgs.size() > 0) { 12038 return pkgs.get(0); 12039 } 12040 } 12041 return null; 12042 } 12043 12044 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12045 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12046 userId, andCode ? 1 : 0, packageName); 12047 if (mSystemReady) { 12048 msg.sendToTarget(); 12049 } else { 12050 if (mPostSystemReadyMessages == null) { 12051 mPostSystemReadyMessages = new ArrayList<>(); 12052 } 12053 mPostSystemReadyMessages.add(msg); 12054 } 12055 } 12056 12057 void startCleaningPackages() { 12058 // reader 12059 if (!isExternalMediaAvailable()) { 12060 return; 12061 } 12062 synchronized (mPackages) { 12063 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12064 return; 12065 } 12066 } 12067 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12068 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12069 IActivityManager am = ActivityManager.getService(); 12070 if (am != null) { 12071 try { 12072 am.startService(null, intent, null, mContext.getOpPackageName(), 12073 UserHandle.USER_SYSTEM); 12074 } catch (RemoteException e) { 12075 } 12076 } 12077 } 12078 12079 @Override 12080 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12081 int installFlags, String installerPackageName, int userId) { 12082 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12083 12084 final int callingUid = Binder.getCallingUid(); 12085 enforceCrossUserPermission(callingUid, userId, 12086 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12087 12088 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12089 try { 12090 if (observer != null) { 12091 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12092 } 12093 } catch (RemoteException re) { 12094 } 12095 return; 12096 } 12097 12098 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12099 installFlags |= PackageManager.INSTALL_FROM_ADB; 12100 12101 } else { 12102 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12103 // about installerPackageName. 12104 12105 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12106 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12107 } 12108 12109 UserHandle user; 12110 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12111 user = UserHandle.ALL; 12112 } else { 12113 user = new UserHandle(userId); 12114 } 12115 12116 // Only system components can circumvent runtime permissions when installing. 12117 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12118 && mContext.checkCallingOrSelfPermission(Manifest.permission 12119 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12120 throw new SecurityException("You need the " 12121 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12122 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12123 } 12124 12125 final File originFile = new File(originPath); 12126 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12127 12128 final Message msg = mHandler.obtainMessage(INIT_COPY); 12129 final VerificationInfo verificationInfo = new VerificationInfo( 12130 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12131 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12132 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12133 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12134 null /*certificates*/); 12135 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12136 msg.obj = params; 12137 12138 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12139 System.identityHashCode(msg.obj)); 12140 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12141 System.identityHashCode(msg.obj)); 12142 12143 mHandler.sendMessage(msg); 12144 } 12145 12146 void installStage(String packageName, File stagedDir, String stagedCid, 12147 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12148 String installerPackageName, int installerUid, UserHandle user, 12149 Certificate[][] certificates) { 12150 if (DEBUG_EPHEMERAL) { 12151 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12152 Slog.d(TAG, "Ephemeral install of " + packageName); 12153 } 12154 } 12155 final VerificationInfo verificationInfo = new VerificationInfo( 12156 sessionParams.originatingUri, sessionParams.referrerUri, 12157 sessionParams.originatingUid, installerUid); 12158 12159 final OriginInfo origin; 12160 if (stagedDir != null) { 12161 origin = OriginInfo.fromStagedFile(stagedDir); 12162 } else { 12163 origin = OriginInfo.fromStagedContainer(stagedCid); 12164 } 12165 12166 final Message msg = mHandler.obtainMessage(INIT_COPY); 12167 final InstallParams params = new InstallParams(origin, null, observer, 12168 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12169 verificationInfo, user, sessionParams.abiOverride, 12170 sessionParams.grantedRuntimePermissions, certificates); 12171 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12172 msg.obj = params; 12173 12174 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12175 System.identityHashCode(msg.obj)); 12176 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12177 System.identityHashCode(msg.obj)); 12178 12179 mHandler.sendMessage(msg); 12180 } 12181 12182 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12183 int userId) { 12184 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12185 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12186 } 12187 12188 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12189 int appId, int... userIds) { 12190 if (ArrayUtils.isEmpty(userIds)) { 12191 return; 12192 } 12193 Bundle extras = new Bundle(1); 12194 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12195 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12196 12197 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12198 packageName, extras, 0, null, null, userIds); 12199 if (isSystem) { 12200 mHandler.post(() -> { 12201 for (int userId : userIds) { 12202 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12203 } 12204 } 12205 ); 12206 } 12207 } 12208 12209 /** 12210 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12211 * automatically without needing an explicit launch. 12212 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12213 */ 12214 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12215 // If user is not running, the app didn't miss any broadcast 12216 if (!mUserManagerInternal.isUserRunning(userId)) { 12217 return; 12218 } 12219 final IActivityManager am = ActivityManager.getService(); 12220 try { 12221 // Deliver LOCKED_BOOT_COMPLETED first 12222 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12223 .setPackage(packageName); 12224 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12225 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12226 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12227 12228 // Deliver BOOT_COMPLETED only if user is unlocked 12229 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12230 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12231 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12232 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12233 } 12234 } catch (RemoteException e) { 12235 throw e.rethrowFromSystemServer(); 12236 } 12237 } 12238 12239 @Override 12240 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12241 int userId) { 12242 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12243 PackageSetting pkgSetting; 12244 final int uid = Binder.getCallingUid(); 12245 enforceCrossUserPermission(uid, userId, 12246 true /* requireFullPermission */, true /* checkShell */, 12247 "setApplicationHiddenSetting for user " + userId); 12248 12249 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12250 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12251 return false; 12252 } 12253 12254 long callingId = Binder.clearCallingIdentity(); 12255 try { 12256 boolean sendAdded = false; 12257 boolean sendRemoved = false; 12258 // writer 12259 synchronized (mPackages) { 12260 pkgSetting = mSettings.mPackages.get(packageName); 12261 if (pkgSetting == null) { 12262 return false; 12263 } 12264 // Do not allow "android" is being disabled 12265 if ("android".equals(packageName)) { 12266 Slog.w(TAG, "Cannot hide package: android"); 12267 return false; 12268 } 12269 // Only allow protected packages to hide themselves. 12270 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12271 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12272 Slog.w(TAG, "Not hiding protected package: " + packageName); 12273 return false; 12274 } 12275 12276 if (pkgSetting.getHidden(userId) != hidden) { 12277 pkgSetting.setHidden(hidden, userId); 12278 mSettings.writePackageRestrictionsLPr(userId); 12279 if (hidden) { 12280 sendRemoved = true; 12281 } else { 12282 sendAdded = true; 12283 } 12284 } 12285 } 12286 if (sendAdded) { 12287 sendPackageAddedForUser(packageName, pkgSetting, userId); 12288 return true; 12289 } 12290 if (sendRemoved) { 12291 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12292 "hiding pkg"); 12293 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12294 return true; 12295 } 12296 } finally { 12297 Binder.restoreCallingIdentity(callingId); 12298 } 12299 return false; 12300 } 12301 12302 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12303 int userId) { 12304 final PackageRemovedInfo info = new PackageRemovedInfo(); 12305 info.removedPackage = packageName; 12306 info.removedUsers = new int[] {userId}; 12307 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12308 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12309 } 12310 12311 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12312 if (pkgList.length > 0) { 12313 Bundle extras = new Bundle(1); 12314 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12315 12316 sendPackageBroadcast( 12317 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12318 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12319 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12320 new int[] {userId}); 12321 } 12322 } 12323 12324 /** 12325 * Returns true if application is not found or there was an error. Otherwise it returns 12326 * the hidden state of the package for the given user. 12327 */ 12328 @Override 12329 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12330 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12331 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12332 true /* requireFullPermission */, false /* checkShell */, 12333 "getApplicationHidden for user " + userId); 12334 PackageSetting pkgSetting; 12335 long callingId = Binder.clearCallingIdentity(); 12336 try { 12337 // writer 12338 synchronized (mPackages) { 12339 pkgSetting = mSettings.mPackages.get(packageName); 12340 if (pkgSetting == null) { 12341 return true; 12342 } 12343 return pkgSetting.getHidden(userId); 12344 } 12345 } finally { 12346 Binder.restoreCallingIdentity(callingId); 12347 } 12348 } 12349 12350 /** 12351 * @hide 12352 */ 12353 @Override 12354 public int installExistingPackageAsUser(String packageName, int userId) { 12355 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12356 null); 12357 PackageSetting pkgSetting; 12358 final int uid = Binder.getCallingUid(); 12359 enforceCrossUserPermission(uid, userId, 12360 true /* requireFullPermission */, true /* checkShell */, 12361 "installExistingPackage for user " + userId); 12362 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12363 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12364 } 12365 12366 long callingId = Binder.clearCallingIdentity(); 12367 try { 12368 boolean installed = false; 12369 12370 // writer 12371 synchronized (mPackages) { 12372 pkgSetting = mSettings.mPackages.get(packageName); 12373 if (pkgSetting == null) { 12374 return PackageManager.INSTALL_FAILED_INVALID_URI; 12375 } 12376 if (!pkgSetting.getInstalled(userId)) { 12377 pkgSetting.setInstalled(true, userId); 12378 pkgSetting.setHidden(false, userId); 12379 mSettings.writePackageRestrictionsLPr(userId); 12380 installed = true; 12381 } 12382 } 12383 12384 if (installed) { 12385 if (pkgSetting.pkg != null) { 12386 synchronized (mInstallLock) { 12387 // We don't need to freeze for a brand new install 12388 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12389 } 12390 } 12391 sendPackageAddedForUser(packageName, pkgSetting, userId); 12392 } 12393 } finally { 12394 Binder.restoreCallingIdentity(callingId); 12395 } 12396 12397 return PackageManager.INSTALL_SUCCEEDED; 12398 } 12399 12400 boolean isUserRestricted(int userId, String restrictionKey) { 12401 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12402 if (restrictions.getBoolean(restrictionKey, false)) { 12403 Log.w(TAG, "User is restricted: " + restrictionKey); 12404 return true; 12405 } 12406 return false; 12407 } 12408 12409 @Override 12410 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12411 int userId) { 12412 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12414 true /* requireFullPermission */, true /* checkShell */, 12415 "setPackagesSuspended for user " + userId); 12416 12417 if (ArrayUtils.isEmpty(packageNames)) { 12418 return packageNames; 12419 } 12420 12421 // List of package names for whom the suspended state has changed. 12422 List<String> changedPackages = new ArrayList<>(packageNames.length); 12423 // List of package names for whom the suspended state is not set as requested in this 12424 // method. 12425 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12426 long callingId = Binder.clearCallingIdentity(); 12427 try { 12428 for (int i = 0; i < packageNames.length; i++) { 12429 String packageName = packageNames[i]; 12430 boolean changed = false; 12431 final int appId; 12432 synchronized (mPackages) { 12433 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12434 if (pkgSetting == null) { 12435 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12436 + "\". Skipping suspending/un-suspending."); 12437 unactionedPackages.add(packageName); 12438 continue; 12439 } 12440 appId = pkgSetting.appId; 12441 if (pkgSetting.getSuspended(userId) != suspended) { 12442 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12443 unactionedPackages.add(packageName); 12444 continue; 12445 } 12446 pkgSetting.setSuspended(suspended, userId); 12447 mSettings.writePackageRestrictionsLPr(userId); 12448 changed = true; 12449 changedPackages.add(packageName); 12450 } 12451 } 12452 12453 if (changed && suspended) { 12454 killApplication(packageName, UserHandle.getUid(userId, appId), 12455 "suspending package"); 12456 } 12457 } 12458 } finally { 12459 Binder.restoreCallingIdentity(callingId); 12460 } 12461 12462 if (!changedPackages.isEmpty()) { 12463 sendPackagesSuspendedForUser(changedPackages.toArray( 12464 new String[changedPackages.size()]), userId, suspended); 12465 } 12466 12467 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12468 } 12469 12470 @Override 12471 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12472 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12473 true /* requireFullPermission */, false /* checkShell */, 12474 "isPackageSuspendedForUser for user " + userId); 12475 synchronized (mPackages) { 12476 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12477 if (pkgSetting == null) { 12478 throw new IllegalArgumentException("Unknown target package: " + packageName); 12479 } 12480 return pkgSetting.getSuspended(userId); 12481 } 12482 } 12483 12484 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12485 if (isPackageDeviceAdmin(packageName, userId)) { 12486 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12487 + "\": has an active device admin"); 12488 return false; 12489 } 12490 12491 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12492 if (packageName.equals(activeLauncherPackageName)) { 12493 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12494 + "\": contains the active launcher"); 12495 return false; 12496 } 12497 12498 if (packageName.equals(mRequiredInstallerPackage)) { 12499 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12500 + "\": required for package installation"); 12501 return false; 12502 } 12503 12504 if (packageName.equals(mRequiredUninstallerPackage)) { 12505 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12506 + "\": required for package uninstallation"); 12507 return false; 12508 } 12509 12510 if (packageName.equals(mRequiredVerifierPackage)) { 12511 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12512 + "\": required for package verification"); 12513 return false; 12514 } 12515 12516 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12517 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12518 + "\": is the default dialer"); 12519 return false; 12520 } 12521 12522 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12523 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12524 + "\": protected package"); 12525 return false; 12526 } 12527 12528 return true; 12529 } 12530 12531 private String getActiveLauncherPackageName(int userId) { 12532 Intent intent = new Intent(Intent.ACTION_MAIN); 12533 intent.addCategory(Intent.CATEGORY_HOME); 12534 ResolveInfo resolveInfo = resolveIntent( 12535 intent, 12536 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12537 PackageManager.MATCH_DEFAULT_ONLY, 12538 userId); 12539 12540 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12541 } 12542 12543 private String getDefaultDialerPackageName(int userId) { 12544 synchronized (mPackages) { 12545 return mSettings.getDefaultDialerPackageNameLPw(userId); 12546 } 12547 } 12548 12549 @Override 12550 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12551 mContext.enforceCallingOrSelfPermission( 12552 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12553 "Only package verification agents can verify applications"); 12554 12555 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12556 final PackageVerificationResponse response = new PackageVerificationResponse( 12557 verificationCode, Binder.getCallingUid()); 12558 msg.arg1 = id; 12559 msg.obj = response; 12560 mHandler.sendMessage(msg); 12561 } 12562 12563 @Override 12564 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12565 long millisecondsToDelay) { 12566 mContext.enforceCallingOrSelfPermission( 12567 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12568 "Only package verification agents can extend verification timeouts"); 12569 12570 final PackageVerificationState state = mPendingVerification.get(id); 12571 final PackageVerificationResponse response = new PackageVerificationResponse( 12572 verificationCodeAtTimeout, Binder.getCallingUid()); 12573 12574 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12575 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12576 } 12577 if (millisecondsToDelay < 0) { 12578 millisecondsToDelay = 0; 12579 } 12580 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12581 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12582 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12583 } 12584 12585 if ((state != null) && !state.timeoutExtended()) { 12586 state.extendTimeout(); 12587 12588 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12589 msg.arg1 = id; 12590 msg.obj = response; 12591 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12592 } 12593 } 12594 12595 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12596 int verificationCode, UserHandle user) { 12597 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12598 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12599 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12600 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12601 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12602 12603 mContext.sendBroadcastAsUser(intent, user, 12604 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12605 } 12606 12607 private ComponentName matchComponentForVerifier(String packageName, 12608 List<ResolveInfo> receivers) { 12609 ActivityInfo targetReceiver = null; 12610 12611 final int NR = receivers.size(); 12612 for (int i = 0; i < NR; i++) { 12613 final ResolveInfo info = receivers.get(i); 12614 if (info.activityInfo == null) { 12615 continue; 12616 } 12617 12618 if (packageName.equals(info.activityInfo.packageName)) { 12619 targetReceiver = info.activityInfo; 12620 break; 12621 } 12622 } 12623 12624 if (targetReceiver == null) { 12625 return null; 12626 } 12627 12628 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12629 } 12630 12631 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12632 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12633 if (pkgInfo.verifiers.length == 0) { 12634 return null; 12635 } 12636 12637 final int N = pkgInfo.verifiers.length; 12638 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12639 for (int i = 0; i < N; i++) { 12640 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12641 12642 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12643 receivers); 12644 if (comp == null) { 12645 continue; 12646 } 12647 12648 final int verifierUid = getUidForVerifier(verifierInfo); 12649 if (verifierUid == -1) { 12650 continue; 12651 } 12652 12653 if (DEBUG_VERIFY) { 12654 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12655 + " with the correct signature"); 12656 } 12657 sufficientVerifiers.add(comp); 12658 verificationState.addSufficientVerifier(verifierUid); 12659 } 12660 12661 return sufficientVerifiers; 12662 } 12663 12664 private int getUidForVerifier(VerifierInfo verifierInfo) { 12665 synchronized (mPackages) { 12666 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12667 if (pkg == null) { 12668 return -1; 12669 } else if (pkg.mSignatures.length != 1) { 12670 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12671 + " has more than one signature; ignoring"); 12672 return -1; 12673 } 12674 12675 /* 12676 * If the public key of the package's signature does not match 12677 * our expected public key, then this is a different package and 12678 * we should skip. 12679 */ 12680 12681 final byte[] expectedPublicKey; 12682 try { 12683 final Signature verifierSig = pkg.mSignatures[0]; 12684 final PublicKey publicKey = verifierSig.getPublicKey(); 12685 expectedPublicKey = publicKey.getEncoded(); 12686 } catch (CertificateException e) { 12687 return -1; 12688 } 12689 12690 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12691 12692 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12693 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12694 + " does not have the expected public key; ignoring"); 12695 return -1; 12696 } 12697 12698 return pkg.applicationInfo.uid; 12699 } 12700 } 12701 12702 @Override 12703 public void finishPackageInstall(int token, boolean didLaunch) { 12704 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12705 12706 if (DEBUG_INSTALL) { 12707 Slog.v(TAG, "BM finishing package install for " + token); 12708 } 12709 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12710 12711 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12712 mHandler.sendMessage(msg); 12713 } 12714 12715 /** 12716 * Get the verification agent timeout. 12717 * 12718 * @return verification timeout in milliseconds 12719 */ 12720 private long getVerificationTimeout() { 12721 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12722 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12723 DEFAULT_VERIFICATION_TIMEOUT); 12724 } 12725 12726 /** 12727 * Get the default verification agent response code. 12728 * 12729 * @return default verification response code 12730 */ 12731 private int getDefaultVerificationResponse() { 12732 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12733 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12734 DEFAULT_VERIFICATION_RESPONSE); 12735 } 12736 12737 /** 12738 * Check whether or not package verification has been enabled. 12739 * 12740 * @return true if verification should be performed 12741 */ 12742 private boolean isVerificationEnabled(int userId, int installFlags) { 12743 if (!DEFAULT_VERIFY_ENABLE) { 12744 return false; 12745 } 12746 // Ephemeral apps don't get the full verification treatment 12747 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12748 if (DEBUG_EPHEMERAL) { 12749 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12750 } 12751 return false; 12752 } 12753 12754 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12755 12756 // Check if installing from ADB 12757 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12758 // Do not run verification in a test harness environment 12759 if (ActivityManager.isRunningInTestHarness()) { 12760 return false; 12761 } 12762 if (ensureVerifyAppsEnabled) { 12763 return true; 12764 } 12765 // Check if the developer does not want package verification for ADB installs 12766 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12767 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12768 return false; 12769 } 12770 } 12771 12772 if (ensureVerifyAppsEnabled) { 12773 return true; 12774 } 12775 12776 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12777 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12778 } 12779 12780 @Override 12781 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12782 throws RemoteException { 12783 mContext.enforceCallingOrSelfPermission( 12784 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12785 "Only intentfilter verification agents can verify applications"); 12786 12787 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12788 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12789 Binder.getCallingUid(), verificationCode, failedDomains); 12790 msg.arg1 = id; 12791 msg.obj = response; 12792 mHandler.sendMessage(msg); 12793 } 12794 12795 @Override 12796 public int getIntentVerificationStatus(String packageName, int userId) { 12797 synchronized (mPackages) { 12798 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12799 } 12800 } 12801 12802 @Override 12803 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12804 mContext.enforceCallingOrSelfPermission( 12805 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12806 12807 boolean result = false; 12808 synchronized (mPackages) { 12809 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12810 } 12811 if (result) { 12812 scheduleWritePackageRestrictionsLocked(userId); 12813 } 12814 return result; 12815 } 12816 12817 @Override 12818 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12819 String packageName) { 12820 synchronized (mPackages) { 12821 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12822 } 12823 } 12824 12825 @Override 12826 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12827 if (TextUtils.isEmpty(packageName)) { 12828 return ParceledListSlice.emptyList(); 12829 } 12830 synchronized (mPackages) { 12831 PackageParser.Package pkg = mPackages.get(packageName); 12832 if (pkg == null || pkg.activities == null) { 12833 return ParceledListSlice.emptyList(); 12834 } 12835 final int count = pkg.activities.size(); 12836 ArrayList<IntentFilter> result = new ArrayList<>(); 12837 for (int n=0; n<count; n++) { 12838 PackageParser.Activity activity = pkg.activities.get(n); 12839 if (activity.intents != null && activity.intents.size() > 0) { 12840 result.addAll(activity.intents); 12841 } 12842 } 12843 return new ParceledListSlice<>(result); 12844 } 12845 } 12846 12847 @Override 12848 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12849 mContext.enforceCallingOrSelfPermission( 12850 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12851 12852 synchronized (mPackages) { 12853 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12854 if (packageName != null) { 12855 result |= updateIntentVerificationStatus(packageName, 12856 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12857 userId); 12858 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12859 packageName, userId); 12860 } 12861 return result; 12862 } 12863 } 12864 12865 @Override 12866 public String getDefaultBrowserPackageName(int userId) { 12867 synchronized (mPackages) { 12868 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12869 } 12870 } 12871 12872 /** 12873 * Get the "allow unknown sources" setting. 12874 * 12875 * @return the current "allow unknown sources" setting 12876 */ 12877 private int getUnknownSourcesSettings() { 12878 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12879 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12880 -1); 12881 } 12882 12883 @Override 12884 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12885 final int uid = Binder.getCallingUid(); 12886 // writer 12887 synchronized (mPackages) { 12888 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12889 if (targetPackageSetting == null) { 12890 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12891 } 12892 12893 PackageSetting installerPackageSetting; 12894 if (installerPackageName != null) { 12895 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12896 if (installerPackageSetting == null) { 12897 throw new IllegalArgumentException("Unknown installer package: " 12898 + installerPackageName); 12899 } 12900 } else { 12901 installerPackageSetting = null; 12902 } 12903 12904 Signature[] callerSignature; 12905 Object obj = mSettings.getUserIdLPr(uid); 12906 if (obj != null) { 12907 if (obj instanceof SharedUserSetting) { 12908 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12909 } else if (obj instanceof PackageSetting) { 12910 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12911 } else { 12912 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12913 } 12914 } else { 12915 throw new SecurityException("Unknown calling UID: " + uid); 12916 } 12917 12918 // Verify: can't set installerPackageName to a package that is 12919 // not signed with the same cert as the caller. 12920 if (installerPackageSetting != null) { 12921 if (compareSignatures(callerSignature, 12922 installerPackageSetting.signatures.mSignatures) 12923 != PackageManager.SIGNATURE_MATCH) { 12924 throw new SecurityException( 12925 "Caller does not have same cert as new installer package " 12926 + installerPackageName); 12927 } 12928 } 12929 12930 // Verify: if target already has an installer package, it must 12931 // be signed with the same cert as the caller. 12932 if (targetPackageSetting.installerPackageName != null) { 12933 PackageSetting setting = mSettings.mPackages.get( 12934 targetPackageSetting.installerPackageName); 12935 // If the currently set package isn't valid, then it's always 12936 // okay to change it. 12937 if (setting != null) { 12938 if (compareSignatures(callerSignature, 12939 setting.signatures.mSignatures) 12940 != PackageManager.SIGNATURE_MATCH) { 12941 throw new SecurityException( 12942 "Caller does not have same cert as old installer package " 12943 + targetPackageSetting.installerPackageName); 12944 } 12945 } 12946 } 12947 12948 // Okay! 12949 targetPackageSetting.installerPackageName = installerPackageName; 12950 if (installerPackageName != null) { 12951 mSettings.mInstallerPackages.add(installerPackageName); 12952 } 12953 scheduleWriteSettingsLocked(); 12954 } 12955 } 12956 12957 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12958 // Queue up an async operation since the package installation may take a little while. 12959 mHandler.post(new Runnable() { 12960 public void run() { 12961 mHandler.removeCallbacks(this); 12962 // Result object to be returned 12963 PackageInstalledInfo res = new PackageInstalledInfo(); 12964 res.setReturnCode(currentStatus); 12965 res.uid = -1; 12966 res.pkg = null; 12967 res.removedInfo = null; 12968 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12969 args.doPreInstall(res.returnCode); 12970 synchronized (mInstallLock) { 12971 installPackageTracedLI(args, res); 12972 } 12973 args.doPostInstall(res.returnCode, res.uid); 12974 } 12975 12976 // A restore should be performed at this point if (a) the install 12977 // succeeded, (b) the operation is not an update, and (c) the new 12978 // package has not opted out of backup participation. 12979 final boolean update = res.removedInfo != null 12980 && res.removedInfo.removedPackage != null; 12981 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12982 boolean doRestore = !update 12983 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12984 12985 // Set up the post-install work request bookkeeping. This will be used 12986 // and cleaned up by the post-install event handling regardless of whether 12987 // there's a restore pass performed. Token values are >= 1. 12988 int token; 12989 if (mNextInstallToken < 0) mNextInstallToken = 1; 12990 token = mNextInstallToken++; 12991 12992 PostInstallData data = new PostInstallData(args, res); 12993 mRunningInstalls.put(token, data); 12994 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12995 12996 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12997 // Pass responsibility to the Backup Manager. It will perform a 12998 // restore if appropriate, then pass responsibility back to the 12999 // Package Manager to run the post-install observer callbacks 13000 // and broadcasts. 13001 IBackupManager bm = IBackupManager.Stub.asInterface( 13002 ServiceManager.getService(Context.BACKUP_SERVICE)); 13003 if (bm != null) { 13004 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 13005 + " to BM for possible restore"); 13006 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13007 try { 13008 // TODO: http://b/22388012 13009 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 13010 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 13011 } else { 13012 doRestore = false; 13013 } 13014 } catch (RemoteException e) { 13015 // can't happen; the backup manager is local 13016 } catch (Exception e) { 13017 Slog.e(TAG, "Exception trying to enqueue restore", e); 13018 doRestore = false; 13019 } 13020 } else { 13021 Slog.e(TAG, "Backup Manager not found!"); 13022 doRestore = false; 13023 } 13024 } 13025 13026 if (!doRestore) { 13027 // No restore possible, or the Backup Manager was mysteriously not 13028 // available -- just fire the post-install work request directly. 13029 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 13030 13031 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 13032 13033 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 13034 mHandler.sendMessage(msg); 13035 } 13036 } 13037 }); 13038 } 13039 13040 /** 13041 * Callback from PackageSettings whenever an app is first transitioned out of the 13042 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 13043 * the app was "launched" for a restoreAtInstall operation. Therefore we check 13044 * here whether the app is the target of an ongoing install, and only send the 13045 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13046 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13047 * handling. 13048 */ 13049 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13050 // Serialize this with the rest of the install-process message chain. In the 13051 // restore-at-install case, this Runnable will necessarily run before the 13052 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13053 // are coherent. In the non-restore case, the app has already completed install 13054 // and been launched through some other means, so it is not in a problematic 13055 // state for observers to see the FIRST_LAUNCH signal. 13056 mHandler.post(new Runnable() { 13057 @Override 13058 public void run() { 13059 for (int i = 0; i < mRunningInstalls.size(); i++) { 13060 final PostInstallData data = mRunningInstalls.valueAt(i); 13061 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13062 continue; 13063 } 13064 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13065 // right package; but is it for the right user? 13066 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13067 if (userId == data.res.newUsers[uIndex]) { 13068 if (DEBUG_BACKUP) { 13069 Slog.i(TAG, "Package " + pkgName 13070 + " being restored so deferring FIRST_LAUNCH"); 13071 } 13072 return; 13073 } 13074 } 13075 } 13076 } 13077 // didn't find it, so not being restored 13078 if (DEBUG_BACKUP) { 13079 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13080 } 13081 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13082 } 13083 }); 13084 } 13085 13086 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13087 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13088 installerPkg, null, userIds); 13089 } 13090 13091 private abstract class HandlerParams { 13092 private static final int MAX_RETRIES = 4; 13093 13094 /** 13095 * Number of times startCopy() has been attempted and had a non-fatal 13096 * error. 13097 */ 13098 private int mRetries = 0; 13099 13100 /** User handle for the user requesting the information or installation. */ 13101 private final UserHandle mUser; 13102 String traceMethod; 13103 int traceCookie; 13104 13105 HandlerParams(UserHandle user) { 13106 mUser = user; 13107 } 13108 13109 UserHandle getUser() { 13110 return mUser; 13111 } 13112 13113 HandlerParams setTraceMethod(String traceMethod) { 13114 this.traceMethod = traceMethod; 13115 return this; 13116 } 13117 13118 HandlerParams setTraceCookie(int traceCookie) { 13119 this.traceCookie = traceCookie; 13120 return this; 13121 } 13122 13123 final boolean startCopy() { 13124 boolean res; 13125 try { 13126 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13127 13128 if (++mRetries > MAX_RETRIES) { 13129 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13130 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13131 handleServiceError(); 13132 return false; 13133 } else { 13134 handleStartCopy(); 13135 res = true; 13136 } 13137 } catch (RemoteException e) { 13138 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13139 mHandler.sendEmptyMessage(MCS_RECONNECT); 13140 res = false; 13141 } 13142 handleReturnCode(); 13143 return res; 13144 } 13145 13146 final void serviceError() { 13147 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13148 handleServiceError(); 13149 handleReturnCode(); 13150 } 13151 13152 abstract void handleStartCopy() throws RemoteException; 13153 abstract void handleServiceError(); 13154 abstract void handleReturnCode(); 13155 } 13156 13157 class MeasureParams extends HandlerParams { 13158 private final PackageStats mStats; 13159 private boolean mSuccess; 13160 13161 private final IPackageStatsObserver mObserver; 13162 13163 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 13164 super(new UserHandle(stats.userHandle)); 13165 mObserver = observer; 13166 mStats = stats; 13167 } 13168 13169 @Override 13170 public String toString() { 13171 return "MeasureParams{" 13172 + Integer.toHexString(System.identityHashCode(this)) 13173 + " " + mStats.packageName + "}"; 13174 } 13175 13176 @Override 13177 void handleStartCopy() throws RemoteException { 13178 synchronized (mInstallLock) { 13179 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 13180 } 13181 13182 if (mSuccess) { 13183 boolean mounted = false; 13184 try { 13185 final String status = Environment.getExternalStorageState(); 13186 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13187 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13188 } catch (Exception e) { 13189 } 13190 13191 if (mounted) { 13192 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13193 13194 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13195 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13196 13197 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13198 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13199 13200 // Always subtract cache size, since it's a subdirectory 13201 mStats.externalDataSize -= mStats.externalCacheSize; 13202 13203 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13204 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13205 13206 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13207 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13208 } 13209 } 13210 } 13211 13212 @Override 13213 void handleReturnCode() { 13214 if (mObserver != null) { 13215 try { 13216 mObserver.onGetStatsCompleted(mStats, mSuccess); 13217 } catch (RemoteException e) { 13218 Slog.i(TAG, "Observer no longer exists."); 13219 } 13220 } 13221 } 13222 13223 @Override 13224 void handleServiceError() { 13225 Slog.e(TAG, "Could not measure application " + mStats.packageName 13226 + " external storage"); 13227 } 13228 } 13229 13230 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13231 throws RemoteException { 13232 long result = 0; 13233 for (File path : paths) { 13234 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13235 } 13236 return result; 13237 } 13238 13239 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13240 for (File path : paths) { 13241 try { 13242 mcs.clearDirectory(path.getAbsolutePath()); 13243 } catch (RemoteException e) { 13244 } 13245 } 13246 } 13247 13248 static class OriginInfo { 13249 /** 13250 * Location where install is coming from, before it has been 13251 * copied/renamed into place. This could be a single monolithic APK 13252 * file, or a cluster directory. This location may be untrusted. 13253 */ 13254 final File file; 13255 final String cid; 13256 13257 /** 13258 * Flag indicating that {@link #file} or {@link #cid} has already been 13259 * staged, meaning downstream users don't need to defensively copy the 13260 * contents. 13261 */ 13262 final boolean staged; 13263 13264 /** 13265 * Flag indicating that {@link #file} or {@link #cid} is an already 13266 * installed app that is being moved. 13267 */ 13268 final boolean existing; 13269 13270 final String resolvedPath; 13271 final File resolvedFile; 13272 13273 static OriginInfo fromNothing() { 13274 return new OriginInfo(null, null, false, false); 13275 } 13276 13277 static OriginInfo fromUntrustedFile(File file) { 13278 return new OriginInfo(file, null, false, false); 13279 } 13280 13281 static OriginInfo fromExistingFile(File file) { 13282 return new OriginInfo(file, null, false, true); 13283 } 13284 13285 static OriginInfo fromStagedFile(File file) { 13286 return new OriginInfo(file, null, true, false); 13287 } 13288 13289 static OriginInfo fromStagedContainer(String cid) { 13290 return new OriginInfo(null, cid, true, false); 13291 } 13292 13293 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13294 this.file = file; 13295 this.cid = cid; 13296 this.staged = staged; 13297 this.existing = existing; 13298 13299 if (cid != null) { 13300 resolvedPath = PackageHelper.getSdDir(cid); 13301 resolvedFile = new File(resolvedPath); 13302 } else if (file != null) { 13303 resolvedPath = file.getAbsolutePath(); 13304 resolvedFile = file; 13305 } else { 13306 resolvedPath = null; 13307 resolvedFile = null; 13308 } 13309 } 13310 } 13311 13312 static class MoveInfo { 13313 final int moveId; 13314 final String fromUuid; 13315 final String toUuid; 13316 final String packageName; 13317 final String dataAppName; 13318 final int appId; 13319 final String seinfo; 13320 final int targetSdkVersion; 13321 13322 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13323 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13324 this.moveId = moveId; 13325 this.fromUuid = fromUuid; 13326 this.toUuid = toUuid; 13327 this.packageName = packageName; 13328 this.dataAppName = dataAppName; 13329 this.appId = appId; 13330 this.seinfo = seinfo; 13331 this.targetSdkVersion = targetSdkVersion; 13332 } 13333 } 13334 13335 static class VerificationInfo { 13336 /** A constant used to indicate that a uid value is not present. */ 13337 public static final int NO_UID = -1; 13338 13339 /** URI referencing where the package was downloaded from. */ 13340 final Uri originatingUri; 13341 13342 /** HTTP referrer URI associated with the originatingURI. */ 13343 final Uri referrer; 13344 13345 /** UID of the application that the install request originated from. */ 13346 final int originatingUid; 13347 13348 /** UID of application requesting the install */ 13349 final int installerUid; 13350 13351 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13352 this.originatingUri = originatingUri; 13353 this.referrer = referrer; 13354 this.originatingUid = originatingUid; 13355 this.installerUid = installerUid; 13356 } 13357 } 13358 13359 class InstallParams extends HandlerParams { 13360 final OriginInfo origin; 13361 final MoveInfo move; 13362 final IPackageInstallObserver2 observer; 13363 int installFlags; 13364 final String installerPackageName; 13365 final String volumeUuid; 13366 private InstallArgs mArgs; 13367 private int mRet; 13368 final String packageAbiOverride; 13369 final String[] grantedRuntimePermissions; 13370 final VerificationInfo verificationInfo; 13371 final Certificate[][] certificates; 13372 13373 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13374 int installFlags, String installerPackageName, String volumeUuid, 13375 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13376 String[] grantedPermissions, Certificate[][] certificates) { 13377 super(user); 13378 this.origin = origin; 13379 this.move = move; 13380 this.observer = observer; 13381 this.installFlags = installFlags; 13382 this.installerPackageName = installerPackageName; 13383 this.volumeUuid = volumeUuid; 13384 this.verificationInfo = verificationInfo; 13385 this.packageAbiOverride = packageAbiOverride; 13386 this.grantedRuntimePermissions = grantedPermissions; 13387 this.certificates = certificates; 13388 } 13389 13390 @Override 13391 public String toString() { 13392 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13393 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13394 } 13395 13396 private int installLocationPolicy(PackageInfoLite pkgLite) { 13397 String packageName = pkgLite.packageName; 13398 int installLocation = pkgLite.installLocation; 13399 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13400 // reader 13401 synchronized (mPackages) { 13402 // Currently installed package which the new package is attempting to replace or 13403 // null if no such package is installed. 13404 PackageParser.Package installedPkg = mPackages.get(packageName); 13405 // Package which currently owns the data which the new package will own if installed. 13406 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13407 // will be null whereas dataOwnerPkg will contain information about the package 13408 // which was uninstalled while keeping its data. 13409 PackageParser.Package dataOwnerPkg = installedPkg; 13410 if (dataOwnerPkg == null) { 13411 PackageSetting ps = mSettings.mPackages.get(packageName); 13412 if (ps != null) { 13413 dataOwnerPkg = ps.pkg; 13414 } 13415 } 13416 13417 if (dataOwnerPkg != null) { 13418 // If installed, the package will get access to data left on the device by its 13419 // predecessor. As a security measure, this is permited only if this is not a 13420 // version downgrade or if the predecessor package is marked as debuggable and 13421 // a downgrade is explicitly requested. 13422 // 13423 // On debuggable platform builds, downgrades are permitted even for 13424 // non-debuggable packages to make testing easier. Debuggable platform builds do 13425 // not offer security guarantees and thus it's OK to disable some security 13426 // mechanisms to make debugging/testing easier on those builds. However, even on 13427 // debuggable builds downgrades of packages are permitted only if requested via 13428 // installFlags. This is because we aim to keep the behavior of debuggable 13429 // platform builds as close as possible to the behavior of non-debuggable 13430 // platform builds. 13431 final boolean downgradeRequested = 13432 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13433 final boolean packageDebuggable = 13434 (dataOwnerPkg.applicationInfo.flags 13435 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13436 final boolean downgradePermitted = 13437 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13438 if (!downgradePermitted) { 13439 try { 13440 checkDowngrade(dataOwnerPkg, pkgLite); 13441 } catch (PackageManagerException e) { 13442 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13443 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13444 } 13445 } 13446 } 13447 13448 if (installedPkg != null) { 13449 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13450 // Check for updated system application. 13451 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13452 if (onSd) { 13453 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13454 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13455 } 13456 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13457 } else { 13458 if (onSd) { 13459 // Install flag overrides everything. 13460 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13461 } 13462 // If current upgrade specifies particular preference 13463 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13464 // Application explicitly specified internal. 13465 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13466 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13467 // App explictly prefers external. Let policy decide 13468 } else { 13469 // Prefer previous location 13470 if (isExternal(installedPkg)) { 13471 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13472 } 13473 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13474 } 13475 } 13476 } else { 13477 // Invalid install. Return error code 13478 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13479 } 13480 } 13481 } 13482 // All the special cases have been taken care of. 13483 // Return result based on recommended install location. 13484 if (onSd) { 13485 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13486 } 13487 return pkgLite.recommendedInstallLocation; 13488 } 13489 13490 /* 13491 * Invoke remote method to get package information and install 13492 * location values. Override install location based on default 13493 * policy if needed and then create install arguments based 13494 * on the install location. 13495 */ 13496 public void handleStartCopy() throws RemoteException { 13497 int ret = PackageManager.INSTALL_SUCCEEDED; 13498 13499 // If we're already staged, we've firmly committed to an install location 13500 if (origin.staged) { 13501 if (origin.file != null) { 13502 installFlags |= PackageManager.INSTALL_INTERNAL; 13503 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13504 } else if (origin.cid != null) { 13505 installFlags |= PackageManager.INSTALL_EXTERNAL; 13506 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13507 } else { 13508 throw new IllegalStateException("Invalid stage location"); 13509 } 13510 } 13511 13512 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13513 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13514 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13515 PackageInfoLite pkgLite = null; 13516 13517 if (onInt && onSd) { 13518 // Check if both bits are set. 13519 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13520 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13521 } else if (onSd && ephemeral) { 13522 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13523 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13524 } else { 13525 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13526 packageAbiOverride); 13527 13528 if (DEBUG_EPHEMERAL && ephemeral) { 13529 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13530 } 13531 13532 /* 13533 * If we have too little free space, try to free cache 13534 * before giving up. 13535 */ 13536 if (!origin.staged && pkgLite.recommendedInstallLocation 13537 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13538 // TODO: focus freeing disk space on the target device 13539 final StorageManager storage = StorageManager.from(mContext); 13540 final long lowThreshold = storage.getStorageLowBytes( 13541 Environment.getDataDirectory()); 13542 13543 final long sizeBytes = mContainerService.calculateInstalledSize( 13544 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13545 13546 try { 13547 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13548 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13549 installFlags, packageAbiOverride); 13550 } catch (InstallerException e) { 13551 Slog.w(TAG, "Failed to free cache", e); 13552 } 13553 13554 /* 13555 * The cache free must have deleted the file we 13556 * downloaded to install. 13557 * 13558 * TODO: fix the "freeCache" call to not delete 13559 * the file we care about. 13560 */ 13561 if (pkgLite.recommendedInstallLocation 13562 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13563 pkgLite.recommendedInstallLocation 13564 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13565 } 13566 } 13567 } 13568 13569 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13570 int loc = pkgLite.recommendedInstallLocation; 13571 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13572 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13573 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13574 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13575 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13576 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13577 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13578 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13579 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13580 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13581 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13582 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13583 } else { 13584 // Override with defaults if needed. 13585 loc = installLocationPolicy(pkgLite); 13586 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13587 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13588 } else if (!onSd && !onInt) { 13589 // Override install location with flags 13590 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13591 // Set the flag to install on external media. 13592 installFlags |= PackageManager.INSTALL_EXTERNAL; 13593 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13594 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13595 if (DEBUG_EPHEMERAL) { 13596 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13597 } 13598 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13599 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13600 |PackageManager.INSTALL_INTERNAL); 13601 } else { 13602 // Make sure the flag for installing on external 13603 // media is unset 13604 installFlags |= PackageManager.INSTALL_INTERNAL; 13605 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13606 } 13607 } 13608 } 13609 } 13610 13611 final InstallArgs args = createInstallArgs(this); 13612 mArgs = args; 13613 13614 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13615 // TODO: http://b/22976637 13616 // Apps installed for "all" users use the device owner to verify the app 13617 UserHandle verifierUser = getUser(); 13618 if (verifierUser == UserHandle.ALL) { 13619 verifierUser = UserHandle.SYSTEM; 13620 } 13621 13622 /* 13623 * Determine if we have any installed package verifiers. If we 13624 * do, then we'll defer to them to verify the packages. 13625 */ 13626 final int requiredUid = mRequiredVerifierPackage == null ? -1 13627 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13628 verifierUser.getIdentifier()); 13629 if (!origin.existing && requiredUid != -1 13630 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13631 final Intent verification = new Intent( 13632 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13633 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13634 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13635 PACKAGE_MIME_TYPE); 13636 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13637 13638 // Query all live verifiers based on current user state 13639 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13640 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13641 13642 if (DEBUG_VERIFY) { 13643 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13644 + verification.toString() + " with " + pkgLite.verifiers.length 13645 + " optional verifiers"); 13646 } 13647 13648 final int verificationId = mPendingVerificationToken++; 13649 13650 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13651 13652 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13653 installerPackageName); 13654 13655 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13656 installFlags); 13657 13658 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13659 pkgLite.packageName); 13660 13661 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13662 pkgLite.versionCode); 13663 13664 if (verificationInfo != null) { 13665 if (verificationInfo.originatingUri != null) { 13666 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13667 verificationInfo.originatingUri); 13668 } 13669 if (verificationInfo.referrer != null) { 13670 verification.putExtra(Intent.EXTRA_REFERRER, 13671 verificationInfo.referrer); 13672 } 13673 if (verificationInfo.originatingUid >= 0) { 13674 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13675 verificationInfo.originatingUid); 13676 } 13677 if (verificationInfo.installerUid >= 0) { 13678 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13679 verificationInfo.installerUid); 13680 } 13681 } 13682 13683 final PackageVerificationState verificationState = new PackageVerificationState( 13684 requiredUid, args); 13685 13686 mPendingVerification.append(verificationId, verificationState); 13687 13688 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13689 receivers, verificationState); 13690 13691 /* 13692 * If any sufficient verifiers were listed in the package 13693 * manifest, attempt to ask them. 13694 */ 13695 if (sufficientVerifiers != null) { 13696 final int N = sufficientVerifiers.size(); 13697 if (N == 0) { 13698 Slog.i(TAG, "Additional verifiers required, but none installed."); 13699 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13700 } else { 13701 for (int i = 0; i < N; i++) { 13702 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13703 13704 final Intent sufficientIntent = new Intent(verification); 13705 sufficientIntent.setComponent(verifierComponent); 13706 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13707 } 13708 } 13709 } 13710 13711 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13712 mRequiredVerifierPackage, receivers); 13713 if (ret == PackageManager.INSTALL_SUCCEEDED 13714 && mRequiredVerifierPackage != null) { 13715 Trace.asyncTraceBegin( 13716 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13717 /* 13718 * Send the intent to the required verification agent, 13719 * but only start the verification timeout after the 13720 * target BroadcastReceivers have run. 13721 */ 13722 verification.setComponent(requiredVerifierComponent); 13723 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13724 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13725 new BroadcastReceiver() { 13726 @Override 13727 public void onReceive(Context context, Intent intent) { 13728 final Message msg = mHandler 13729 .obtainMessage(CHECK_PENDING_VERIFICATION); 13730 msg.arg1 = verificationId; 13731 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13732 } 13733 }, null, 0, null, null); 13734 13735 /* 13736 * We don't want the copy to proceed until verification 13737 * succeeds, so null out this field. 13738 */ 13739 mArgs = null; 13740 } 13741 } else { 13742 /* 13743 * No package verification is enabled, so immediately start 13744 * the remote call to initiate copy using temporary file. 13745 */ 13746 ret = args.copyApk(mContainerService, true); 13747 } 13748 } 13749 13750 mRet = ret; 13751 } 13752 13753 @Override 13754 void handleReturnCode() { 13755 // If mArgs is null, then MCS couldn't be reached. When it 13756 // reconnects, it will try again to install. At that point, this 13757 // will succeed. 13758 if (mArgs != null) { 13759 processPendingInstall(mArgs, mRet); 13760 } 13761 } 13762 13763 @Override 13764 void handleServiceError() { 13765 mArgs = createInstallArgs(this); 13766 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13767 } 13768 13769 public boolean isForwardLocked() { 13770 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13771 } 13772 } 13773 13774 /** 13775 * Used during creation of InstallArgs 13776 * 13777 * @param installFlags package installation flags 13778 * @return true if should be installed on external storage 13779 */ 13780 private static boolean installOnExternalAsec(int installFlags) { 13781 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13782 return false; 13783 } 13784 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13785 return true; 13786 } 13787 return false; 13788 } 13789 13790 /** 13791 * Used during creation of InstallArgs 13792 * 13793 * @param installFlags package installation flags 13794 * @return true if should be installed as forward locked 13795 */ 13796 private static boolean installForwardLocked(int installFlags) { 13797 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13798 } 13799 13800 private InstallArgs createInstallArgs(InstallParams params) { 13801 if (params.move != null) { 13802 return new MoveInstallArgs(params); 13803 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13804 return new AsecInstallArgs(params); 13805 } else { 13806 return new FileInstallArgs(params); 13807 } 13808 } 13809 13810 /** 13811 * Create args that describe an existing installed package. Typically used 13812 * when cleaning up old installs, or used as a move source. 13813 */ 13814 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13815 String resourcePath, String[] instructionSets) { 13816 final boolean isInAsec; 13817 if (installOnExternalAsec(installFlags)) { 13818 /* Apps on SD card are always in ASEC containers. */ 13819 isInAsec = true; 13820 } else if (installForwardLocked(installFlags) 13821 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13822 /* 13823 * Forward-locked apps are only in ASEC containers if they're the 13824 * new style 13825 */ 13826 isInAsec = true; 13827 } else { 13828 isInAsec = false; 13829 } 13830 13831 if (isInAsec) { 13832 return new AsecInstallArgs(codePath, instructionSets, 13833 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13834 } else { 13835 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13836 } 13837 } 13838 13839 static abstract class InstallArgs { 13840 /** @see InstallParams#origin */ 13841 final OriginInfo origin; 13842 /** @see InstallParams#move */ 13843 final MoveInfo move; 13844 13845 final IPackageInstallObserver2 observer; 13846 // Always refers to PackageManager flags only 13847 final int installFlags; 13848 final String installerPackageName; 13849 final String volumeUuid; 13850 final UserHandle user; 13851 final String abiOverride; 13852 final String[] installGrantPermissions; 13853 /** If non-null, drop an async trace when the install completes */ 13854 final String traceMethod; 13855 final int traceCookie; 13856 final Certificate[][] certificates; 13857 13858 // The list of instruction sets supported by this app. This is currently 13859 // only used during the rmdex() phase to clean up resources. We can get rid of this 13860 // if we move dex files under the common app path. 13861 /* nullable */ String[] instructionSets; 13862 13863 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13864 int installFlags, String installerPackageName, String volumeUuid, 13865 UserHandle user, String[] instructionSets, 13866 String abiOverride, String[] installGrantPermissions, 13867 String traceMethod, int traceCookie, Certificate[][] certificates) { 13868 this.origin = origin; 13869 this.move = move; 13870 this.installFlags = installFlags; 13871 this.observer = observer; 13872 this.installerPackageName = installerPackageName; 13873 this.volumeUuid = volumeUuid; 13874 this.user = user; 13875 this.instructionSets = instructionSets; 13876 this.abiOverride = abiOverride; 13877 this.installGrantPermissions = installGrantPermissions; 13878 this.traceMethod = traceMethod; 13879 this.traceCookie = traceCookie; 13880 this.certificates = certificates; 13881 } 13882 13883 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13884 abstract int doPreInstall(int status); 13885 13886 /** 13887 * Rename package into final resting place. All paths on the given 13888 * scanned package should be updated to reflect the rename. 13889 */ 13890 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13891 abstract int doPostInstall(int status, int uid); 13892 13893 /** @see PackageSettingBase#codePathString */ 13894 abstract String getCodePath(); 13895 /** @see PackageSettingBase#resourcePathString */ 13896 abstract String getResourcePath(); 13897 13898 // Need installer lock especially for dex file removal. 13899 abstract void cleanUpResourcesLI(); 13900 abstract boolean doPostDeleteLI(boolean delete); 13901 13902 /** 13903 * Called before the source arguments are copied. This is used mostly 13904 * for MoveParams when it needs to read the source file to put it in the 13905 * destination. 13906 */ 13907 int doPreCopy() { 13908 return PackageManager.INSTALL_SUCCEEDED; 13909 } 13910 13911 /** 13912 * Called after the source arguments are copied. This is used mostly for 13913 * MoveParams when it needs to read the source file to put it in the 13914 * destination. 13915 */ 13916 int doPostCopy(int uid) { 13917 return PackageManager.INSTALL_SUCCEEDED; 13918 } 13919 13920 protected boolean isFwdLocked() { 13921 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13922 } 13923 13924 protected boolean isExternalAsec() { 13925 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13926 } 13927 13928 protected boolean isEphemeral() { 13929 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13930 } 13931 13932 UserHandle getUser() { 13933 return user; 13934 } 13935 } 13936 13937 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13938 if (!allCodePaths.isEmpty()) { 13939 if (instructionSets == null) { 13940 throw new IllegalStateException("instructionSet == null"); 13941 } 13942 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13943 for (String codePath : allCodePaths) { 13944 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13945 try { 13946 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13947 } catch (InstallerException ignored) { 13948 } 13949 } 13950 } 13951 } 13952 } 13953 13954 /** 13955 * Logic to handle installation of non-ASEC applications, including copying 13956 * and renaming logic. 13957 */ 13958 class FileInstallArgs extends InstallArgs { 13959 private File codeFile; 13960 private File resourceFile; 13961 13962 // Example topology: 13963 // /data/app/com.example/base.apk 13964 // /data/app/com.example/split_foo.apk 13965 // /data/app/com.example/lib/arm/libfoo.so 13966 // /data/app/com.example/lib/arm64/libfoo.so 13967 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13968 13969 /** New install */ 13970 FileInstallArgs(InstallParams params) { 13971 super(params.origin, params.move, params.observer, params.installFlags, 13972 params.installerPackageName, params.volumeUuid, 13973 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13974 params.grantedRuntimePermissions, 13975 params.traceMethod, params.traceCookie, params.certificates); 13976 if (isFwdLocked()) { 13977 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13978 } 13979 } 13980 13981 /** Existing install */ 13982 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13983 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13984 null, null, null, 0, null /*certificates*/); 13985 this.codeFile = (codePath != null) ? new File(codePath) : null; 13986 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13987 } 13988 13989 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13990 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13991 try { 13992 return doCopyApk(imcs, temp); 13993 } finally { 13994 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13995 } 13996 } 13997 13998 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13999 if (origin.staged) { 14000 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14001 codeFile = origin.file; 14002 resourceFile = origin.file; 14003 return PackageManager.INSTALL_SUCCEEDED; 14004 } 14005 14006 try { 14007 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14008 final File tempDir = 14009 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14010 codeFile = tempDir; 14011 resourceFile = tempDir; 14012 } catch (IOException e) { 14013 Slog.w(TAG, "Failed to create copy file: " + e); 14014 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14015 } 14016 14017 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14018 @Override 14019 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14020 if (!FileUtils.isValidExtFilename(name)) { 14021 throw new IllegalArgumentException("Invalid filename: " + name); 14022 } 14023 try { 14024 final File file = new File(codeFile, name); 14025 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14026 O_RDWR | O_CREAT, 0644); 14027 Os.chmod(file.getAbsolutePath(), 0644); 14028 return new ParcelFileDescriptor(fd); 14029 } catch (ErrnoException e) { 14030 throw new RemoteException("Failed to open: " + e.getMessage()); 14031 } 14032 } 14033 }; 14034 14035 int ret = PackageManager.INSTALL_SUCCEEDED; 14036 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14037 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14038 Slog.e(TAG, "Failed to copy package"); 14039 return ret; 14040 } 14041 14042 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14043 NativeLibraryHelper.Handle handle = null; 14044 try { 14045 handle = NativeLibraryHelper.Handle.create(codeFile); 14046 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14047 abiOverride); 14048 } catch (IOException e) { 14049 Slog.e(TAG, "Copying native libraries failed", e); 14050 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14051 } finally { 14052 IoUtils.closeQuietly(handle); 14053 } 14054 14055 return ret; 14056 } 14057 14058 int doPreInstall(int status) { 14059 if (status != PackageManager.INSTALL_SUCCEEDED) { 14060 cleanUp(); 14061 } 14062 return status; 14063 } 14064 14065 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14066 if (status != PackageManager.INSTALL_SUCCEEDED) { 14067 cleanUp(); 14068 return false; 14069 } 14070 14071 final File targetDir = codeFile.getParentFile(); 14072 final File beforeCodeFile = codeFile; 14073 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14074 14075 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14076 try { 14077 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14078 } catch (ErrnoException e) { 14079 Slog.w(TAG, "Failed to rename", e); 14080 return false; 14081 } 14082 14083 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14084 Slog.w(TAG, "Failed to restorecon"); 14085 return false; 14086 } 14087 14088 // Reflect the rename internally 14089 codeFile = afterCodeFile; 14090 resourceFile = afterCodeFile; 14091 14092 // Reflect the rename in scanned details 14093 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14094 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14095 afterCodeFile, pkg.baseCodePath)); 14096 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14097 afterCodeFile, pkg.splitCodePaths)); 14098 14099 // Reflect the rename in app info 14100 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14101 pkg.setApplicationInfoCodePath(pkg.codePath); 14102 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14103 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14104 pkg.setApplicationInfoResourcePath(pkg.codePath); 14105 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14106 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14107 14108 return true; 14109 } 14110 14111 int doPostInstall(int status, int uid) { 14112 if (status != PackageManager.INSTALL_SUCCEEDED) { 14113 cleanUp(); 14114 } 14115 return status; 14116 } 14117 14118 @Override 14119 String getCodePath() { 14120 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14121 } 14122 14123 @Override 14124 String getResourcePath() { 14125 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14126 } 14127 14128 private boolean cleanUp() { 14129 if (codeFile == null || !codeFile.exists()) { 14130 return false; 14131 } 14132 14133 removeCodePathLI(codeFile); 14134 14135 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14136 resourceFile.delete(); 14137 } 14138 14139 return true; 14140 } 14141 14142 void cleanUpResourcesLI() { 14143 // Try enumerating all code paths before deleting 14144 List<String> allCodePaths = Collections.EMPTY_LIST; 14145 if (codeFile != null && codeFile.exists()) { 14146 try { 14147 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14148 allCodePaths = pkg.getAllCodePaths(); 14149 } catch (PackageParserException e) { 14150 // Ignored; we tried our best 14151 } 14152 } 14153 14154 cleanUp(); 14155 removeDexFiles(allCodePaths, instructionSets); 14156 } 14157 14158 boolean doPostDeleteLI(boolean delete) { 14159 // XXX err, shouldn't we respect the delete flag? 14160 cleanUpResourcesLI(); 14161 return true; 14162 } 14163 } 14164 14165 private boolean isAsecExternal(String cid) { 14166 final String asecPath = PackageHelper.getSdFilesystem(cid); 14167 return !asecPath.startsWith(mAsecInternalPath); 14168 } 14169 14170 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 14171 PackageManagerException { 14172 if (copyRet < 0) { 14173 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 14174 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 14175 throw new PackageManagerException(copyRet, message); 14176 } 14177 } 14178 } 14179 14180 /** 14181 * Extract the StorageManagerService "container ID" from the full code path of an 14182 * .apk. 14183 */ 14184 static String cidFromCodePath(String fullCodePath) { 14185 int eidx = fullCodePath.lastIndexOf("/"); 14186 String subStr1 = fullCodePath.substring(0, eidx); 14187 int sidx = subStr1.lastIndexOf("/"); 14188 return subStr1.substring(sidx+1, eidx); 14189 } 14190 14191 /** 14192 * Logic to handle installation of ASEC applications, including copying and 14193 * renaming logic. 14194 */ 14195 class AsecInstallArgs extends InstallArgs { 14196 static final String RES_FILE_NAME = "pkg.apk"; 14197 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14198 14199 String cid; 14200 String packagePath; 14201 String resourcePath; 14202 14203 /** New install */ 14204 AsecInstallArgs(InstallParams params) { 14205 super(params.origin, params.move, params.observer, params.installFlags, 14206 params.installerPackageName, params.volumeUuid, 14207 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14208 params.grantedRuntimePermissions, 14209 params.traceMethod, params.traceCookie, params.certificates); 14210 } 14211 14212 /** Existing install */ 14213 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14214 boolean isExternal, boolean isForwardLocked) { 14215 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14216 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14217 instructionSets, null, null, null, 0, null /*certificates*/); 14218 // Hackily pretend we're still looking at a full code path 14219 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14220 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14221 } 14222 14223 // Extract cid from fullCodePath 14224 int eidx = fullCodePath.lastIndexOf("/"); 14225 String subStr1 = fullCodePath.substring(0, eidx); 14226 int sidx = subStr1.lastIndexOf("/"); 14227 cid = subStr1.substring(sidx+1, eidx); 14228 setMountPath(subStr1); 14229 } 14230 14231 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14232 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14233 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14234 instructionSets, null, null, null, 0, null /*certificates*/); 14235 this.cid = cid; 14236 setMountPath(PackageHelper.getSdDir(cid)); 14237 } 14238 14239 void createCopyFile() { 14240 cid = mInstallerService.allocateExternalStageCidLegacy(); 14241 } 14242 14243 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14244 if (origin.staged && origin.cid != null) { 14245 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14246 cid = origin.cid; 14247 setMountPath(PackageHelper.getSdDir(cid)); 14248 return PackageManager.INSTALL_SUCCEEDED; 14249 } 14250 14251 if (temp) { 14252 createCopyFile(); 14253 } else { 14254 /* 14255 * Pre-emptively destroy the container since it's destroyed if 14256 * copying fails due to it existing anyway. 14257 */ 14258 PackageHelper.destroySdDir(cid); 14259 } 14260 14261 final String newMountPath = imcs.copyPackageToContainer( 14262 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14263 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14264 14265 if (newMountPath != null) { 14266 setMountPath(newMountPath); 14267 return PackageManager.INSTALL_SUCCEEDED; 14268 } else { 14269 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14270 } 14271 } 14272 14273 @Override 14274 String getCodePath() { 14275 return packagePath; 14276 } 14277 14278 @Override 14279 String getResourcePath() { 14280 return resourcePath; 14281 } 14282 14283 int doPreInstall(int status) { 14284 if (status != PackageManager.INSTALL_SUCCEEDED) { 14285 // Destroy container 14286 PackageHelper.destroySdDir(cid); 14287 } else { 14288 boolean mounted = PackageHelper.isContainerMounted(cid); 14289 if (!mounted) { 14290 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14291 Process.SYSTEM_UID); 14292 if (newMountPath != null) { 14293 setMountPath(newMountPath); 14294 } else { 14295 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14296 } 14297 } 14298 } 14299 return status; 14300 } 14301 14302 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14303 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14304 String newMountPath = null; 14305 if (PackageHelper.isContainerMounted(cid)) { 14306 // Unmount the container 14307 if (!PackageHelper.unMountSdDir(cid)) { 14308 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14309 return false; 14310 } 14311 } 14312 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14313 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14314 " which might be stale. Will try to clean up."); 14315 // Clean up the stale container and proceed to recreate. 14316 if (!PackageHelper.destroySdDir(newCacheId)) { 14317 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14318 return false; 14319 } 14320 // Successfully cleaned up stale container. Try to rename again. 14321 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14322 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14323 + " inspite of cleaning it up."); 14324 return false; 14325 } 14326 } 14327 if (!PackageHelper.isContainerMounted(newCacheId)) { 14328 Slog.w(TAG, "Mounting container " + newCacheId); 14329 newMountPath = PackageHelper.mountSdDir(newCacheId, 14330 getEncryptKey(), Process.SYSTEM_UID); 14331 } else { 14332 newMountPath = PackageHelper.getSdDir(newCacheId); 14333 } 14334 if (newMountPath == null) { 14335 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14336 return false; 14337 } 14338 Log.i(TAG, "Succesfully renamed " + cid + 14339 " to " + newCacheId + 14340 " at new path: " + newMountPath); 14341 cid = newCacheId; 14342 14343 final File beforeCodeFile = new File(packagePath); 14344 setMountPath(newMountPath); 14345 final File afterCodeFile = new File(packagePath); 14346 14347 // Reflect the rename in scanned details 14348 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14349 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14350 afterCodeFile, pkg.baseCodePath)); 14351 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14352 afterCodeFile, pkg.splitCodePaths)); 14353 14354 // Reflect the rename in app info 14355 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14356 pkg.setApplicationInfoCodePath(pkg.codePath); 14357 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14358 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14359 pkg.setApplicationInfoResourcePath(pkg.codePath); 14360 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14361 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14362 14363 return true; 14364 } 14365 14366 private void setMountPath(String mountPath) { 14367 final File mountFile = new File(mountPath); 14368 14369 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14370 if (monolithicFile.exists()) { 14371 packagePath = monolithicFile.getAbsolutePath(); 14372 if (isFwdLocked()) { 14373 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14374 } else { 14375 resourcePath = packagePath; 14376 } 14377 } else { 14378 packagePath = mountFile.getAbsolutePath(); 14379 resourcePath = packagePath; 14380 } 14381 } 14382 14383 int doPostInstall(int status, int uid) { 14384 if (status != PackageManager.INSTALL_SUCCEEDED) { 14385 cleanUp(); 14386 } else { 14387 final int groupOwner; 14388 final String protectedFile; 14389 if (isFwdLocked()) { 14390 groupOwner = UserHandle.getSharedAppGid(uid); 14391 protectedFile = RES_FILE_NAME; 14392 } else { 14393 groupOwner = -1; 14394 protectedFile = null; 14395 } 14396 14397 if (uid < Process.FIRST_APPLICATION_UID 14398 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14399 Slog.e(TAG, "Failed to finalize " + cid); 14400 PackageHelper.destroySdDir(cid); 14401 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14402 } 14403 14404 boolean mounted = PackageHelper.isContainerMounted(cid); 14405 if (!mounted) { 14406 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14407 } 14408 } 14409 return status; 14410 } 14411 14412 private void cleanUp() { 14413 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14414 14415 // Destroy secure container 14416 PackageHelper.destroySdDir(cid); 14417 } 14418 14419 private List<String> getAllCodePaths() { 14420 final File codeFile = new File(getCodePath()); 14421 if (codeFile != null && codeFile.exists()) { 14422 try { 14423 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14424 return pkg.getAllCodePaths(); 14425 } catch (PackageParserException e) { 14426 // Ignored; we tried our best 14427 } 14428 } 14429 return Collections.EMPTY_LIST; 14430 } 14431 14432 void cleanUpResourcesLI() { 14433 // Enumerate all code paths before deleting 14434 cleanUpResourcesLI(getAllCodePaths()); 14435 } 14436 14437 private void cleanUpResourcesLI(List<String> allCodePaths) { 14438 cleanUp(); 14439 removeDexFiles(allCodePaths, instructionSets); 14440 } 14441 14442 String getPackageName() { 14443 return getAsecPackageName(cid); 14444 } 14445 14446 boolean doPostDeleteLI(boolean delete) { 14447 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14448 final List<String> allCodePaths = getAllCodePaths(); 14449 boolean mounted = PackageHelper.isContainerMounted(cid); 14450 if (mounted) { 14451 // Unmount first 14452 if (PackageHelper.unMountSdDir(cid)) { 14453 mounted = false; 14454 } 14455 } 14456 if (!mounted && delete) { 14457 cleanUpResourcesLI(allCodePaths); 14458 } 14459 return !mounted; 14460 } 14461 14462 @Override 14463 int doPreCopy() { 14464 if (isFwdLocked()) { 14465 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14466 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14467 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14468 } 14469 } 14470 14471 return PackageManager.INSTALL_SUCCEEDED; 14472 } 14473 14474 @Override 14475 int doPostCopy(int uid) { 14476 if (isFwdLocked()) { 14477 if (uid < Process.FIRST_APPLICATION_UID 14478 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14479 RES_FILE_NAME)) { 14480 Slog.e(TAG, "Failed to finalize " + cid); 14481 PackageHelper.destroySdDir(cid); 14482 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14483 } 14484 } 14485 14486 return PackageManager.INSTALL_SUCCEEDED; 14487 } 14488 } 14489 14490 /** 14491 * Logic to handle movement of existing installed applications. 14492 */ 14493 class MoveInstallArgs extends InstallArgs { 14494 private File codeFile; 14495 private File resourceFile; 14496 14497 /** New install */ 14498 MoveInstallArgs(InstallParams params) { 14499 super(params.origin, params.move, params.observer, params.installFlags, 14500 params.installerPackageName, params.volumeUuid, 14501 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14502 params.grantedRuntimePermissions, 14503 params.traceMethod, params.traceCookie, params.certificates); 14504 } 14505 14506 int copyApk(IMediaContainerService imcs, boolean temp) { 14507 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14508 + move.fromUuid + " to " + move.toUuid); 14509 synchronized (mInstaller) { 14510 try { 14511 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14512 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14513 } catch (InstallerException e) { 14514 Slog.w(TAG, "Failed to move app", e); 14515 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14516 } 14517 } 14518 14519 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14520 resourceFile = codeFile; 14521 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14522 14523 return PackageManager.INSTALL_SUCCEEDED; 14524 } 14525 14526 int doPreInstall(int status) { 14527 if (status != PackageManager.INSTALL_SUCCEEDED) { 14528 cleanUp(move.toUuid); 14529 } 14530 return status; 14531 } 14532 14533 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14534 if (status != PackageManager.INSTALL_SUCCEEDED) { 14535 cleanUp(move.toUuid); 14536 return false; 14537 } 14538 14539 // Reflect the move in app info 14540 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14541 pkg.setApplicationInfoCodePath(pkg.codePath); 14542 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14543 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14544 pkg.setApplicationInfoResourcePath(pkg.codePath); 14545 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14546 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14547 14548 return true; 14549 } 14550 14551 int doPostInstall(int status, int uid) { 14552 if (status == PackageManager.INSTALL_SUCCEEDED) { 14553 cleanUp(move.fromUuid); 14554 } else { 14555 cleanUp(move.toUuid); 14556 } 14557 return status; 14558 } 14559 14560 @Override 14561 String getCodePath() { 14562 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14563 } 14564 14565 @Override 14566 String getResourcePath() { 14567 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14568 } 14569 14570 private boolean cleanUp(String volumeUuid) { 14571 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14572 move.dataAppName); 14573 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14574 final int[] userIds = sUserManager.getUserIds(); 14575 synchronized (mInstallLock) { 14576 // Clean up both app data and code 14577 // All package moves are frozen until finished 14578 for (int userId : userIds) { 14579 try { 14580 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14581 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14582 } catch (InstallerException e) { 14583 Slog.w(TAG, String.valueOf(e)); 14584 } 14585 } 14586 removeCodePathLI(codeFile); 14587 } 14588 return true; 14589 } 14590 14591 void cleanUpResourcesLI() { 14592 throw new UnsupportedOperationException(); 14593 } 14594 14595 boolean doPostDeleteLI(boolean delete) { 14596 throw new UnsupportedOperationException(); 14597 } 14598 } 14599 14600 static String getAsecPackageName(String packageCid) { 14601 int idx = packageCid.lastIndexOf("-"); 14602 if (idx == -1) { 14603 return packageCid; 14604 } 14605 return packageCid.substring(0, idx); 14606 } 14607 14608 // Utility method used to create code paths based on package name and available index. 14609 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14610 String idxStr = ""; 14611 int idx = 1; 14612 // Fall back to default value of idx=1 if prefix is not 14613 // part of oldCodePath 14614 if (oldCodePath != null) { 14615 String subStr = oldCodePath; 14616 // Drop the suffix right away 14617 if (suffix != null && subStr.endsWith(suffix)) { 14618 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14619 } 14620 // If oldCodePath already contains prefix find out the 14621 // ending index to either increment or decrement. 14622 int sidx = subStr.lastIndexOf(prefix); 14623 if (sidx != -1) { 14624 subStr = subStr.substring(sidx + prefix.length()); 14625 if (subStr != null) { 14626 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14627 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14628 } 14629 try { 14630 idx = Integer.parseInt(subStr); 14631 if (idx <= 1) { 14632 idx++; 14633 } else { 14634 idx--; 14635 } 14636 } catch(NumberFormatException e) { 14637 } 14638 } 14639 } 14640 } 14641 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14642 return prefix + idxStr; 14643 } 14644 14645 private File getNextCodePath(File targetDir, String packageName) { 14646 File result; 14647 SecureRandom random = new SecureRandom(); 14648 byte[] bytes = new byte[16]; 14649 do { 14650 random.nextBytes(bytes); 14651 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14652 result = new File(targetDir, packageName + "-" + suffix); 14653 } while (result.exists()); 14654 return result; 14655 } 14656 14657 // Utility method that returns the relative package path with respect 14658 // to the installation directory. Like say for /data/data/com.test-1.apk 14659 // string com.test-1 is returned. 14660 static String deriveCodePathName(String codePath) { 14661 if (codePath == null) { 14662 return null; 14663 } 14664 final File codeFile = new File(codePath); 14665 final String name = codeFile.getName(); 14666 if (codeFile.isDirectory()) { 14667 return name; 14668 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14669 final int lastDot = name.lastIndexOf('.'); 14670 return name.substring(0, lastDot); 14671 } else { 14672 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14673 return null; 14674 } 14675 } 14676 14677 static class PackageInstalledInfo { 14678 String name; 14679 int uid; 14680 // The set of users that originally had this package installed. 14681 int[] origUsers; 14682 // The set of users that now have this package installed. 14683 int[] newUsers; 14684 PackageParser.Package pkg; 14685 int returnCode; 14686 String returnMsg; 14687 PackageRemovedInfo removedInfo; 14688 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14689 14690 public void setError(int code, String msg) { 14691 setReturnCode(code); 14692 setReturnMessage(msg); 14693 Slog.w(TAG, msg); 14694 } 14695 14696 public void setError(String msg, PackageParserException e) { 14697 setReturnCode(e.error); 14698 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14699 Slog.w(TAG, msg, e); 14700 } 14701 14702 public void setError(String msg, PackageManagerException e) { 14703 returnCode = e.error; 14704 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14705 Slog.w(TAG, msg, e); 14706 } 14707 14708 public void setReturnCode(int returnCode) { 14709 this.returnCode = returnCode; 14710 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14711 for (int i = 0; i < childCount; i++) { 14712 addedChildPackages.valueAt(i).returnCode = returnCode; 14713 } 14714 } 14715 14716 private void setReturnMessage(String returnMsg) { 14717 this.returnMsg = returnMsg; 14718 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14719 for (int i = 0; i < childCount; i++) { 14720 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14721 } 14722 } 14723 14724 // In some error cases we want to convey more info back to the observer 14725 String origPackage; 14726 String origPermission; 14727 } 14728 14729 /* 14730 * Install a non-existing package. 14731 */ 14732 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14733 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14734 PackageInstalledInfo res) { 14735 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14736 14737 // Remember this for later, in case we need to rollback this install 14738 String pkgName = pkg.packageName; 14739 14740 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14741 14742 synchronized(mPackages) { 14743 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14744 if (renamedPackage != null) { 14745 // A package with the same name is already installed, though 14746 // it has been renamed to an older name. The package we 14747 // are trying to install should be installed as an update to 14748 // the existing one, but that has not been requested, so bail. 14749 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14750 + " without first uninstalling package running as " 14751 + renamedPackage); 14752 return; 14753 } 14754 if (mPackages.containsKey(pkgName)) { 14755 // Don't allow installation over an existing package with the same name. 14756 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14757 + " without first uninstalling."); 14758 return; 14759 } 14760 } 14761 14762 try { 14763 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14764 System.currentTimeMillis(), user); 14765 14766 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14767 14768 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14769 prepareAppDataAfterInstallLIF(newPackage); 14770 14771 } else { 14772 // Remove package from internal structures, but keep around any 14773 // data that might have already existed 14774 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14775 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14776 } 14777 } catch (PackageManagerException e) { 14778 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14779 } 14780 14781 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14782 } 14783 14784 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14785 // Can't rotate keys during boot or if sharedUser. 14786 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14787 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14788 return false; 14789 } 14790 // app is using upgradeKeySets; make sure all are valid 14791 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14792 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14793 for (int i = 0; i < upgradeKeySets.length; i++) { 14794 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14795 Slog.wtf(TAG, "Package " 14796 + (oldPs.name != null ? oldPs.name : "<null>") 14797 + " contains upgrade-key-set reference to unknown key-set: " 14798 + upgradeKeySets[i] 14799 + " reverting to signatures check."); 14800 return false; 14801 } 14802 } 14803 return true; 14804 } 14805 14806 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14807 // Upgrade keysets are being used. Determine if new package has a superset of the 14808 // required keys. 14809 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14810 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14811 for (int i = 0; i < upgradeKeySets.length; i++) { 14812 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14813 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14814 return true; 14815 } 14816 } 14817 return false; 14818 } 14819 14820 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14821 try (DigestInputStream digestStream = 14822 new DigestInputStream(new FileInputStream(file), digest)) { 14823 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14824 } 14825 } 14826 14827 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14828 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14829 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14830 14831 final PackageParser.Package oldPackage; 14832 final String pkgName = pkg.packageName; 14833 final int[] allUsers; 14834 final int[] installedUsers; 14835 14836 synchronized(mPackages) { 14837 oldPackage = mPackages.get(pkgName); 14838 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14839 14840 // don't allow upgrade to target a release SDK from a pre-release SDK 14841 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14842 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14843 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14844 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14845 if (oldTargetsPreRelease 14846 && !newTargetsPreRelease 14847 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14848 Slog.w(TAG, "Can't install package targeting released sdk"); 14849 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14850 return; 14851 } 14852 14853 // don't allow an upgrade from full to ephemeral 14854 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14855 if (isEphemeral && !oldIsEphemeral) { 14856 // can't downgrade from full to ephemeral 14857 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14858 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14859 return; 14860 } 14861 14862 // verify signatures are valid 14863 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14864 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14865 if (!checkUpgradeKeySetLP(ps, pkg)) { 14866 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14867 "New package not signed by keys specified by upgrade-keysets: " 14868 + pkgName); 14869 return; 14870 } 14871 } else { 14872 // default to original signature matching 14873 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14874 != PackageManager.SIGNATURE_MATCH) { 14875 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14876 "New package has a different signature: " + pkgName); 14877 return; 14878 } 14879 } 14880 14881 // don't allow a system upgrade unless the upgrade hash matches 14882 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14883 byte[] digestBytes = null; 14884 try { 14885 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14886 updateDigest(digest, new File(pkg.baseCodePath)); 14887 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14888 for (String path : pkg.splitCodePaths) { 14889 updateDigest(digest, new File(path)); 14890 } 14891 } 14892 digestBytes = digest.digest(); 14893 } catch (NoSuchAlgorithmException | IOException e) { 14894 res.setError(INSTALL_FAILED_INVALID_APK, 14895 "Could not compute hash: " + pkgName); 14896 return; 14897 } 14898 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14899 res.setError(INSTALL_FAILED_INVALID_APK, 14900 "New package fails restrict-update check: " + pkgName); 14901 return; 14902 } 14903 // retain upgrade restriction 14904 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14905 } 14906 14907 // Check for shared user id changes 14908 String invalidPackageName = 14909 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14910 if (invalidPackageName != null) { 14911 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14912 "Package " + invalidPackageName + " tried to change user " 14913 + oldPackage.mSharedUserId); 14914 return; 14915 } 14916 14917 // In case of rollback, remember per-user/profile install state 14918 allUsers = sUserManager.getUserIds(); 14919 installedUsers = ps.queryInstalledUsers(allUsers, true); 14920 } 14921 14922 // Update what is removed 14923 res.removedInfo = new PackageRemovedInfo(); 14924 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14925 res.removedInfo.removedPackage = oldPackage.packageName; 14926 res.removedInfo.isUpdate = true; 14927 res.removedInfo.origUsers = installedUsers; 14928 final int childCount = (oldPackage.childPackages != null) 14929 ? oldPackage.childPackages.size() : 0; 14930 for (int i = 0; i < childCount; i++) { 14931 boolean childPackageUpdated = false; 14932 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14933 if (res.addedChildPackages != null) { 14934 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14935 if (childRes != null) { 14936 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14937 childRes.removedInfo.removedPackage = childPkg.packageName; 14938 childRes.removedInfo.isUpdate = true; 14939 childPackageUpdated = true; 14940 } 14941 } 14942 if (!childPackageUpdated) { 14943 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14944 childRemovedRes.removedPackage = childPkg.packageName; 14945 childRemovedRes.isUpdate = false; 14946 childRemovedRes.dataRemoved = true; 14947 synchronized (mPackages) { 14948 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14949 if (childPs != null) { 14950 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14951 } 14952 } 14953 if (res.removedInfo.removedChildPackages == null) { 14954 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14955 } 14956 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14957 } 14958 } 14959 14960 boolean sysPkg = (isSystemApp(oldPackage)); 14961 if (sysPkg) { 14962 // Set the system/privileged flags as needed 14963 final boolean privileged = 14964 (oldPackage.applicationInfo.privateFlags 14965 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14966 final int systemPolicyFlags = policyFlags 14967 | PackageParser.PARSE_IS_SYSTEM 14968 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14969 14970 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14971 user, allUsers, installerPackageName, res); 14972 } else { 14973 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14974 user, allUsers, installerPackageName, res); 14975 } 14976 } 14977 14978 public List<String> getPreviousCodePaths(String packageName) { 14979 final PackageSetting ps = mSettings.mPackages.get(packageName); 14980 final List<String> result = new ArrayList<String>(); 14981 if (ps != null && ps.oldCodePaths != null) { 14982 result.addAll(ps.oldCodePaths); 14983 } 14984 return result; 14985 } 14986 14987 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14988 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14989 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14990 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14991 + deletedPackage); 14992 14993 String pkgName = deletedPackage.packageName; 14994 boolean deletedPkg = true; 14995 boolean addedPkg = false; 14996 boolean updatedSettings = false; 14997 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14998 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14999 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15000 15001 final long origUpdateTime = (pkg.mExtras != null) 15002 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15003 15004 // First delete the existing package while retaining the data directory 15005 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15006 res.removedInfo, true, pkg)) { 15007 // If the existing package wasn't successfully deleted 15008 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15009 deletedPkg = false; 15010 } else { 15011 // Successfully deleted the old package; proceed with replace. 15012 15013 // If deleted package lived in a container, give users a chance to 15014 // relinquish resources before killing. 15015 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15016 if (DEBUG_INSTALL) { 15017 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15018 } 15019 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15020 final ArrayList<String> pkgList = new ArrayList<String>(1); 15021 pkgList.add(deletedPackage.applicationInfo.packageName); 15022 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15023 } 15024 15025 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15026 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15027 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15028 15029 try { 15030 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15031 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15032 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15033 15034 // Update the in-memory copy of the previous code paths. 15035 PackageSetting ps = mSettings.mPackages.get(pkgName); 15036 if (!killApp) { 15037 if (ps.oldCodePaths == null) { 15038 ps.oldCodePaths = new ArraySet<>(); 15039 } 15040 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15041 if (deletedPackage.splitCodePaths != null) { 15042 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15043 } 15044 } else { 15045 ps.oldCodePaths = null; 15046 } 15047 if (ps.childPackageNames != null) { 15048 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15049 final String childPkgName = ps.childPackageNames.get(i); 15050 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15051 childPs.oldCodePaths = ps.oldCodePaths; 15052 } 15053 } 15054 prepareAppDataAfterInstallLIF(newPackage); 15055 addedPkg = true; 15056 } catch (PackageManagerException e) { 15057 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15058 } 15059 } 15060 15061 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15062 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15063 15064 // Revert all internal state mutations and added folders for the failed install 15065 if (addedPkg) { 15066 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15067 res.removedInfo, true, null); 15068 } 15069 15070 // Restore the old package 15071 if (deletedPkg) { 15072 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15073 File restoreFile = new File(deletedPackage.codePath); 15074 // Parse old package 15075 boolean oldExternal = isExternal(deletedPackage); 15076 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15077 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15078 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15079 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15080 try { 15081 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15082 null); 15083 } catch (PackageManagerException e) { 15084 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15085 + e.getMessage()); 15086 return; 15087 } 15088 15089 synchronized (mPackages) { 15090 // Ensure the installer package name up to date 15091 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15092 15093 // Update permissions for restored package 15094 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15095 15096 mSettings.writeLPr(); 15097 } 15098 15099 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15100 } 15101 } else { 15102 synchronized (mPackages) { 15103 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15104 if (ps != null) { 15105 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15106 if (res.removedInfo.removedChildPackages != null) { 15107 final int childCount = res.removedInfo.removedChildPackages.size(); 15108 // Iterate in reverse as we may modify the collection 15109 for (int i = childCount - 1; i >= 0; i--) { 15110 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15111 if (res.addedChildPackages.containsKey(childPackageName)) { 15112 res.removedInfo.removedChildPackages.removeAt(i); 15113 } else { 15114 PackageRemovedInfo childInfo = res.removedInfo 15115 .removedChildPackages.valueAt(i); 15116 childInfo.removedForAllUsers = mPackages.get( 15117 childInfo.removedPackage) == null; 15118 } 15119 } 15120 } 15121 } 15122 } 15123 } 15124 } 15125 15126 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15127 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15128 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 15129 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15130 + ", old=" + deletedPackage); 15131 15132 final boolean disabledSystem; 15133 15134 // Remove existing system package 15135 removePackageLI(deletedPackage, true); 15136 15137 synchronized (mPackages) { 15138 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15139 } 15140 if (!disabledSystem) { 15141 // We didn't need to disable the .apk as a current system package, 15142 // which means we are replacing another update that is already 15143 // installed. We need to make sure to delete the older one's .apk. 15144 res.removedInfo.args = createInstallArgsForExisting(0, 15145 deletedPackage.applicationInfo.getCodePath(), 15146 deletedPackage.applicationInfo.getResourcePath(), 15147 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15148 } else { 15149 res.removedInfo.args = null; 15150 } 15151 15152 // Successfully disabled the old package. Now proceed with re-installation 15153 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15154 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15155 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15156 15157 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15158 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15159 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15160 15161 PackageParser.Package newPackage = null; 15162 try { 15163 // Add the package to the internal data structures 15164 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 15165 15166 // Set the update and install times 15167 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15168 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15169 System.currentTimeMillis()); 15170 15171 // Update the package dynamic state if succeeded 15172 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15173 // Now that the install succeeded make sure we remove data 15174 // directories for any child package the update removed. 15175 final int deletedChildCount = (deletedPackage.childPackages != null) 15176 ? deletedPackage.childPackages.size() : 0; 15177 final int newChildCount = (newPackage.childPackages != null) 15178 ? newPackage.childPackages.size() : 0; 15179 for (int i = 0; i < deletedChildCount; i++) { 15180 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15181 boolean childPackageDeleted = true; 15182 for (int j = 0; j < newChildCount; j++) { 15183 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15184 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15185 childPackageDeleted = false; 15186 break; 15187 } 15188 } 15189 if (childPackageDeleted) { 15190 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15191 deletedChildPkg.packageName); 15192 if (ps != null && res.removedInfo.removedChildPackages != null) { 15193 PackageRemovedInfo removedChildRes = res.removedInfo 15194 .removedChildPackages.get(deletedChildPkg.packageName); 15195 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15196 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15197 } 15198 } 15199 } 15200 15201 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15202 prepareAppDataAfterInstallLIF(newPackage); 15203 } 15204 } catch (PackageManagerException e) { 15205 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15206 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15207 } 15208 15209 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15210 // Re installation failed. Restore old information 15211 // Remove new pkg information 15212 if (newPackage != null) { 15213 removeInstalledPackageLI(newPackage, true); 15214 } 15215 // Add back the old system package 15216 try { 15217 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15218 } catch (PackageManagerException e) { 15219 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15220 } 15221 15222 synchronized (mPackages) { 15223 if (disabledSystem) { 15224 enableSystemPackageLPw(deletedPackage); 15225 } 15226 15227 // Ensure the installer package name up to date 15228 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15229 15230 // Update permissions for restored package 15231 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15232 15233 mSettings.writeLPr(); 15234 } 15235 15236 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15237 + " after failed upgrade"); 15238 } 15239 } 15240 15241 /** 15242 * Checks whether the parent or any of the child packages have a change shared 15243 * user. For a package to be a valid update the shred users of the parent and 15244 * the children should match. We may later support changing child shared users. 15245 * @param oldPkg The updated package. 15246 * @param newPkg The update package. 15247 * @return The shared user that change between the versions. 15248 */ 15249 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15250 PackageParser.Package newPkg) { 15251 // Check parent shared user 15252 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15253 return newPkg.packageName; 15254 } 15255 // Check child shared users 15256 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15257 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15258 for (int i = 0; i < newChildCount; i++) { 15259 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15260 // If this child was present, did it have the same shared user? 15261 for (int j = 0; j < oldChildCount; j++) { 15262 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15263 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15264 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15265 return newChildPkg.packageName; 15266 } 15267 } 15268 } 15269 return null; 15270 } 15271 15272 private void removeNativeBinariesLI(PackageSetting ps) { 15273 // Remove the lib path for the parent package 15274 if (ps != null) { 15275 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15276 // Remove the lib path for the child packages 15277 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15278 for (int i = 0; i < childCount; i++) { 15279 PackageSetting childPs = null; 15280 synchronized (mPackages) { 15281 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15282 } 15283 if (childPs != null) { 15284 NativeLibraryHelper.removeNativeBinariesLI(childPs 15285 .legacyNativeLibraryPathString); 15286 } 15287 } 15288 } 15289 } 15290 15291 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15292 // Enable the parent package 15293 mSettings.enableSystemPackageLPw(pkg.packageName); 15294 // Enable the child packages 15295 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15296 for (int i = 0; i < childCount; i++) { 15297 PackageParser.Package childPkg = pkg.childPackages.get(i); 15298 mSettings.enableSystemPackageLPw(childPkg.packageName); 15299 } 15300 } 15301 15302 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15303 PackageParser.Package newPkg) { 15304 // Disable the parent package (parent always replaced) 15305 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15306 // Disable the child packages 15307 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15308 for (int i = 0; i < childCount; i++) { 15309 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15310 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15311 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15312 } 15313 return disabled; 15314 } 15315 15316 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15317 String installerPackageName) { 15318 // Enable the parent package 15319 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15320 // Enable the child packages 15321 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15322 for (int i = 0; i < childCount; i++) { 15323 PackageParser.Package childPkg = pkg.childPackages.get(i); 15324 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15325 } 15326 } 15327 15328 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15329 // Collect all used permissions in the UID 15330 ArraySet<String> usedPermissions = new ArraySet<>(); 15331 final int packageCount = su.packages.size(); 15332 for (int i = 0; i < packageCount; i++) { 15333 PackageSetting ps = su.packages.valueAt(i); 15334 if (ps.pkg == null) { 15335 continue; 15336 } 15337 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15338 for (int j = 0; j < requestedPermCount; j++) { 15339 String permission = ps.pkg.requestedPermissions.get(j); 15340 BasePermission bp = mSettings.mPermissions.get(permission); 15341 if (bp != null) { 15342 usedPermissions.add(permission); 15343 } 15344 } 15345 } 15346 15347 PermissionsState permissionsState = su.getPermissionsState(); 15348 // Prune install permissions 15349 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15350 final int installPermCount = installPermStates.size(); 15351 for (int i = installPermCount - 1; i >= 0; i--) { 15352 PermissionState permissionState = installPermStates.get(i); 15353 if (!usedPermissions.contains(permissionState.getName())) { 15354 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15355 if (bp != null) { 15356 permissionsState.revokeInstallPermission(bp); 15357 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15358 PackageManager.MASK_PERMISSION_FLAGS, 0); 15359 } 15360 } 15361 } 15362 15363 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15364 15365 // Prune runtime permissions 15366 for (int userId : allUserIds) { 15367 List<PermissionState> runtimePermStates = permissionsState 15368 .getRuntimePermissionStates(userId); 15369 final int runtimePermCount = runtimePermStates.size(); 15370 for (int i = runtimePermCount - 1; i >= 0; i--) { 15371 PermissionState permissionState = runtimePermStates.get(i); 15372 if (!usedPermissions.contains(permissionState.getName())) { 15373 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15374 if (bp != null) { 15375 permissionsState.revokeRuntimePermission(bp, userId); 15376 permissionsState.updatePermissionFlags(bp, userId, 15377 PackageManager.MASK_PERMISSION_FLAGS, 0); 15378 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15379 runtimePermissionChangedUserIds, userId); 15380 } 15381 } 15382 } 15383 } 15384 15385 return runtimePermissionChangedUserIds; 15386 } 15387 15388 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15389 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15390 // Update the parent package setting 15391 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15392 res, user); 15393 // Update the child packages setting 15394 final int childCount = (newPackage.childPackages != null) 15395 ? newPackage.childPackages.size() : 0; 15396 for (int i = 0; i < childCount; i++) { 15397 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15398 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15399 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15400 childRes.origUsers, childRes, user); 15401 } 15402 } 15403 15404 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15405 String installerPackageName, int[] allUsers, int[] installedForUsers, 15406 PackageInstalledInfo res, UserHandle user) { 15407 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15408 15409 String pkgName = newPackage.packageName; 15410 synchronized (mPackages) { 15411 //write settings. the installStatus will be incomplete at this stage. 15412 //note that the new package setting would have already been 15413 //added to mPackages. It hasn't been persisted yet. 15414 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15415 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15416 mSettings.writeLPr(); 15417 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15418 } 15419 15420 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15421 synchronized (mPackages) { 15422 updatePermissionsLPw(newPackage.packageName, newPackage, 15423 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15424 ? UPDATE_PERMISSIONS_ALL : 0)); 15425 // For system-bundled packages, we assume that installing an upgraded version 15426 // of the package implies that the user actually wants to run that new code, 15427 // so we enable the package. 15428 PackageSetting ps = mSettings.mPackages.get(pkgName); 15429 final int userId = user.getIdentifier(); 15430 if (ps != null) { 15431 if (isSystemApp(newPackage)) { 15432 if (DEBUG_INSTALL) { 15433 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15434 } 15435 // Enable system package for requested users 15436 if (res.origUsers != null) { 15437 for (int origUserId : res.origUsers) { 15438 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15439 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15440 origUserId, installerPackageName); 15441 } 15442 } 15443 } 15444 // Also convey the prior install/uninstall state 15445 if (allUsers != null && installedForUsers != null) { 15446 for (int currentUserId : allUsers) { 15447 final boolean installed = ArrayUtils.contains( 15448 installedForUsers, currentUserId); 15449 if (DEBUG_INSTALL) { 15450 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15451 } 15452 ps.setInstalled(installed, currentUserId); 15453 } 15454 // these install state changes will be persisted in the 15455 // upcoming call to mSettings.writeLPr(). 15456 } 15457 } 15458 // It's implied that when a user requests installation, they want the app to be 15459 // installed and enabled. 15460 if (userId != UserHandle.USER_ALL) { 15461 ps.setInstalled(true, userId); 15462 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15463 } 15464 } 15465 res.name = pkgName; 15466 res.uid = newPackage.applicationInfo.uid; 15467 res.pkg = newPackage; 15468 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15469 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15470 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15471 //to update install status 15472 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15473 mSettings.writeLPr(); 15474 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15475 } 15476 15477 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15478 } 15479 15480 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15481 try { 15482 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15483 installPackageLI(args, res); 15484 } finally { 15485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15486 } 15487 } 15488 15489 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15490 final int installFlags = args.installFlags; 15491 final String installerPackageName = args.installerPackageName; 15492 final String volumeUuid = args.volumeUuid; 15493 final File tmpPackageFile = new File(args.getCodePath()); 15494 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15495 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15496 || (args.volumeUuid != null)); 15497 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15498 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15499 boolean replace = false; 15500 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15501 if (args.move != null) { 15502 // moving a complete application; perform an initial scan on the new install location 15503 scanFlags |= SCAN_INITIAL; 15504 } 15505 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15506 scanFlags |= SCAN_DONT_KILL_APP; 15507 } 15508 15509 // Result object to be returned 15510 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15511 15512 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15513 15514 // Sanity check 15515 if (ephemeral && (forwardLocked || onExternal)) { 15516 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15517 + " external=" + onExternal); 15518 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15519 return; 15520 } 15521 15522 // Retrieve PackageSettings and parse package 15523 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15524 | PackageParser.PARSE_ENFORCE_CODE 15525 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15526 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15527 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15528 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15529 PackageParser pp = new PackageParser(); 15530 pp.setSeparateProcesses(mSeparateProcesses); 15531 pp.setDisplayMetrics(mMetrics); 15532 15533 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15534 final PackageParser.Package pkg; 15535 try { 15536 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15537 } catch (PackageParserException e) { 15538 res.setError("Failed parse during installPackageLI", e); 15539 return; 15540 } finally { 15541 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15542 } 15543 15544 // Ephemeral apps must have target SDK >= O. 15545 // TODO: Update conditional and error message when O gets locked down 15546 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 15547 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 15548 "Ephemeral apps must have target SDK version of at least O"); 15549 return; 15550 } 15551 15552 // If we are installing a clustered package add results for the children 15553 if (pkg.childPackages != null) { 15554 synchronized (mPackages) { 15555 final int childCount = pkg.childPackages.size(); 15556 for (int i = 0; i < childCount; i++) { 15557 PackageParser.Package childPkg = pkg.childPackages.get(i); 15558 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15559 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15560 childRes.pkg = childPkg; 15561 childRes.name = childPkg.packageName; 15562 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15563 if (childPs != null) { 15564 childRes.origUsers = childPs.queryInstalledUsers( 15565 sUserManager.getUserIds(), true); 15566 } 15567 if ((mPackages.containsKey(childPkg.packageName))) { 15568 childRes.removedInfo = new PackageRemovedInfo(); 15569 childRes.removedInfo.removedPackage = childPkg.packageName; 15570 } 15571 if (res.addedChildPackages == null) { 15572 res.addedChildPackages = new ArrayMap<>(); 15573 } 15574 res.addedChildPackages.put(childPkg.packageName, childRes); 15575 } 15576 } 15577 } 15578 15579 // If package doesn't declare API override, mark that we have an install 15580 // time CPU ABI override. 15581 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15582 pkg.cpuAbiOverride = args.abiOverride; 15583 } 15584 15585 String pkgName = res.name = pkg.packageName; 15586 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15587 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15588 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15589 return; 15590 } 15591 } 15592 15593 try { 15594 // either use what we've been given or parse directly from the APK 15595 if (args.certificates != null) { 15596 try { 15597 PackageParser.populateCertificates(pkg, args.certificates); 15598 } catch (PackageParserException e) { 15599 // there was something wrong with the certificates we were given; 15600 // try to pull them from the APK 15601 PackageParser.collectCertificates(pkg, parseFlags); 15602 } 15603 } else { 15604 PackageParser.collectCertificates(pkg, parseFlags); 15605 } 15606 } catch (PackageParserException e) { 15607 res.setError("Failed collect during installPackageLI", e); 15608 return; 15609 } 15610 15611 // Get rid of all references to package scan path via parser. 15612 pp = null; 15613 String oldCodePath = null; 15614 boolean systemApp = false; 15615 synchronized (mPackages) { 15616 // Check if installing already existing package 15617 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15618 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15619 if (pkg.mOriginalPackages != null 15620 && pkg.mOriginalPackages.contains(oldName) 15621 && mPackages.containsKey(oldName)) { 15622 // This package is derived from an original package, 15623 // and this device has been updating from that original 15624 // name. We must continue using the original name, so 15625 // rename the new package here. 15626 pkg.setPackageName(oldName); 15627 pkgName = pkg.packageName; 15628 replace = true; 15629 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15630 + oldName + " pkgName=" + pkgName); 15631 } else if (mPackages.containsKey(pkgName)) { 15632 // This package, under its official name, already exists 15633 // on the device; we should replace it. 15634 replace = true; 15635 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15636 } 15637 15638 // Child packages are installed through the parent package 15639 if (pkg.parentPackage != null) { 15640 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15641 "Package " + pkg.packageName + " is child of package " 15642 + pkg.parentPackage.parentPackage + ". Child packages " 15643 + "can be updated only through the parent package."); 15644 return; 15645 } 15646 15647 if (replace) { 15648 // Prevent apps opting out from runtime permissions 15649 PackageParser.Package oldPackage = mPackages.get(pkgName); 15650 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15651 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15652 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15653 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15654 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15655 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15656 + " doesn't support runtime permissions but the old" 15657 + " target SDK " + oldTargetSdk + " does."); 15658 return; 15659 } 15660 15661 // Prevent installing of child packages 15662 if (oldPackage.parentPackage != null) { 15663 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15664 "Package " + pkg.packageName + " is child of package " 15665 + oldPackage.parentPackage + ". Child packages " 15666 + "can be updated only through the parent package."); 15667 return; 15668 } 15669 } 15670 } 15671 15672 PackageSetting ps = mSettings.mPackages.get(pkgName); 15673 if (ps != null) { 15674 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15675 15676 // Quick sanity check that we're signed correctly if updating; 15677 // we'll check this again later when scanning, but we want to 15678 // bail early here before tripping over redefined permissions. 15679 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15680 if (!checkUpgradeKeySetLP(ps, pkg)) { 15681 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15682 + pkg.packageName + " upgrade keys do not match the " 15683 + "previously installed version"); 15684 return; 15685 } 15686 } else { 15687 try { 15688 verifySignaturesLP(ps, pkg); 15689 } catch (PackageManagerException e) { 15690 res.setError(e.error, e.getMessage()); 15691 return; 15692 } 15693 } 15694 15695 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15696 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15697 systemApp = (ps.pkg.applicationInfo.flags & 15698 ApplicationInfo.FLAG_SYSTEM) != 0; 15699 } 15700 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15701 } 15702 15703 // Check whether the newly-scanned package wants to define an already-defined perm 15704 int N = pkg.permissions.size(); 15705 for (int i = N-1; i >= 0; i--) { 15706 PackageParser.Permission perm = pkg.permissions.get(i); 15707 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15708 if (bp != null) { 15709 // If the defining package is signed with our cert, it's okay. This 15710 // also includes the "updating the same package" case, of course. 15711 // "updating same package" could also involve key-rotation. 15712 final boolean sigsOk; 15713 if (bp.sourcePackage.equals(pkg.packageName) 15714 && (bp.packageSetting instanceof PackageSetting) 15715 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15716 scanFlags))) { 15717 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15718 } else { 15719 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15720 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15721 } 15722 if (!sigsOk) { 15723 // If the owning package is the system itself, we log but allow 15724 // install to proceed; we fail the install on all other permission 15725 // redefinitions. 15726 if (!bp.sourcePackage.equals("android")) { 15727 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15728 + pkg.packageName + " attempting to redeclare permission " 15729 + perm.info.name + " already owned by " + bp.sourcePackage); 15730 res.origPermission = perm.info.name; 15731 res.origPackage = bp.sourcePackage; 15732 return; 15733 } else { 15734 Slog.w(TAG, "Package " + pkg.packageName 15735 + " attempting to redeclare system permission " 15736 + perm.info.name + "; ignoring new declaration"); 15737 pkg.permissions.remove(i); 15738 } 15739 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 15740 // Prevent apps to change protection level to dangerous from any other 15741 // type as this would allow a privilege escalation where an app adds a 15742 // normal/signature permission in other app's group and later redefines 15743 // it as dangerous leading to the group auto-grant. 15744 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 15745 == PermissionInfo.PROTECTION_DANGEROUS) { 15746 if (bp != null && !bp.isRuntime()) { 15747 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 15748 + "non-runtime permission " + perm.info.name 15749 + " to runtime; keeping old protection level"); 15750 perm.info.protectionLevel = bp.protectionLevel; 15751 } 15752 } 15753 } 15754 } 15755 } 15756 } 15757 15758 if (systemApp) { 15759 if (onExternal) { 15760 // Abort update; system app can't be replaced with app on sdcard 15761 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15762 "Cannot install updates to system apps on sdcard"); 15763 return; 15764 } else if (ephemeral) { 15765 // Abort update; system app can't be replaced with an ephemeral app 15766 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15767 "Cannot update a system app with an ephemeral app"); 15768 return; 15769 } 15770 } 15771 15772 if (args.move != null) { 15773 // We did an in-place move, so dex is ready to roll 15774 scanFlags |= SCAN_NO_DEX; 15775 scanFlags |= SCAN_MOVE; 15776 15777 synchronized (mPackages) { 15778 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15779 if (ps == null) { 15780 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15781 "Missing settings for moved package " + pkgName); 15782 } 15783 15784 // We moved the entire application as-is, so bring over the 15785 // previously derived ABI information. 15786 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15787 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15788 } 15789 15790 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15791 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15792 scanFlags |= SCAN_NO_DEX; 15793 15794 try { 15795 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15796 args.abiOverride : pkg.cpuAbiOverride); 15797 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15798 true /*extractLibs*/, mAppLib32InstallDir); 15799 } catch (PackageManagerException pme) { 15800 Slog.e(TAG, "Error deriving application ABI", pme); 15801 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15802 return; 15803 } 15804 15805 // Shared libraries for the package need to be updated. 15806 synchronized (mPackages) { 15807 try { 15808 updateSharedLibrariesLPr(pkg, null); 15809 } catch (PackageManagerException e) { 15810 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15811 } 15812 } 15813 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15814 // Do not run PackageDexOptimizer through the local performDexOpt 15815 // method because `pkg` may not be in `mPackages` yet. 15816 // 15817 // Also, don't fail application installs if the dexopt step fails. 15818 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15819 null /* instructionSets */, false /* checkProfiles */, 15820 getCompilerFilterForReason(REASON_INSTALL), 15821 getOrCreateCompilerPackageStats(pkg)); 15822 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15823 15824 // Notify BackgroundDexOptService that the package has been changed. 15825 // If this is an update of a package which used to fail to compile, 15826 // BDOS will remove it from its blacklist. 15827 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15828 } 15829 15830 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15831 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15832 return; 15833 } 15834 15835 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15836 15837 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15838 "installPackageLI")) { 15839 if (replace) { 15840 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15841 installerPackageName, res); 15842 } else { 15843 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15844 args.user, installerPackageName, volumeUuid, res); 15845 } 15846 } 15847 synchronized (mPackages) { 15848 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15849 if (ps != null) { 15850 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15851 } 15852 15853 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15854 for (int i = 0; i < childCount; i++) { 15855 PackageParser.Package childPkg = pkg.childPackages.get(i); 15856 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15857 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15858 if (childPs != null) { 15859 childRes.newUsers = childPs.queryInstalledUsers( 15860 sUserManager.getUserIds(), true); 15861 } 15862 } 15863 } 15864 } 15865 15866 private void startIntentFilterVerifications(int userId, boolean replacing, 15867 PackageParser.Package pkg) { 15868 if (mIntentFilterVerifierComponent == null) { 15869 Slog.w(TAG, "No IntentFilter verification will not be done as " 15870 + "there is no IntentFilterVerifier available!"); 15871 return; 15872 } 15873 15874 final int verifierUid = getPackageUid( 15875 mIntentFilterVerifierComponent.getPackageName(), 15876 MATCH_DEBUG_TRIAGED_MISSING, 15877 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15878 15879 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15880 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15881 mHandler.sendMessage(msg); 15882 15883 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15884 for (int i = 0; i < childCount; i++) { 15885 PackageParser.Package childPkg = pkg.childPackages.get(i); 15886 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15887 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15888 mHandler.sendMessage(msg); 15889 } 15890 } 15891 15892 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15893 PackageParser.Package pkg) { 15894 int size = pkg.activities.size(); 15895 if (size == 0) { 15896 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15897 "No activity, so no need to verify any IntentFilter!"); 15898 return; 15899 } 15900 15901 final boolean hasDomainURLs = hasDomainURLs(pkg); 15902 if (!hasDomainURLs) { 15903 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15904 "No domain URLs, so no need to verify any IntentFilter!"); 15905 return; 15906 } 15907 15908 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15909 + " if any IntentFilter from the " + size 15910 + " Activities needs verification ..."); 15911 15912 int count = 0; 15913 final String packageName = pkg.packageName; 15914 15915 synchronized (mPackages) { 15916 // If this is a new install and we see that we've already run verification for this 15917 // package, we have nothing to do: it means the state was restored from backup. 15918 if (!replacing) { 15919 IntentFilterVerificationInfo ivi = 15920 mSettings.getIntentFilterVerificationLPr(packageName); 15921 if (ivi != null) { 15922 if (DEBUG_DOMAIN_VERIFICATION) { 15923 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15924 + ivi.getStatusString()); 15925 } 15926 return; 15927 } 15928 } 15929 15930 // If any filters need to be verified, then all need to be. 15931 boolean needToVerify = false; 15932 for (PackageParser.Activity a : pkg.activities) { 15933 for (ActivityIntentInfo filter : a.intents) { 15934 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15935 if (DEBUG_DOMAIN_VERIFICATION) { 15936 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15937 } 15938 needToVerify = true; 15939 break; 15940 } 15941 } 15942 } 15943 15944 if (needToVerify) { 15945 final int verificationId = mIntentFilterVerificationToken++; 15946 for (PackageParser.Activity a : pkg.activities) { 15947 for (ActivityIntentInfo filter : a.intents) { 15948 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15949 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15950 "Verification needed for IntentFilter:" + filter.toString()); 15951 mIntentFilterVerifier.addOneIntentFilterVerification( 15952 verifierUid, userId, verificationId, filter, packageName); 15953 count++; 15954 } 15955 } 15956 } 15957 } 15958 } 15959 15960 if (count > 0) { 15961 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15962 + " IntentFilter verification" + (count > 1 ? "s" : "") 15963 + " for userId:" + userId); 15964 mIntentFilterVerifier.startVerifications(userId); 15965 } else { 15966 if (DEBUG_DOMAIN_VERIFICATION) { 15967 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15968 } 15969 } 15970 } 15971 15972 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15973 final ComponentName cn = filter.activity.getComponentName(); 15974 final String packageName = cn.getPackageName(); 15975 15976 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15977 packageName); 15978 if (ivi == null) { 15979 return true; 15980 } 15981 int status = ivi.getStatus(); 15982 switch (status) { 15983 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15984 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15985 return true; 15986 15987 default: 15988 // Nothing to do 15989 return false; 15990 } 15991 } 15992 15993 private static boolean isMultiArch(ApplicationInfo info) { 15994 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15995 } 15996 15997 private static boolean isExternal(PackageParser.Package pkg) { 15998 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15999 } 16000 16001 private static boolean isExternal(PackageSetting ps) { 16002 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16003 } 16004 16005 private static boolean isEphemeral(PackageParser.Package pkg) { 16006 return pkg.applicationInfo.isEphemeralApp(); 16007 } 16008 16009 private static boolean isEphemeral(PackageSetting ps) { 16010 return ps.pkg != null && isEphemeral(ps.pkg); 16011 } 16012 16013 private static boolean isSystemApp(PackageParser.Package pkg) { 16014 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 16015 } 16016 16017 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 16018 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16019 } 16020 16021 private static boolean hasDomainURLs(PackageParser.Package pkg) { 16022 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 16023 } 16024 16025 private static boolean isSystemApp(PackageSetting ps) { 16026 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 16027 } 16028 16029 private static boolean isUpdatedSystemApp(PackageSetting ps) { 16030 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 16031 } 16032 16033 private int packageFlagsToInstallFlags(PackageSetting ps) { 16034 int installFlags = 0; 16035 if (isEphemeral(ps)) { 16036 installFlags |= PackageManager.INSTALL_EPHEMERAL; 16037 } 16038 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 16039 // This existing package was an external ASEC install when we have 16040 // the external flag without a UUID 16041 installFlags |= PackageManager.INSTALL_EXTERNAL; 16042 } 16043 if (ps.isForwardLocked()) { 16044 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16045 } 16046 return installFlags; 16047 } 16048 16049 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 16050 if (isExternal(pkg)) { 16051 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16052 return StorageManager.UUID_PRIMARY_PHYSICAL; 16053 } else { 16054 return pkg.volumeUuid; 16055 } 16056 } else { 16057 return StorageManager.UUID_PRIVATE_INTERNAL; 16058 } 16059 } 16060 16061 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16062 if (isExternal(pkg)) { 16063 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16064 return mSettings.getExternalVersion(); 16065 } else { 16066 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16067 } 16068 } else { 16069 return mSettings.getInternalVersion(); 16070 } 16071 } 16072 16073 private void deleteTempPackageFiles() { 16074 final FilenameFilter filter = new FilenameFilter() { 16075 public boolean accept(File dir, String name) { 16076 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16077 } 16078 }; 16079 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16080 file.delete(); 16081 } 16082 } 16083 16084 @Override 16085 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 16086 int flags) { 16087 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 16088 flags); 16089 } 16090 16091 @Override 16092 public void deletePackage(final String packageName, 16093 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16094 mContext.enforceCallingOrSelfPermission( 16095 android.Manifest.permission.DELETE_PACKAGES, null); 16096 Preconditions.checkNotNull(packageName); 16097 Preconditions.checkNotNull(observer); 16098 final int uid = Binder.getCallingUid(); 16099 if (!isOrphaned(packageName) 16100 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 16101 try { 16102 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16103 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16104 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16105 observer.onUserActionRequired(intent); 16106 } catch (RemoteException re) { 16107 } 16108 return; 16109 } 16110 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16111 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16112 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16113 mContext.enforceCallingOrSelfPermission( 16114 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16115 "deletePackage for user " + userId); 16116 } 16117 16118 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16119 try { 16120 observer.onPackageDeleted(packageName, 16121 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16122 } catch (RemoteException re) { 16123 } 16124 return; 16125 } 16126 16127 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 16128 try { 16129 observer.onPackageDeleted(packageName, 16130 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16131 } catch (RemoteException re) { 16132 } 16133 return; 16134 } 16135 16136 if (DEBUG_REMOVE) { 16137 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 16138 + " deleteAllUsers: " + deleteAllUsers ); 16139 } 16140 // Queue up an async operation since the package deletion may take a little while. 16141 mHandler.post(new Runnable() { 16142 public void run() { 16143 mHandler.removeCallbacks(this); 16144 int returnCode; 16145 if (!deleteAllUsers) { 16146 returnCode = deletePackageX(packageName, userId, deleteFlags); 16147 } else { 16148 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 16149 // If nobody is blocking uninstall, proceed with delete for all users 16150 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16151 returnCode = deletePackageX(packageName, userId, deleteFlags); 16152 } else { 16153 // Otherwise uninstall individually for users with blockUninstalls=false 16154 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16155 for (int userId : users) { 16156 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16157 returnCode = deletePackageX(packageName, userId, userFlags); 16158 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16159 Slog.w(TAG, "Package delete failed for user " + userId 16160 + ", returnCode " + returnCode); 16161 } 16162 } 16163 } 16164 // The app has only been marked uninstalled for certain users. 16165 // We still need to report that delete was blocked 16166 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16167 } 16168 } 16169 try { 16170 observer.onPackageDeleted(packageName, returnCode, null); 16171 } catch (RemoteException e) { 16172 Log.i(TAG, "Observer no longer exists."); 16173 } //end catch 16174 } //end run 16175 }); 16176 } 16177 16178 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 16179 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 16180 || callingUid == Process.SYSTEM_UID) { 16181 return true; 16182 } 16183 final int callingUserId = UserHandle.getUserId(callingUid); 16184 // If the caller installed the pkgName, then allow it to silently uninstall. 16185 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 16186 return true; 16187 } 16188 16189 // Allow package verifier to silently uninstall. 16190 if (mRequiredVerifierPackage != null && 16191 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 16192 return true; 16193 } 16194 16195 // Allow package uninstaller to silently uninstall. 16196 if (mRequiredUninstallerPackage != null && 16197 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 16198 return true; 16199 } 16200 16201 // Allow storage manager to silently uninstall. 16202 if (mStorageManagerPackage != null && 16203 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 16204 return true; 16205 } 16206 return false; 16207 } 16208 16209 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16210 int[] result = EMPTY_INT_ARRAY; 16211 for (int userId : userIds) { 16212 if (getBlockUninstallForUser(packageName, userId)) { 16213 result = ArrayUtils.appendInt(result, userId); 16214 } 16215 } 16216 return result; 16217 } 16218 16219 @Override 16220 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16221 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16222 } 16223 16224 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16225 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16226 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16227 try { 16228 if (dpm != null) { 16229 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16230 /* callingUserOnly =*/ false); 16231 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16232 : deviceOwnerComponentName.getPackageName(); 16233 // Does the package contains the device owner? 16234 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16235 // this check is probably not needed, since DO should be registered as a device 16236 // admin on some user too. (Original bug for this: b/17657954) 16237 if (packageName.equals(deviceOwnerPackageName)) { 16238 return true; 16239 } 16240 // Does it contain a device admin for any user? 16241 int[] users; 16242 if (userId == UserHandle.USER_ALL) { 16243 users = sUserManager.getUserIds(); 16244 } else { 16245 users = new int[]{userId}; 16246 } 16247 for (int i = 0; i < users.length; ++i) { 16248 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16249 return true; 16250 } 16251 } 16252 } 16253 } catch (RemoteException e) { 16254 } 16255 return false; 16256 } 16257 16258 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16259 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16260 } 16261 16262 /** 16263 * This method is an internal method that could be get invoked either 16264 * to delete an installed package or to clean up a failed installation. 16265 * After deleting an installed package, a broadcast is sent to notify any 16266 * listeners that the package has been removed. For cleaning up a failed 16267 * installation, the broadcast is not necessary since the package's 16268 * installation wouldn't have sent the initial broadcast either 16269 * The key steps in deleting a package are 16270 * deleting the package information in internal structures like mPackages, 16271 * deleting the packages base directories through installd 16272 * updating mSettings to reflect current status 16273 * persisting settings for later use 16274 * sending a broadcast if necessary 16275 */ 16276 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16277 final PackageRemovedInfo info = new PackageRemovedInfo(); 16278 final boolean res; 16279 16280 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16281 ? UserHandle.USER_ALL : userId; 16282 16283 if (isPackageDeviceAdmin(packageName, removeUser)) { 16284 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16285 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16286 } 16287 16288 PackageSetting uninstalledPs = null; 16289 16290 // for the uninstall-updates case and restricted profiles, remember the per- 16291 // user handle installed state 16292 int[] allUsers; 16293 synchronized (mPackages) { 16294 uninstalledPs = mSettings.mPackages.get(packageName); 16295 if (uninstalledPs == null) { 16296 Slog.w(TAG, "Not removing non-existent package " + packageName); 16297 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16298 } 16299 allUsers = sUserManager.getUserIds(); 16300 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16301 } 16302 16303 final int freezeUser; 16304 if (isUpdatedSystemApp(uninstalledPs) 16305 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16306 // We're downgrading a system app, which will apply to all users, so 16307 // freeze them all during the downgrade 16308 freezeUser = UserHandle.USER_ALL; 16309 } else { 16310 freezeUser = removeUser; 16311 } 16312 16313 synchronized (mInstallLock) { 16314 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16315 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16316 deleteFlags, "deletePackageX")) { 16317 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16318 deleteFlags | REMOVE_CHATTY, info, true, null); 16319 } 16320 synchronized (mPackages) { 16321 if (res) { 16322 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16323 } 16324 } 16325 } 16326 16327 if (res) { 16328 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16329 info.sendPackageRemovedBroadcasts(killApp); 16330 info.sendSystemPackageUpdatedBroadcasts(); 16331 info.sendSystemPackageAppearedBroadcasts(); 16332 } 16333 // Force a gc here. 16334 Runtime.getRuntime().gc(); 16335 // Delete the resources here after sending the broadcast to let 16336 // other processes clean up before deleting resources. 16337 if (info.args != null) { 16338 synchronized (mInstallLock) { 16339 info.args.doPostDeleteLI(true); 16340 } 16341 } 16342 16343 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16344 } 16345 16346 class PackageRemovedInfo { 16347 String removedPackage; 16348 int uid = -1; 16349 int removedAppId = -1; 16350 int[] origUsers; 16351 int[] removedUsers = null; 16352 boolean isRemovedPackageSystemUpdate = false; 16353 boolean isUpdate; 16354 boolean dataRemoved; 16355 boolean removedForAllUsers; 16356 // Clean up resources deleted packages. 16357 InstallArgs args = null; 16358 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16359 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16360 16361 void sendPackageRemovedBroadcasts(boolean killApp) { 16362 sendPackageRemovedBroadcastInternal(killApp); 16363 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16364 for (int i = 0; i < childCount; i++) { 16365 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16366 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16367 } 16368 } 16369 16370 void sendSystemPackageUpdatedBroadcasts() { 16371 if (isRemovedPackageSystemUpdate) { 16372 sendSystemPackageUpdatedBroadcastsInternal(); 16373 final int childCount = (removedChildPackages != null) 16374 ? removedChildPackages.size() : 0; 16375 for (int i = 0; i < childCount; i++) { 16376 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16377 if (childInfo.isRemovedPackageSystemUpdate) { 16378 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16379 } 16380 } 16381 } 16382 } 16383 16384 void sendSystemPackageAppearedBroadcasts() { 16385 final int packageCount = (appearedChildPackages != null) 16386 ? appearedChildPackages.size() : 0; 16387 for (int i = 0; i < packageCount; i++) { 16388 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16389 sendPackageAddedForNewUsers(installedInfo.name, true, 16390 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16391 } 16392 } 16393 16394 private void sendSystemPackageUpdatedBroadcastsInternal() { 16395 Bundle extras = new Bundle(2); 16396 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16397 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16398 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16399 extras, 0, null, null, null); 16400 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16401 extras, 0, null, null, null); 16402 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16403 null, 0, removedPackage, null, null); 16404 } 16405 16406 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16407 Bundle extras = new Bundle(2); 16408 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16409 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16410 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16411 if (isUpdate || isRemovedPackageSystemUpdate) { 16412 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16413 } 16414 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16415 if (removedPackage != null) { 16416 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16417 extras, 0, null, null, removedUsers); 16418 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16419 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16420 removedPackage, extras, 0, null, null, removedUsers); 16421 } 16422 } 16423 if (removedAppId >= 0) { 16424 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16425 removedUsers); 16426 } 16427 } 16428 } 16429 16430 /* 16431 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16432 * flag is not set, the data directory is removed as well. 16433 * make sure this flag is set for partially installed apps. If not its meaningless to 16434 * delete a partially installed application. 16435 */ 16436 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16437 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16438 String packageName = ps.name; 16439 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16440 // Retrieve object to delete permissions for shared user later on 16441 final PackageParser.Package deletedPkg; 16442 final PackageSetting deletedPs; 16443 // reader 16444 synchronized (mPackages) { 16445 deletedPkg = mPackages.get(packageName); 16446 deletedPs = mSettings.mPackages.get(packageName); 16447 if (outInfo != null) { 16448 outInfo.removedPackage = packageName; 16449 outInfo.removedUsers = deletedPs != null 16450 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16451 : null; 16452 } 16453 } 16454 16455 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16456 16457 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16458 final PackageParser.Package resolvedPkg; 16459 if (deletedPkg != null) { 16460 resolvedPkg = deletedPkg; 16461 } else { 16462 // We don't have a parsed package when it lives on an ejected 16463 // adopted storage device, so fake something together 16464 resolvedPkg = new PackageParser.Package(ps.name); 16465 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16466 } 16467 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16468 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16469 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16470 if (outInfo != null) { 16471 outInfo.dataRemoved = true; 16472 } 16473 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16474 } 16475 16476 // writer 16477 synchronized (mPackages) { 16478 if (deletedPs != null) { 16479 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16480 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16481 clearDefaultBrowserIfNeeded(packageName); 16482 if (outInfo != null) { 16483 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16484 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16485 } 16486 updatePermissionsLPw(deletedPs.name, null, 0); 16487 if (deletedPs.sharedUser != null) { 16488 // Remove permissions associated with package. Since runtime 16489 // permissions are per user we have to kill the removed package 16490 // or packages running under the shared user of the removed 16491 // package if revoking the permissions requested only by the removed 16492 // package is successful and this causes a change in gids. 16493 for (int userId : UserManagerService.getInstance().getUserIds()) { 16494 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16495 userId); 16496 if (userIdToKill == UserHandle.USER_ALL 16497 || userIdToKill >= UserHandle.USER_SYSTEM) { 16498 // If gids changed for this user, kill all affected packages. 16499 mHandler.post(new Runnable() { 16500 @Override 16501 public void run() { 16502 // This has to happen with no lock held. 16503 killApplication(deletedPs.name, deletedPs.appId, 16504 KILL_APP_REASON_GIDS_CHANGED); 16505 } 16506 }); 16507 break; 16508 } 16509 } 16510 } 16511 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16512 } 16513 // make sure to preserve per-user disabled state if this removal was just 16514 // a downgrade of a system app to the factory package 16515 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16516 if (DEBUG_REMOVE) { 16517 Slog.d(TAG, "Propagating install state across downgrade"); 16518 } 16519 for (int userId : allUserHandles) { 16520 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16521 if (DEBUG_REMOVE) { 16522 Slog.d(TAG, " user " + userId + " => " + installed); 16523 } 16524 ps.setInstalled(installed, userId); 16525 } 16526 } 16527 } 16528 // can downgrade to reader 16529 if (writeSettings) { 16530 // Save settings now 16531 mSettings.writeLPr(); 16532 } 16533 } 16534 if (outInfo != null) { 16535 // A user ID was deleted here. Go through all users and remove it 16536 // from KeyStore. 16537 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16538 } 16539 } 16540 16541 static boolean locationIsPrivileged(File path) { 16542 try { 16543 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16544 .getCanonicalPath(); 16545 return path.getCanonicalPath().startsWith(privilegedAppDir); 16546 } catch (IOException e) { 16547 Slog.e(TAG, "Unable to access code path " + path); 16548 } 16549 return false; 16550 } 16551 16552 /* 16553 * Tries to delete system package. 16554 */ 16555 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16556 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16557 boolean writeSettings) { 16558 if (deletedPs.parentPackageName != null) { 16559 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16560 return false; 16561 } 16562 16563 final boolean applyUserRestrictions 16564 = (allUserHandles != null) && (outInfo.origUsers != null); 16565 final PackageSetting disabledPs; 16566 // Confirm if the system package has been updated 16567 // An updated system app can be deleted. This will also have to restore 16568 // the system pkg from system partition 16569 // reader 16570 synchronized (mPackages) { 16571 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16572 } 16573 16574 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16575 + " disabledPs=" + disabledPs); 16576 16577 if (disabledPs == null) { 16578 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16579 return false; 16580 } else if (DEBUG_REMOVE) { 16581 Slog.d(TAG, "Deleting system pkg from data partition"); 16582 } 16583 16584 if (DEBUG_REMOVE) { 16585 if (applyUserRestrictions) { 16586 Slog.d(TAG, "Remembering install states:"); 16587 for (int userId : allUserHandles) { 16588 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16589 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16590 } 16591 } 16592 } 16593 16594 // Delete the updated package 16595 outInfo.isRemovedPackageSystemUpdate = true; 16596 if (outInfo.removedChildPackages != null) { 16597 final int childCount = (deletedPs.childPackageNames != null) 16598 ? deletedPs.childPackageNames.size() : 0; 16599 for (int i = 0; i < childCount; i++) { 16600 String childPackageName = deletedPs.childPackageNames.get(i); 16601 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16602 .contains(childPackageName)) { 16603 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16604 childPackageName); 16605 if (childInfo != null) { 16606 childInfo.isRemovedPackageSystemUpdate = true; 16607 } 16608 } 16609 } 16610 } 16611 16612 if (disabledPs.versionCode < deletedPs.versionCode) { 16613 // Delete data for downgrades 16614 flags &= ~PackageManager.DELETE_KEEP_DATA; 16615 } else { 16616 // Preserve data by setting flag 16617 flags |= PackageManager.DELETE_KEEP_DATA; 16618 } 16619 16620 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16621 outInfo, writeSettings, disabledPs.pkg); 16622 if (!ret) { 16623 return false; 16624 } 16625 16626 // writer 16627 synchronized (mPackages) { 16628 // Reinstate the old system package 16629 enableSystemPackageLPw(disabledPs.pkg); 16630 // Remove any native libraries from the upgraded package. 16631 removeNativeBinariesLI(deletedPs); 16632 } 16633 16634 // Install the system package 16635 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16636 int parseFlags = mDefParseFlags 16637 | PackageParser.PARSE_MUST_BE_APK 16638 | PackageParser.PARSE_IS_SYSTEM 16639 | PackageParser.PARSE_IS_SYSTEM_DIR; 16640 if (locationIsPrivileged(disabledPs.codePath)) { 16641 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16642 } 16643 16644 final PackageParser.Package newPkg; 16645 try { 16646 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16647 0 /* currentTime */, null); 16648 } catch (PackageManagerException e) { 16649 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16650 + e.getMessage()); 16651 return false; 16652 } 16653 try { 16654 // update shared libraries for the newly re-installed system package 16655 updateSharedLibrariesLPr(newPkg, null); 16656 } catch (PackageManagerException e) { 16657 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16658 } 16659 16660 prepareAppDataAfterInstallLIF(newPkg); 16661 16662 // writer 16663 synchronized (mPackages) { 16664 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16665 16666 // Propagate the permissions state as we do not want to drop on the floor 16667 // runtime permissions. The update permissions method below will take 16668 // care of removing obsolete permissions and grant install permissions. 16669 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16670 updatePermissionsLPw(newPkg.packageName, newPkg, 16671 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16672 16673 if (applyUserRestrictions) { 16674 if (DEBUG_REMOVE) { 16675 Slog.d(TAG, "Propagating install state across reinstall"); 16676 } 16677 for (int userId : allUserHandles) { 16678 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16679 if (DEBUG_REMOVE) { 16680 Slog.d(TAG, " user " + userId + " => " + installed); 16681 } 16682 ps.setInstalled(installed, userId); 16683 16684 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16685 } 16686 // Regardless of writeSettings we need to ensure that this restriction 16687 // state propagation is persisted 16688 mSettings.writeAllUsersPackageRestrictionsLPr(); 16689 } 16690 // can downgrade to reader here 16691 if (writeSettings) { 16692 mSettings.writeLPr(); 16693 } 16694 } 16695 return true; 16696 } 16697 16698 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16699 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16700 PackageRemovedInfo outInfo, boolean writeSettings, 16701 PackageParser.Package replacingPackage) { 16702 synchronized (mPackages) { 16703 if (outInfo != null) { 16704 outInfo.uid = ps.appId; 16705 } 16706 16707 if (outInfo != null && outInfo.removedChildPackages != null) { 16708 final int childCount = (ps.childPackageNames != null) 16709 ? ps.childPackageNames.size() : 0; 16710 for (int i = 0; i < childCount; i++) { 16711 String childPackageName = ps.childPackageNames.get(i); 16712 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16713 if (childPs == null) { 16714 return false; 16715 } 16716 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16717 childPackageName); 16718 if (childInfo != null) { 16719 childInfo.uid = childPs.appId; 16720 } 16721 } 16722 } 16723 } 16724 16725 // Delete package data from internal structures and also remove data if flag is set 16726 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16727 16728 // Delete the child packages data 16729 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16730 for (int i = 0; i < childCount; i++) { 16731 PackageSetting childPs; 16732 synchronized (mPackages) { 16733 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16734 } 16735 if (childPs != null) { 16736 PackageRemovedInfo childOutInfo = (outInfo != null 16737 && outInfo.removedChildPackages != null) 16738 ? outInfo.removedChildPackages.get(childPs.name) : null; 16739 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16740 && (replacingPackage != null 16741 && !replacingPackage.hasChildPackage(childPs.name)) 16742 ? flags & ~DELETE_KEEP_DATA : flags; 16743 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16744 deleteFlags, writeSettings); 16745 } 16746 } 16747 16748 // Delete application code and resources only for parent packages 16749 if (ps.parentPackageName == null) { 16750 if (deleteCodeAndResources && (outInfo != null)) { 16751 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16752 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16753 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16754 } 16755 } 16756 16757 return true; 16758 } 16759 16760 @Override 16761 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16762 int userId) { 16763 mContext.enforceCallingOrSelfPermission( 16764 android.Manifest.permission.DELETE_PACKAGES, null); 16765 synchronized (mPackages) { 16766 PackageSetting ps = mSettings.mPackages.get(packageName); 16767 if (ps == null) { 16768 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16769 return false; 16770 } 16771 if (!ps.getInstalled(userId)) { 16772 // Can't block uninstall for an app that is not installed or enabled. 16773 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16774 return false; 16775 } 16776 ps.setBlockUninstall(blockUninstall, userId); 16777 mSettings.writePackageRestrictionsLPr(userId); 16778 } 16779 return true; 16780 } 16781 16782 @Override 16783 public boolean getBlockUninstallForUser(String packageName, int userId) { 16784 synchronized (mPackages) { 16785 PackageSetting ps = mSettings.mPackages.get(packageName); 16786 if (ps == null) { 16787 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16788 return false; 16789 } 16790 return ps.getBlockUninstall(userId); 16791 } 16792 } 16793 16794 @Override 16795 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16796 int callingUid = Binder.getCallingUid(); 16797 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16798 throw new SecurityException( 16799 "setRequiredForSystemUser can only be run by the system or root"); 16800 } 16801 synchronized (mPackages) { 16802 PackageSetting ps = mSettings.mPackages.get(packageName); 16803 if (ps == null) { 16804 Log.w(TAG, "Package doesn't exist: " + packageName); 16805 return false; 16806 } 16807 if (systemUserApp) { 16808 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16809 } else { 16810 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16811 } 16812 mSettings.writeLPr(); 16813 } 16814 return true; 16815 } 16816 16817 /* 16818 * This method handles package deletion in general 16819 */ 16820 private boolean deletePackageLIF(String packageName, UserHandle user, 16821 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16822 PackageRemovedInfo outInfo, boolean writeSettings, 16823 PackageParser.Package replacingPackage) { 16824 if (packageName == null) { 16825 Slog.w(TAG, "Attempt to delete null packageName."); 16826 return false; 16827 } 16828 16829 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16830 16831 PackageSetting ps; 16832 16833 synchronized (mPackages) { 16834 ps = mSettings.mPackages.get(packageName); 16835 if (ps == null) { 16836 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16837 return false; 16838 } 16839 16840 if (ps.parentPackageName != null && (!isSystemApp(ps) 16841 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16842 if (DEBUG_REMOVE) { 16843 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16844 + ((user == null) ? UserHandle.USER_ALL : user)); 16845 } 16846 final int removedUserId = (user != null) ? user.getIdentifier() 16847 : UserHandle.USER_ALL; 16848 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16849 return false; 16850 } 16851 markPackageUninstalledForUserLPw(ps, user); 16852 scheduleWritePackageRestrictionsLocked(user); 16853 return true; 16854 } 16855 } 16856 16857 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16858 && user.getIdentifier() != UserHandle.USER_ALL)) { 16859 // The caller is asking that the package only be deleted for a single 16860 // user. To do this, we just mark its uninstalled state and delete 16861 // its data. If this is a system app, we only allow this to happen if 16862 // they have set the special DELETE_SYSTEM_APP which requests different 16863 // semantics than normal for uninstalling system apps. 16864 markPackageUninstalledForUserLPw(ps, user); 16865 16866 if (!isSystemApp(ps)) { 16867 // Do not uninstall the APK if an app should be cached 16868 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16869 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16870 // Other user still have this package installed, so all 16871 // we need to do is clear this user's data and save that 16872 // it is uninstalled. 16873 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16874 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16875 return false; 16876 } 16877 scheduleWritePackageRestrictionsLocked(user); 16878 return true; 16879 } else { 16880 // We need to set it back to 'installed' so the uninstall 16881 // broadcasts will be sent correctly. 16882 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16883 ps.setInstalled(true, user.getIdentifier()); 16884 } 16885 } else { 16886 // This is a system app, so we assume that the 16887 // other users still have this package installed, so all 16888 // we need to do is clear this user's data and save that 16889 // it is uninstalled. 16890 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16891 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16892 return false; 16893 } 16894 scheduleWritePackageRestrictionsLocked(user); 16895 return true; 16896 } 16897 } 16898 16899 // If we are deleting a composite package for all users, keep track 16900 // of result for each child. 16901 if (ps.childPackageNames != null && outInfo != null) { 16902 synchronized (mPackages) { 16903 final int childCount = ps.childPackageNames.size(); 16904 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16905 for (int i = 0; i < childCount; i++) { 16906 String childPackageName = ps.childPackageNames.get(i); 16907 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16908 childInfo.removedPackage = childPackageName; 16909 outInfo.removedChildPackages.put(childPackageName, childInfo); 16910 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16911 if (childPs != null) { 16912 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16913 } 16914 } 16915 } 16916 } 16917 16918 boolean ret = false; 16919 if (isSystemApp(ps)) { 16920 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16921 // When an updated system application is deleted we delete the existing resources 16922 // as well and fall back to existing code in system partition 16923 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16924 } else { 16925 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16926 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16927 outInfo, writeSettings, replacingPackage); 16928 } 16929 16930 // Take a note whether we deleted the package for all users 16931 if (outInfo != null) { 16932 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16933 if (outInfo.removedChildPackages != null) { 16934 synchronized (mPackages) { 16935 final int childCount = outInfo.removedChildPackages.size(); 16936 for (int i = 0; i < childCount; i++) { 16937 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16938 if (childInfo != null) { 16939 childInfo.removedForAllUsers = mPackages.get( 16940 childInfo.removedPackage) == null; 16941 } 16942 } 16943 } 16944 } 16945 // If we uninstalled an update to a system app there may be some 16946 // child packages that appeared as they are declared in the system 16947 // app but were not declared in the update. 16948 if (isSystemApp(ps)) { 16949 synchronized (mPackages) { 16950 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16951 final int childCount = (updatedPs.childPackageNames != null) 16952 ? updatedPs.childPackageNames.size() : 0; 16953 for (int i = 0; i < childCount; i++) { 16954 String childPackageName = updatedPs.childPackageNames.get(i); 16955 if (outInfo.removedChildPackages == null 16956 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16957 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16958 if (childPs == null) { 16959 continue; 16960 } 16961 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16962 installRes.name = childPackageName; 16963 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16964 installRes.pkg = mPackages.get(childPackageName); 16965 installRes.uid = childPs.pkg.applicationInfo.uid; 16966 if (outInfo.appearedChildPackages == null) { 16967 outInfo.appearedChildPackages = new ArrayMap<>(); 16968 } 16969 outInfo.appearedChildPackages.put(childPackageName, installRes); 16970 } 16971 } 16972 } 16973 } 16974 } 16975 16976 return ret; 16977 } 16978 16979 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16980 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16981 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16982 for (int nextUserId : userIds) { 16983 if (DEBUG_REMOVE) { 16984 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16985 } 16986 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16987 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16988 false /*hidden*/, false /*suspended*/, null, null, null, 16989 false /*blockUninstall*/, 16990 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16991 } 16992 } 16993 16994 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16995 PackageRemovedInfo outInfo) { 16996 final PackageParser.Package pkg; 16997 synchronized (mPackages) { 16998 pkg = mPackages.get(ps.name); 16999 } 17000 17001 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 17002 : new int[] {userId}; 17003 for (int nextUserId : userIds) { 17004 if (DEBUG_REMOVE) { 17005 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 17006 + nextUserId); 17007 } 17008 17009 destroyAppDataLIF(pkg, userId, 17010 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17011 destroyAppProfilesLIF(pkg, userId); 17012 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 17013 schedulePackageCleaning(ps.name, nextUserId, false); 17014 synchronized (mPackages) { 17015 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 17016 scheduleWritePackageRestrictionsLocked(nextUserId); 17017 } 17018 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 17019 } 17020 } 17021 17022 if (outInfo != null) { 17023 outInfo.removedPackage = ps.name; 17024 outInfo.removedAppId = ps.appId; 17025 outInfo.removedUsers = userIds; 17026 } 17027 17028 return true; 17029 } 17030 17031 private final class ClearStorageConnection implements ServiceConnection { 17032 IMediaContainerService mContainerService; 17033 17034 @Override 17035 public void onServiceConnected(ComponentName name, IBinder service) { 17036 synchronized (this) { 17037 mContainerService = IMediaContainerService.Stub 17038 .asInterface(Binder.allowBlocking(service)); 17039 notifyAll(); 17040 } 17041 } 17042 17043 @Override 17044 public void onServiceDisconnected(ComponentName name) { 17045 } 17046 } 17047 17048 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 17049 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 17050 17051 final boolean mounted; 17052 if (Environment.isExternalStorageEmulated()) { 17053 mounted = true; 17054 } else { 17055 final String status = Environment.getExternalStorageState(); 17056 17057 mounted = status.equals(Environment.MEDIA_MOUNTED) 17058 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 17059 } 17060 17061 if (!mounted) { 17062 return; 17063 } 17064 17065 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 17066 int[] users; 17067 if (userId == UserHandle.USER_ALL) { 17068 users = sUserManager.getUserIds(); 17069 } else { 17070 users = new int[] { userId }; 17071 } 17072 final ClearStorageConnection conn = new ClearStorageConnection(); 17073 if (mContext.bindServiceAsUser( 17074 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 17075 try { 17076 for (int curUser : users) { 17077 long timeout = SystemClock.uptimeMillis() + 5000; 17078 synchronized (conn) { 17079 long now; 17080 while (conn.mContainerService == null && 17081 (now = SystemClock.uptimeMillis()) < timeout) { 17082 try { 17083 conn.wait(timeout - now); 17084 } catch (InterruptedException e) { 17085 } 17086 } 17087 } 17088 if (conn.mContainerService == null) { 17089 return; 17090 } 17091 17092 final UserEnvironment userEnv = new UserEnvironment(curUser); 17093 clearDirectory(conn.mContainerService, 17094 userEnv.buildExternalStorageAppCacheDirs(packageName)); 17095 if (allData) { 17096 clearDirectory(conn.mContainerService, 17097 userEnv.buildExternalStorageAppDataDirs(packageName)); 17098 clearDirectory(conn.mContainerService, 17099 userEnv.buildExternalStorageAppMediaDirs(packageName)); 17100 } 17101 } 17102 } finally { 17103 mContext.unbindService(conn); 17104 } 17105 } 17106 } 17107 17108 @Override 17109 public void clearApplicationProfileData(String packageName) { 17110 enforceSystemOrRoot("Only the system can clear all profile data"); 17111 17112 final PackageParser.Package pkg; 17113 synchronized (mPackages) { 17114 pkg = mPackages.get(packageName); 17115 } 17116 17117 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 17118 synchronized (mInstallLock) { 17119 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 17120 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 17121 true /* removeBaseMarker */); 17122 } 17123 } 17124 } 17125 17126 @Override 17127 public void clearApplicationUserData(final String packageName, 17128 final IPackageDataObserver observer, final int userId) { 17129 mContext.enforceCallingOrSelfPermission( 17130 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 17131 17132 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17133 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 17134 17135 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 17136 throw new SecurityException("Cannot clear data for a protected package: " 17137 + packageName); 17138 } 17139 // Queue up an async operation since the package deletion may take a little while. 17140 mHandler.post(new Runnable() { 17141 public void run() { 17142 mHandler.removeCallbacks(this); 17143 final boolean succeeded; 17144 try (PackageFreezer freezer = freezePackage(packageName, 17145 "clearApplicationUserData")) { 17146 synchronized (mInstallLock) { 17147 succeeded = clearApplicationUserDataLIF(packageName, userId); 17148 } 17149 clearExternalStorageDataSync(packageName, userId, true); 17150 } 17151 if (succeeded) { 17152 // invoke DeviceStorageMonitor's update method to clear any notifications 17153 DeviceStorageMonitorInternal dsm = LocalServices 17154 .getService(DeviceStorageMonitorInternal.class); 17155 if (dsm != null) { 17156 dsm.checkMemory(); 17157 } 17158 } 17159 if(observer != null) { 17160 try { 17161 observer.onRemoveCompleted(packageName, succeeded); 17162 } catch (RemoteException e) { 17163 Log.i(TAG, "Observer no longer exists."); 17164 } 17165 } //end if observer 17166 } //end run 17167 }); 17168 } 17169 17170 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 17171 if (packageName == null) { 17172 Slog.w(TAG, "Attempt to delete null packageName."); 17173 return false; 17174 } 17175 17176 // Try finding details about the requested package 17177 PackageParser.Package pkg; 17178 synchronized (mPackages) { 17179 pkg = mPackages.get(packageName); 17180 if (pkg == null) { 17181 final PackageSetting ps = mSettings.mPackages.get(packageName); 17182 if (ps != null) { 17183 pkg = ps.pkg; 17184 } 17185 } 17186 17187 if (pkg == null) { 17188 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17189 return false; 17190 } 17191 17192 PackageSetting ps = (PackageSetting) pkg.mExtras; 17193 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17194 } 17195 17196 clearAppDataLIF(pkg, userId, 17197 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17198 17199 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17200 removeKeystoreDataIfNeeded(userId, appId); 17201 17202 UserManagerInternal umInternal = getUserManagerInternal(); 17203 final int flags; 17204 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17205 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17206 } else if (umInternal.isUserRunning(userId)) { 17207 flags = StorageManager.FLAG_STORAGE_DE; 17208 } else { 17209 flags = 0; 17210 } 17211 prepareAppDataContentsLIF(pkg, userId, flags); 17212 17213 return true; 17214 } 17215 17216 /** 17217 * Reverts user permission state changes (permissions and flags) in 17218 * all packages for a given user. 17219 * 17220 * @param userId The device user for which to do a reset. 17221 */ 17222 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17223 final int packageCount = mPackages.size(); 17224 for (int i = 0; i < packageCount; i++) { 17225 PackageParser.Package pkg = mPackages.valueAt(i); 17226 PackageSetting ps = (PackageSetting) pkg.mExtras; 17227 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17228 } 17229 } 17230 17231 private void resetNetworkPolicies(int userId) { 17232 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17233 } 17234 17235 /** 17236 * Reverts user permission state changes (permissions and flags). 17237 * 17238 * @param ps The package for which to reset. 17239 * @param userId The device user for which to do a reset. 17240 */ 17241 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17242 final PackageSetting ps, final int userId) { 17243 if (ps.pkg == null) { 17244 return; 17245 } 17246 17247 // These are flags that can change base on user actions. 17248 final int userSettableMask = FLAG_PERMISSION_USER_SET 17249 | FLAG_PERMISSION_USER_FIXED 17250 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17251 | FLAG_PERMISSION_REVIEW_REQUIRED; 17252 17253 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17254 | FLAG_PERMISSION_POLICY_FIXED; 17255 17256 boolean writeInstallPermissions = false; 17257 boolean writeRuntimePermissions = false; 17258 17259 final int permissionCount = ps.pkg.requestedPermissions.size(); 17260 for (int i = 0; i < permissionCount; i++) { 17261 String permission = ps.pkg.requestedPermissions.get(i); 17262 17263 BasePermission bp = mSettings.mPermissions.get(permission); 17264 if (bp == null) { 17265 continue; 17266 } 17267 17268 // If shared user we just reset the state to which only this app contributed. 17269 if (ps.sharedUser != null) { 17270 boolean used = false; 17271 final int packageCount = ps.sharedUser.packages.size(); 17272 for (int j = 0; j < packageCount; j++) { 17273 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17274 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17275 && pkg.pkg.requestedPermissions.contains(permission)) { 17276 used = true; 17277 break; 17278 } 17279 } 17280 if (used) { 17281 continue; 17282 } 17283 } 17284 17285 PermissionsState permissionsState = ps.getPermissionsState(); 17286 17287 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17288 17289 // Always clear the user settable flags. 17290 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17291 bp.name) != null; 17292 // If permission review is enabled and this is a legacy app, mark the 17293 // permission as requiring a review as this is the initial state. 17294 int flags = 0; 17295 if (mPermissionReviewRequired 17296 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17297 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17298 } 17299 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17300 if (hasInstallState) { 17301 writeInstallPermissions = true; 17302 } else { 17303 writeRuntimePermissions = true; 17304 } 17305 } 17306 17307 // Below is only runtime permission handling. 17308 if (!bp.isRuntime()) { 17309 continue; 17310 } 17311 17312 // Never clobber system or policy. 17313 if ((oldFlags & policyOrSystemFlags) != 0) { 17314 continue; 17315 } 17316 17317 // If this permission was granted by default, make sure it is. 17318 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17319 if (permissionsState.grantRuntimePermission(bp, userId) 17320 != PERMISSION_OPERATION_FAILURE) { 17321 writeRuntimePermissions = true; 17322 } 17323 // If permission review is enabled the permissions for a legacy apps 17324 // are represented as constantly granted runtime ones, so don't revoke. 17325 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17326 // Otherwise, reset the permission. 17327 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17328 switch (revokeResult) { 17329 case PERMISSION_OPERATION_SUCCESS: 17330 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17331 writeRuntimePermissions = true; 17332 final int appId = ps.appId; 17333 mHandler.post(new Runnable() { 17334 @Override 17335 public void run() { 17336 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17337 } 17338 }); 17339 } break; 17340 } 17341 } 17342 } 17343 17344 // Synchronously write as we are taking permissions away. 17345 if (writeRuntimePermissions) { 17346 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17347 } 17348 17349 // Synchronously write as we are taking permissions away. 17350 if (writeInstallPermissions) { 17351 mSettings.writeLPr(); 17352 } 17353 } 17354 17355 /** 17356 * Remove entries from the keystore daemon. Will only remove it if the 17357 * {@code appId} is valid. 17358 */ 17359 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17360 if (appId < 0) { 17361 return; 17362 } 17363 17364 final KeyStore keyStore = KeyStore.getInstance(); 17365 if (keyStore != null) { 17366 if (userId == UserHandle.USER_ALL) { 17367 for (final int individual : sUserManager.getUserIds()) { 17368 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17369 } 17370 } else { 17371 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17372 } 17373 } else { 17374 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17375 } 17376 } 17377 17378 @Override 17379 public void deleteApplicationCacheFiles(final String packageName, 17380 final IPackageDataObserver observer) { 17381 final int userId = UserHandle.getCallingUserId(); 17382 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17383 } 17384 17385 @Override 17386 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17387 final IPackageDataObserver observer) { 17388 mContext.enforceCallingOrSelfPermission( 17389 android.Manifest.permission.DELETE_CACHE_FILES, null); 17390 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17391 /* requireFullPermission= */ true, /* checkShell= */ false, 17392 "delete application cache files"); 17393 17394 final PackageParser.Package pkg; 17395 synchronized (mPackages) { 17396 pkg = mPackages.get(packageName); 17397 } 17398 17399 // Queue up an async operation since the package deletion may take a little while. 17400 mHandler.post(new Runnable() { 17401 public void run() { 17402 synchronized (mInstallLock) { 17403 final int flags = StorageManager.FLAG_STORAGE_DE 17404 | StorageManager.FLAG_STORAGE_CE; 17405 // We're only clearing cache files, so we don't care if the 17406 // app is unfrozen and still able to run 17407 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17408 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17409 } 17410 clearExternalStorageDataSync(packageName, userId, false); 17411 if (observer != null) { 17412 try { 17413 observer.onRemoveCompleted(packageName, true); 17414 } catch (RemoteException e) { 17415 Log.i(TAG, "Observer no longer exists."); 17416 } 17417 } 17418 } 17419 }); 17420 } 17421 17422 @Override 17423 public void getPackageSizeInfo(final String packageName, int userHandle, 17424 final IPackageStatsObserver observer) { 17425 mContext.enforceCallingOrSelfPermission( 17426 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17427 if (packageName == null) { 17428 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17429 } 17430 17431 PackageStats stats = new PackageStats(packageName, userHandle); 17432 17433 /* 17434 * Queue up an async operation since the package measurement may take a 17435 * little while. 17436 */ 17437 Message msg = mHandler.obtainMessage(INIT_COPY); 17438 msg.obj = new MeasureParams(stats, observer); 17439 mHandler.sendMessage(msg); 17440 } 17441 17442 private boolean equals(PackageStats a, PackageStats b) { 17443 return (a.codeSize == b.codeSize) && (a.dataSize == b.dataSize) 17444 && (a.cacheSize == b.cacheSize); 17445 } 17446 17447 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17448 final PackageSetting ps; 17449 synchronized (mPackages) { 17450 ps = mSettings.mPackages.get(packageName); 17451 if (ps == null) { 17452 Slog.w(TAG, "Failed to find settings for " + packageName); 17453 return false; 17454 } 17455 } 17456 17457 final long ceDataInode = ps.getCeDataInode(userId); 17458 final PackageStats quotaStats = new PackageStats(stats.packageName, stats.userHandle); 17459 17460 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17461 final String externalUuid = storage.getPrimaryStorageUuid(); 17462 try { 17463 final long start = SystemClock.elapsedRealtimeNanos(); 17464 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 0, 17465 ps.appId, ceDataInode, ps.codePathString, externalUuid, stats); 17466 final long stopManual = SystemClock.elapsedRealtimeNanos(); 17467 if (ENABLE_QUOTA) { 17468 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, Installer.FLAG_USE_QUOTA, 17469 ps.appId, ceDataInode, ps.codePathString, externalUuid, quotaStats); 17470 } 17471 final long stopQuota = SystemClock.elapsedRealtimeNanos(); 17472 17473 // For now, ignore code size of packages on system partition 17474 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17475 stats.codeSize = 0; 17476 quotaStats.codeSize = 0; 17477 } 17478 17479 if (ENABLE_QUOTA && Build.IS_ENG && !ps.isSharedUser()) { 17480 if (!equals(stats, quotaStats)) { 17481 Log.w(TAG, "Found discrepancy between statistics:"); 17482 Log.w(TAG, "Manual: " + stats); 17483 Log.w(TAG, "Quota: " + quotaStats); 17484 } 17485 final long manualTime = stopManual - start; 17486 final long quotaTime = stopQuota - stopManual; 17487 EventLogTags.writePmPackageStats(manualTime, quotaTime, 17488 stats.dataSize, quotaStats.dataSize, 17489 stats.cacheSize, quotaStats.cacheSize); 17490 } 17491 17492 // External clients expect these to be tracked separately 17493 stats.dataSize -= stats.cacheSize; 17494 quotaStats.dataSize -= quotaStats.cacheSize; 17495 17496 } catch (InstallerException e) { 17497 Slog.w(TAG, String.valueOf(e)); 17498 return false; 17499 } 17500 17501 return true; 17502 } 17503 17504 private int getUidTargetSdkVersionLockedLPr(int uid) { 17505 Object obj = mSettings.getUserIdLPr(uid); 17506 if (obj instanceof SharedUserSetting) { 17507 final SharedUserSetting sus = (SharedUserSetting) obj; 17508 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17509 final Iterator<PackageSetting> it = sus.packages.iterator(); 17510 while (it.hasNext()) { 17511 final PackageSetting ps = it.next(); 17512 if (ps.pkg != null) { 17513 int v = ps.pkg.applicationInfo.targetSdkVersion; 17514 if (v < vers) vers = v; 17515 } 17516 } 17517 return vers; 17518 } else if (obj instanceof PackageSetting) { 17519 final PackageSetting ps = (PackageSetting) obj; 17520 if (ps.pkg != null) { 17521 return ps.pkg.applicationInfo.targetSdkVersion; 17522 } 17523 } 17524 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17525 } 17526 17527 @Override 17528 public void addPreferredActivity(IntentFilter filter, int match, 17529 ComponentName[] set, ComponentName activity, int userId) { 17530 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17531 "Adding preferred"); 17532 } 17533 17534 private void addPreferredActivityInternal(IntentFilter filter, int match, 17535 ComponentName[] set, ComponentName activity, boolean always, int userId, 17536 String opname) { 17537 // writer 17538 int callingUid = Binder.getCallingUid(); 17539 enforceCrossUserPermission(callingUid, userId, 17540 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17541 if (filter.countActions() == 0) { 17542 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17543 return; 17544 } 17545 synchronized (mPackages) { 17546 if (mContext.checkCallingOrSelfPermission( 17547 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17548 != PackageManager.PERMISSION_GRANTED) { 17549 if (getUidTargetSdkVersionLockedLPr(callingUid) 17550 < Build.VERSION_CODES.FROYO) { 17551 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17552 + callingUid); 17553 return; 17554 } 17555 mContext.enforceCallingOrSelfPermission( 17556 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17557 } 17558 17559 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17560 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17561 + userId + ":"); 17562 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17563 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17564 scheduleWritePackageRestrictionsLocked(userId); 17565 postPreferredActivityChangedBroadcast(userId); 17566 } 17567 } 17568 17569 private void postPreferredActivityChangedBroadcast(int userId) { 17570 mHandler.post(() -> { 17571 final IActivityManager am = ActivityManager.getService(); 17572 if (am == null) { 17573 return; 17574 } 17575 17576 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17577 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17578 try { 17579 am.broadcastIntent(null, intent, null, null, 17580 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17581 null, false, false, userId); 17582 } catch (RemoteException e) { 17583 } 17584 }); 17585 } 17586 17587 @Override 17588 public void replacePreferredActivity(IntentFilter filter, int match, 17589 ComponentName[] set, ComponentName activity, int userId) { 17590 if (filter.countActions() != 1) { 17591 throw new IllegalArgumentException( 17592 "replacePreferredActivity expects filter to have only 1 action."); 17593 } 17594 if (filter.countDataAuthorities() != 0 17595 || filter.countDataPaths() != 0 17596 || filter.countDataSchemes() > 1 17597 || filter.countDataTypes() != 0) { 17598 throw new IllegalArgumentException( 17599 "replacePreferredActivity expects filter to have no data authorities, " + 17600 "paths, or types; and at most one scheme."); 17601 } 17602 17603 final int callingUid = Binder.getCallingUid(); 17604 enforceCrossUserPermission(callingUid, userId, 17605 true /* requireFullPermission */, false /* checkShell */, 17606 "replace preferred activity"); 17607 synchronized (mPackages) { 17608 if (mContext.checkCallingOrSelfPermission( 17609 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17610 != PackageManager.PERMISSION_GRANTED) { 17611 if (getUidTargetSdkVersionLockedLPr(callingUid) 17612 < Build.VERSION_CODES.FROYO) { 17613 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17614 + Binder.getCallingUid()); 17615 return; 17616 } 17617 mContext.enforceCallingOrSelfPermission( 17618 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17619 } 17620 17621 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17622 if (pir != null) { 17623 // Get all of the existing entries that exactly match this filter. 17624 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17625 if (existing != null && existing.size() == 1) { 17626 PreferredActivity cur = existing.get(0); 17627 if (DEBUG_PREFERRED) { 17628 Slog.i(TAG, "Checking replace of preferred:"); 17629 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17630 if (!cur.mPref.mAlways) { 17631 Slog.i(TAG, " -- CUR; not mAlways!"); 17632 } else { 17633 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17634 Slog.i(TAG, " -- CUR: mSet=" 17635 + Arrays.toString(cur.mPref.mSetComponents)); 17636 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17637 Slog.i(TAG, " -- NEW: mMatch=" 17638 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17639 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17640 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17641 } 17642 } 17643 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17644 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17645 && cur.mPref.sameSet(set)) { 17646 // Setting the preferred activity to what it happens to be already 17647 if (DEBUG_PREFERRED) { 17648 Slog.i(TAG, "Replacing with same preferred activity " 17649 + cur.mPref.mShortComponent + " for user " 17650 + userId + ":"); 17651 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17652 } 17653 return; 17654 } 17655 } 17656 17657 if (existing != null) { 17658 if (DEBUG_PREFERRED) { 17659 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17660 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17661 } 17662 for (int i = 0; i < existing.size(); i++) { 17663 PreferredActivity pa = existing.get(i); 17664 if (DEBUG_PREFERRED) { 17665 Slog.i(TAG, "Removing existing preferred activity " 17666 + pa.mPref.mComponent + ":"); 17667 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17668 } 17669 pir.removeFilter(pa); 17670 } 17671 } 17672 } 17673 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17674 "Replacing preferred"); 17675 } 17676 } 17677 17678 @Override 17679 public void clearPackagePreferredActivities(String packageName) { 17680 final int uid = Binder.getCallingUid(); 17681 // writer 17682 synchronized (mPackages) { 17683 PackageParser.Package pkg = mPackages.get(packageName); 17684 if (pkg == null || pkg.applicationInfo.uid != uid) { 17685 if (mContext.checkCallingOrSelfPermission( 17686 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17687 != PackageManager.PERMISSION_GRANTED) { 17688 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17689 < Build.VERSION_CODES.FROYO) { 17690 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17691 + Binder.getCallingUid()); 17692 return; 17693 } 17694 mContext.enforceCallingOrSelfPermission( 17695 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17696 } 17697 } 17698 17699 int user = UserHandle.getCallingUserId(); 17700 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17701 scheduleWritePackageRestrictionsLocked(user); 17702 } 17703 } 17704 } 17705 17706 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17707 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17708 ArrayList<PreferredActivity> removed = null; 17709 boolean changed = false; 17710 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17711 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17712 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17713 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17714 continue; 17715 } 17716 Iterator<PreferredActivity> it = pir.filterIterator(); 17717 while (it.hasNext()) { 17718 PreferredActivity pa = it.next(); 17719 // Mark entry for removal only if it matches the package name 17720 // and the entry is of type "always". 17721 if (packageName == null || 17722 (pa.mPref.mComponent.getPackageName().equals(packageName) 17723 && pa.mPref.mAlways)) { 17724 if (removed == null) { 17725 removed = new ArrayList<PreferredActivity>(); 17726 } 17727 removed.add(pa); 17728 } 17729 } 17730 if (removed != null) { 17731 for (int j=0; j<removed.size(); j++) { 17732 PreferredActivity pa = removed.get(j); 17733 pir.removeFilter(pa); 17734 } 17735 changed = true; 17736 } 17737 } 17738 if (changed) { 17739 postPreferredActivityChangedBroadcast(userId); 17740 } 17741 return changed; 17742 } 17743 17744 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17745 private void clearIntentFilterVerificationsLPw(int userId) { 17746 final int packageCount = mPackages.size(); 17747 for (int i = 0; i < packageCount; i++) { 17748 PackageParser.Package pkg = mPackages.valueAt(i); 17749 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17750 } 17751 } 17752 17753 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17754 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17755 if (userId == UserHandle.USER_ALL) { 17756 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17757 sUserManager.getUserIds())) { 17758 for (int oneUserId : sUserManager.getUserIds()) { 17759 scheduleWritePackageRestrictionsLocked(oneUserId); 17760 } 17761 } 17762 } else { 17763 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17764 scheduleWritePackageRestrictionsLocked(userId); 17765 } 17766 } 17767 } 17768 17769 void clearDefaultBrowserIfNeeded(String packageName) { 17770 for (int oneUserId : sUserManager.getUserIds()) { 17771 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17772 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17773 if (packageName.equals(defaultBrowserPackageName)) { 17774 setDefaultBrowserPackageName(null, oneUserId); 17775 } 17776 } 17777 } 17778 17779 @Override 17780 public void resetApplicationPreferences(int userId) { 17781 mContext.enforceCallingOrSelfPermission( 17782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17783 final long identity = Binder.clearCallingIdentity(); 17784 // writer 17785 try { 17786 synchronized (mPackages) { 17787 clearPackagePreferredActivitiesLPw(null, userId); 17788 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17789 // TODO: We have to reset the default SMS and Phone. This requires 17790 // significant refactoring to keep all default apps in the package 17791 // manager (cleaner but more work) or have the services provide 17792 // callbacks to the package manager to request a default app reset. 17793 applyFactoryDefaultBrowserLPw(userId); 17794 clearIntentFilterVerificationsLPw(userId); 17795 primeDomainVerificationsLPw(userId); 17796 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17797 scheduleWritePackageRestrictionsLocked(userId); 17798 } 17799 resetNetworkPolicies(userId); 17800 } finally { 17801 Binder.restoreCallingIdentity(identity); 17802 } 17803 } 17804 17805 @Override 17806 public int getPreferredActivities(List<IntentFilter> outFilters, 17807 List<ComponentName> outActivities, String packageName) { 17808 17809 int num = 0; 17810 final int userId = UserHandle.getCallingUserId(); 17811 // reader 17812 synchronized (mPackages) { 17813 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17814 if (pir != null) { 17815 final Iterator<PreferredActivity> it = pir.filterIterator(); 17816 while (it.hasNext()) { 17817 final PreferredActivity pa = it.next(); 17818 if (packageName == null 17819 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17820 && pa.mPref.mAlways)) { 17821 if (outFilters != null) { 17822 outFilters.add(new IntentFilter(pa)); 17823 } 17824 if (outActivities != null) { 17825 outActivities.add(pa.mPref.mComponent); 17826 } 17827 } 17828 } 17829 } 17830 } 17831 17832 return num; 17833 } 17834 17835 @Override 17836 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17837 int userId) { 17838 int callingUid = Binder.getCallingUid(); 17839 if (callingUid != Process.SYSTEM_UID) { 17840 throw new SecurityException( 17841 "addPersistentPreferredActivity can only be run by the system"); 17842 } 17843 if (filter.countActions() == 0) { 17844 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17845 return; 17846 } 17847 synchronized (mPackages) { 17848 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17849 ":"); 17850 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17851 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17852 new PersistentPreferredActivity(filter, activity)); 17853 scheduleWritePackageRestrictionsLocked(userId); 17854 postPreferredActivityChangedBroadcast(userId); 17855 } 17856 } 17857 17858 @Override 17859 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17860 int callingUid = Binder.getCallingUid(); 17861 if (callingUid != Process.SYSTEM_UID) { 17862 throw new SecurityException( 17863 "clearPackagePersistentPreferredActivities can only be run by the system"); 17864 } 17865 ArrayList<PersistentPreferredActivity> removed = null; 17866 boolean changed = false; 17867 synchronized (mPackages) { 17868 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17869 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17870 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17871 .valueAt(i); 17872 if (userId != thisUserId) { 17873 continue; 17874 } 17875 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17876 while (it.hasNext()) { 17877 PersistentPreferredActivity ppa = it.next(); 17878 // Mark entry for removal only if it matches the package name. 17879 if (ppa.mComponent.getPackageName().equals(packageName)) { 17880 if (removed == null) { 17881 removed = new ArrayList<PersistentPreferredActivity>(); 17882 } 17883 removed.add(ppa); 17884 } 17885 } 17886 if (removed != null) { 17887 for (int j=0; j<removed.size(); j++) { 17888 PersistentPreferredActivity ppa = removed.get(j); 17889 ppir.removeFilter(ppa); 17890 } 17891 changed = true; 17892 } 17893 } 17894 17895 if (changed) { 17896 scheduleWritePackageRestrictionsLocked(userId); 17897 postPreferredActivityChangedBroadcast(userId); 17898 } 17899 } 17900 } 17901 17902 /** 17903 * Common machinery for picking apart a restored XML blob and passing 17904 * it to a caller-supplied functor to be applied to the running system. 17905 */ 17906 private void restoreFromXml(XmlPullParser parser, int userId, 17907 String expectedStartTag, BlobXmlRestorer functor) 17908 throws IOException, XmlPullParserException { 17909 int type; 17910 while ((type = parser.next()) != XmlPullParser.START_TAG 17911 && type != XmlPullParser.END_DOCUMENT) { 17912 } 17913 if (type != XmlPullParser.START_TAG) { 17914 // oops didn't find a start tag?! 17915 if (DEBUG_BACKUP) { 17916 Slog.e(TAG, "Didn't find start tag during restore"); 17917 } 17918 return; 17919 } 17920Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17921 // this is supposed to be TAG_PREFERRED_BACKUP 17922 if (!expectedStartTag.equals(parser.getName())) { 17923 if (DEBUG_BACKUP) { 17924 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17925 } 17926 return; 17927 } 17928 17929 // skip interfering stuff, then we're aligned with the backing implementation 17930 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17931Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17932 functor.apply(parser, userId); 17933 } 17934 17935 private interface BlobXmlRestorer { 17936 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17937 } 17938 17939 /** 17940 * Non-Binder method, support for the backup/restore mechanism: write the 17941 * full set of preferred activities in its canonical XML format. Returns the 17942 * XML output as a byte array, or null if there is none. 17943 */ 17944 @Override 17945 public byte[] getPreferredActivityBackup(int userId) { 17946 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17947 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17948 } 17949 17950 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17951 try { 17952 final XmlSerializer serializer = new FastXmlSerializer(); 17953 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17954 serializer.startDocument(null, true); 17955 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17956 17957 synchronized (mPackages) { 17958 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17959 } 17960 17961 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17962 serializer.endDocument(); 17963 serializer.flush(); 17964 } catch (Exception e) { 17965 if (DEBUG_BACKUP) { 17966 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17967 } 17968 return null; 17969 } 17970 17971 return dataStream.toByteArray(); 17972 } 17973 17974 @Override 17975 public void restorePreferredActivities(byte[] backup, int userId) { 17976 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17977 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17978 } 17979 17980 try { 17981 final XmlPullParser parser = Xml.newPullParser(); 17982 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17983 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17984 new BlobXmlRestorer() { 17985 @Override 17986 public void apply(XmlPullParser parser, int userId) 17987 throws XmlPullParserException, IOException { 17988 synchronized (mPackages) { 17989 mSettings.readPreferredActivitiesLPw(parser, userId); 17990 } 17991 } 17992 } ); 17993 } catch (Exception e) { 17994 if (DEBUG_BACKUP) { 17995 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17996 } 17997 } 17998 } 17999 18000 /** 18001 * Non-Binder method, support for the backup/restore mechanism: write the 18002 * default browser (etc) settings in its canonical XML format. Returns the default 18003 * browser XML representation as a byte array, or null if there is none. 18004 */ 18005 @Override 18006 public byte[] getDefaultAppsBackup(int userId) { 18007 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18008 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 18009 } 18010 18011 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18012 try { 18013 final XmlSerializer serializer = new FastXmlSerializer(); 18014 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18015 serializer.startDocument(null, true); 18016 serializer.startTag(null, TAG_DEFAULT_APPS); 18017 18018 synchronized (mPackages) { 18019 mSettings.writeDefaultAppsLPr(serializer, userId); 18020 } 18021 18022 serializer.endTag(null, TAG_DEFAULT_APPS); 18023 serializer.endDocument(); 18024 serializer.flush(); 18025 } catch (Exception e) { 18026 if (DEBUG_BACKUP) { 18027 Slog.e(TAG, "Unable to write default apps for backup", e); 18028 } 18029 return null; 18030 } 18031 18032 return dataStream.toByteArray(); 18033 } 18034 18035 @Override 18036 public void restoreDefaultApps(byte[] backup, int userId) { 18037 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18038 throw new SecurityException("Only the system may call restoreDefaultApps()"); 18039 } 18040 18041 try { 18042 final XmlPullParser parser = Xml.newPullParser(); 18043 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18044 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 18045 new BlobXmlRestorer() { 18046 @Override 18047 public void apply(XmlPullParser parser, int userId) 18048 throws XmlPullParserException, IOException { 18049 synchronized (mPackages) { 18050 mSettings.readDefaultAppsLPw(parser, userId); 18051 } 18052 } 18053 } ); 18054 } catch (Exception e) { 18055 if (DEBUG_BACKUP) { 18056 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 18057 } 18058 } 18059 } 18060 18061 @Override 18062 public byte[] getIntentFilterVerificationBackup(int userId) { 18063 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18064 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 18065 } 18066 18067 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18068 try { 18069 final XmlSerializer serializer = new FastXmlSerializer(); 18070 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18071 serializer.startDocument(null, true); 18072 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 18073 18074 synchronized (mPackages) { 18075 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 18076 } 18077 18078 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 18079 serializer.endDocument(); 18080 serializer.flush(); 18081 } catch (Exception e) { 18082 if (DEBUG_BACKUP) { 18083 Slog.e(TAG, "Unable to write default apps for backup", e); 18084 } 18085 return null; 18086 } 18087 18088 return dataStream.toByteArray(); 18089 } 18090 18091 @Override 18092 public void restoreIntentFilterVerification(byte[] backup, int userId) { 18093 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18094 throw new SecurityException("Only the system may call restorePreferredActivities()"); 18095 } 18096 18097 try { 18098 final XmlPullParser parser = Xml.newPullParser(); 18099 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18100 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 18101 new BlobXmlRestorer() { 18102 @Override 18103 public void apply(XmlPullParser parser, int userId) 18104 throws XmlPullParserException, IOException { 18105 synchronized (mPackages) { 18106 mSettings.readAllDomainVerificationsLPr(parser, userId); 18107 mSettings.writeLPr(); 18108 } 18109 } 18110 } ); 18111 } catch (Exception e) { 18112 if (DEBUG_BACKUP) { 18113 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18114 } 18115 } 18116 } 18117 18118 @Override 18119 public byte[] getPermissionGrantBackup(int userId) { 18120 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18121 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 18122 } 18123 18124 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18125 try { 18126 final XmlSerializer serializer = new FastXmlSerializer(); 18127 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18128 serializer.startDocument(null, true); 18129 serializer.startTag(null, TAG_PERMISSION_BACKUP); 18130 18131 synchronized (mPackages) { 18132 serializeRuntimePermissionGrantsLPr(serializer, userId); 18133 } 18134 18135 serializer.endTag(null, TAG_PERMISSION_BACKUP); 18136 serializer.endDocument(); 18137 serializer.flush(); 18138 } catch (Exception e) { 18139 if (DEBUG_BACKUP) { 18140 Slog.e(TAG, "Unable to write default apps for backup", e); 18141 } 18142 return null; 18143 } 18144 18145 return dataStream.toByteArray(); 18146 } 18147 18148 @Override 18149 public void restorePermissionGrants(byte[] backup, int userId) { 18150 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18151 throw new SecurityException("Only the system may call restorePermissionGrants()"); 18152 } 18153 18154 try { 18155 final XmlPullParser parser = Xml.newPullParser(); 18156 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18157 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 18158 new BlobXmlRestorer() { 18159 @Override 18160 public void apply(XmlPullParser parser, int userId) 18161 throws XmlPullParserException, IOException { 18162 synchronized (mPackages) { 18163 processRestoredPermissionGrantsLPr(parser, userId); 18164 } 18165 } 18166 } ); 18167 } catch (Exception e) { 18168 if (DEBUG_BACKUP) { 18169 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18170 } 18171 } 18172 } 18173 18174 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 18175 throws IOException { 18176 serializer.startTag(null, TAG_ALL_GRANTS); 18177 18178 final int N = mSettings.mPackages.size(); 18179 for (int i = 0; i < N; i++) { 18180 final PackageSetting ps = mSettings.mPackages.valueAt(i); 18181 boolean pkgGrantsKnown = false; 18182 18183 PermissionsState packagePerms = ps.getPermissionsState(); 18184 18185 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 18186 final int grantFlags = state.getFlags(); 18187 // only look at grants that are not system/policy fixed 18188 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 18189 final boolean isGranted = state.isGranted(); 18190 // And only back up the user-twiddled state bits 18191 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 18192 final String packageName = mSettings.mPackages.keyAt(i); 18193 if (!pkgGrantsKnown) { 18194 serializer.startTag(null, TAG_GRANT); 18195 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 18196 pkgGrantsKnown = true; 18197 } 18198 18199 final boolean userSet = 18200 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 18201 final boolean userFixed = 18202 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 18203 final boolean revoke = 18204 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 18205 18206 serializer.startTag(null, TAG_PERMISSION); 18207 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 18208 if (isGranted) { 18209 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 18210 } 18211 if (userSet) { 18212 serializer.attribute(null, ATTR_USER_SET, "true"); 18213 } 18214 if (userFixed) { 18215 serializer.attribute(null, ATTR_USER_FIXED, "true"); 18216 } 18217 if (revoke) { 18218 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 18219 } 18220 serializer.endTag(null, TAG_PERMISSION); 18221 } 18222 } 18223 } 18224 18225 if (pkgGrantsKnown) { 18226 serializer.endTag(null, TAG_GRANT); 18227 } 18228 } 18229 18230 serializer.endTag(null, TAG_ALL_GRANTS); 18231 } 18232 18233 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 18234 throws XmlPullParserException, IOException { 18235 String pkgName = null; 18236 int outerDepth = parser.getDepth(); 18237 int type; 18238 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 18239 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 18240 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18241 continue; 18242 } 18243 18244 final String tagName = parser.getName(); 18245 if (tagName.equals(TAG_GRANT)) { 18246 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18247 if (DEBUG_BACKUP) { 18248 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18249 } 18250 } else if (tagName.equals(TAG_PERMISSION)) { 18251 18252 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18253 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18254 18255 int newFlagSet = 0; 18256 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18257 newFlagSet |= FLAG_PERMISSION_USER_SET; 18258 } 18259 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18260 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18261 } 18262 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18263 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18264 } 18265 if (DEBUG_BACKUP) { 18266 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18267 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18268 } 18269 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18270 if (ps != null) { 18271 // Already installed so we apply the grant immediately 18272 if (DEBUG_BACKUP) { 18273 Slog.v(TAG, " + already installed; applying"); 18274 } 18275 PermissionsState perms = ps.getPermissionsState(); 18276 BasePermission bp = mSettings.mPermissions.get(permName); 18277 if (bp != null) { 18278 if (isGranted) { 18279 perms.grantRuntimePermission(bp, userId); 18280 } 18281 if (newFlagSet != 0) { 18282 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18283 } 18284 } 18285 } else { 18286 // Need to wait for post-restore install to apply the grant 18287 if (DEBUG_BACKUP) { 18288 Slog.v(TAG, " - not yet installed; saving for later"); 18289 } 18290 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18291 isGranted, newFlagSet, userId); 18292 } 18293 } else { 18294 PackageManagerService.reportSettingsProblem(Log.WARN, 18295 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18296 XmlUtils.skipCurrentTag(parser); 18297 } 18298 } 18299 18300 scheduleWriteSettingsLocked(); 18301 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18302 } 18303 18304 @Override 18305 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18306 int sourceUserId, int targetUserId, int flags) { 18307 mContext.enforceCallingOrSelfPermission( 18308 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18309 int callingUid = Binder.getCallingUid(); 18310 enforceOwnerRights(ownerPackage, callingUid); 18311 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18312 if (intentFilter.countActions() == 0) { 18313 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18314 return; 18315 } 18316 synchronized (mPackages) { 18317 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18318 ownerPackage, targetUserId, flags); 18319 CrossProfileIntentResolver resolver = 18320 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18321 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18322 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18323 if (existing != null) { 18324 int size = existing.size(); 18325 for (int i = 0; i < size; i++) { 18326 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18327 return; 18328 } 18329 } 18330 } 18331 resolver.addFilter(newFilter); 18332 scheduleWritePackageRestrictionsLocked(sourceUserId); 18333 } 18334 } 18335 18336 @Override 18337 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18338 mContext.enforceCallingOrSelfPermission( 18339 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18340 int callingUid = Binder.getCallingUid(); 18341 enforceOwnerRights(ownerPackage, callingUid); 18342 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18343 synchronized (mPackages) { 18344 CrossProfileIntentResolver resolver = 18345 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18346 ArraySet<CrossProfileIntentFilter> set = 18347 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18348 for (CrossProfileIntentFilter filter : set) { 18349 if (filter.getOwnerPackage().equals(ownerPackage)) { 18350 resolver.removeFilter(filter); 18351 } 18352 } 18353 scheduleWritePackageRestrictionsLocked(sourceUserId); 18354 } 18355 } 18356 18357 // Enforcing that callingUid is owning pkg on userId 18358 private void enforceOwnerRights(String pkg, int callingUid) { 18359 // The system owns everything. 18360 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18361 return; 18362 } 18363 int callingUserId = UserHandle.getUserId(callingUid); 18364 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18365 if (pi == null) { 18366 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18367 + callingUserId); 18368 } 18369 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18370 throw new SecurityException("Calling uid " + callingUid 18371 + " does not own package " + pkg); 18372 } 18373 } 18374 18375 @Override 18376 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18377 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18378 } 18379 18380 private Intent getHomeIntent() { 18381 Intent intent = new Intent(Intent.ACTION_MAIN); 18382 intent.addCategory(Intent.CATEGORY_HOME); 18383 intent.addCategory(Intent.CATEGORY_DEFAULT); 18384 return intent; 18385 } 18386 18387 private IntentFilter getHomeFilter() { 18388 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18389 filter.addCategory(Intent.CATEGORY_HOME); 18390 filter.addCategory(Intent.CATEGORY_DEFAULT); 18391 return filter; 18392 } 18393 18394 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18395 int userId) { 18396 Intent intent = getHomeIntent(); 18397 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18398 PackageManager.GET_META_DATA, userId); 18399 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18400 true, false, false, userId); 18401 18402 allHomeCandidates.clear(); 18403 if (list != null) { 18404 for (ResolveInfo ri : list) { 18405 allHomeCandidates.add(ri); 18406 } 18407 } 18408 return (preferred == null || preferred.activityInfo == null) 18409 ? null 18410 : new ComponentName(preferred.activityInfo.packageName, 18411 preferred.activityInfo.name); 18412 } 18413 18414 @Override 18415 public void setHomeActivity(ComponentName comp, int userId) { 18416 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18417 getHomeActivitiesAsUser(homeActivities, userId); 18418 18419 boolean found = false; 18420 18421 final int size = homeActivities.size(); 18422 final ComponentName[] set = new ComponentName[size]; 18423 for (int i = 0; i < size; i++) { 18424 final ResolveInfo candidate = homeActivities.get(i); 18425 final ActivityInfo info = candidate.activityInfo; 18426 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18427 set[i] = activityName; 18428 if (!found && activityName.equals(comp)) { 18429 found = true; 18430 } 18431 } 18432 if (!found) { 18433 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18434 + userId); 18435 } 18436 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18437 set, comp, userId); 18438 } 18439 18440 private @Nullable String getSetupWizardPackageName() { 18441 final Intent intent = new Intent(Intent.ACTION_MAIN); 18442 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18443 18444 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18445 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18446 | MATCH_DISABLED_COMPONENTS, 18447 UserHandle.myUserId()); 18448 if (matches.size() == 1) { 18449 return matches.get(0).getComponentInfo().packageName; 18450 } else { 18451 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18452 + ": matches=" + matches); 18453 return null; 18454 } 18455 } 18456 18457 private @Nullable String getStorageManagerPackageName() { 18458 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18459 18460 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18461 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18462 | MATCH_DISABLED_COMPONENTS, 18463 UserHandle.myUserId()); 18464 if (matches.size() == 1) { 18465 return matches.get(0).getComponentInfo().packageName; 18466 } else { 18467 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18468 + matches.size() + ": matches=" + matches); 18469 return null; 18470 } 18471 } 18472 18473 @Override 18474 public void setApplicationEnabledSetting(String appPackageName, 18475 int newState, int flags, int userId, String callingPackage) { 18476 if (!sUserManager.exists(userId)) return; 18477 if (callingPackage == null) { 18478 callingPackage = Integer.toString(Binder.getCallingUid()); 18479 } 18480 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18481 } 18482 18483 @Override 18484 public void setComponentEnabledSetting(ComponentName componentName, 18485 int newState, int flags, int userId) { 18486 if (!sUserManager.exists(userId)) return; 18487 setEnabledSetting(componentName.getPackageName(), 18488 componentName.getClassName(), newState, flags, userId, null); 18489 } 18490 18491 private void setEnabledSetting(final String packageName, String className, int newState, 18492 final int flags, int userId, String callingPackage) { 18493 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18494 || newState == COMPONENT_ENABLED_STATE_ENABLED 18495 || newState == COMPONENT_ENABLED_STATE_DISABLED 18496 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18497 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18498 throw new IllegalArgumentException("Invalid new component state: " 18499 + newState); 18500 } 18501 PackageSetting pkgSetting; 18502 final int uid = Binder.getCallingUid(); 18503 final int permission; 18504 if (uid == Process.SYSTEM_UID) { 18505 permission = PackageManager.PERMISSION_GRANTED; 18506 } else { 18507 permission = mContext.checkCallingOrSelfPermission( 18508 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18509 } 18510 enforceCrossUserPermission(uid, userId, 18511 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18512 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18513 boolean sendNow = false; 18514 boolean isApp = (className == null); 18515 String componentName = isApp ? packageName : className; 18516 int packageUid = -1; 18517 ArrayList<String> components; 18518 18519 // writer 18520 synchronized (mPackages) { 18521 pkgSetting = mSettings.mPackages.get(packageName); 18522 if (pkgSetting == null) { 18523 if (className == null) { 18524 throw new IllegalArgumentException("Unknown package: " + packageName); 18525 } 18526 throw new IllegalArgumentException( 18527 "Unknown component: " + packageName + "/" + className); 18528 } 18529 } 18530 18531 // Limit who can change which apps 18532 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18533 // Don't allow apps that don't have permission to modify other apps 18534 if (!allowedByPermission) { 18535 throw new SecurityException( 18536 "Permission Denial: attempt to change component state from pid=" 18537 + Binder.getCallingPid() 18538 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18539 } 18540 // Don't allow changing protected packages. 18541 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18542 throw new SecurityException("Cannot disable a protected package: " + packageName); 18543 } 18544 } 18545 18546 synchronized (mPackages) { 18547 if (uid == Process.SHELL_UID 18548 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18549 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18550 // unless it is a test package. 18551 int oldState = pkgSetting.getEnabled(userId); 18552 if (className == null 18553 && 18554 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18555 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18556 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18557 && 18558 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18559 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18560 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18561 // ok 18562 } else { 18563 throw new SecurityException( 18564 "Shell cannot change component state for " + packageName + "/" 18565 + className + " to " + newState); 18566 } 18567 } 18568 if (className == null) { 18569 // We're dealing with an application/package level state change 18570 if (pkgSetting.getEnabled(userId) == newState) { 18571 // Nothing to do 18572 return; 18573 } 18574 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18575 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18576 // Don't care about who enables an app. 18577 callingPackage = null; 18578 } 18579 pkgSetting.setEnabled(newState, userId, callingPackage); 18580 // pkgSetting.pkg.mSetEnabled = newState; 18581 } else { 18582 // We're dealing with a component level state change 18583 // First, verify that this is a valid class name. 18584 PackageParser.Package pkg = pkgSetting.pkg; 18585 if (pkg == null || !pkg.hasComponentClassName(className)) { 18586 if (pkg != null && 18587 pkg.applicationInfo.targetSdkVersion >= 18588 Build.VERSION_CODES.JELLY_BEAN) { 18589 throw new IllegalArgumentException("Component class " + className 18590 + " does not exist in " + packageName); 18591 } else { 18592 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18593 + className + " does not exist in " + packageName); 18594 } 18595 } 18596 switch (newState) { 18597 case COMPONENT_ENABLED_STATE_ENABLED: 18598 if (!pkgSetting.enableComponentLPw(className, userId)) { 18599 return; 18600 } 18601 break; 18602 case COMPONENT_ENABLED_STATE_DISABLED: 18603 if (!pkgSetting.disableComponentLPw(className, userId)) { 18604 return; 18605 } 18606 break; 18607 case COMPONENT_ENABLED_STATE_DEFAULT: 18608 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18609 return; 18610 } 18611 break; 18612 default: 18613 Slog.e(TAG, "Invalid new component state: " + newState); 18614 return; 18615 } 18616 } 18617 scheduleWritePackageRestrictionsLocked(userId); 18618 components = mPendingBroadcasts.get(userId, packageName); 18619 final boolean newPackage = components == null; 18620 if (newPackage) { 18621 components = new ArrayList<String>(); 18622 } 18623 if (!components.contains(componentName)) { 18624 components.add(componentName); 18625 } 18626 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18627 sendNow = true; 18628 // Purge entry from pending broadcast list if another one exists already 18629 // since we are sending one right away. 18630 mPendingBroadcasts.remove(userId, packageName); 18631 } else { 18632 if (newPackage) { 18633 mPendingBroadcasts.put(userId, packageName, components); 18634 } 18635 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18636 // Schedule a message 18637 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18638 } 18639 } 18640 } 18641 18642 long callingId = Binder.clearCallingIdentity(); 18643 try { 18644 if (sendNow) { 18645 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18646 sendPackageChangedBroadcast(packageName, 18647 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18648 } 18649 } finally { 18650 Binder.restoreCallingIdentity(callingId); 18651 } 18652 } 18653 18654 @Override 18655 public void flushPackageRestrictionsAsUser(int userId) { 18656 if (!sUserManager.exists(userId)) { 18657 return; 18658 } 18659 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18660 false /* checkShell */, "flushPackageRestrictions"); 18661 synchronized (mPackages) { 18662 mSettings.writePackageRestrictionsLPr(userId); 18663 mDirtyUsers.remove(userId); 18664 if (mDirtyUsers.isEmpty()) { 18665 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18666 } 18667 } 18668 } 18669 18670 private void sendPackageChangedBroadcast(String packageName, 18671 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18672 if (DEBUG_INSTALL) 18673 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18674 + componentNames); 18675 Bundle extras = new Bundle(4); 18676 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18677 String nameList[] = new String[componentNames.size()]; 18678 componentNames.toArray(nameList); 18679 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18680 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18681 extras.putInt(Intent.EXTRA_UID, packageUid); 18682 // If this is not reporting a change of the overall package, then only send it 18683 // to registered receivers. We don't want to launch a swath of apps for every 18684 // little component state change. 18685 final int flags = !componentNames.contains(packageName) 18686 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18687 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18688 new int[] {UserHandle.getUserId(packageUid)}); 18689 } 18690 18691 @Override 18692 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18693 if (!sUserManager.exists(userId)) return; 18694 final int uid = Binder.getCallingUid(); 18695 final int permission = mContext.checkCallingOrSelfPermission( 18696 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18697 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18698 enforceCrossUserPermission(uid, userId, 18699 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18700 // writer 18701 synchronized (mPackages) { 18702 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18703 allowedByPermission, uid, userId)) { 18704 scheduleWritePackageRestrictionsLocked(userId); 18705 } 18706 } 18707 } 18708 18709 @Override 18710 public String getInstallerPackageName(String packageName) { 18711 // reader 18712 synchronized (mPackages) { 18713 return mSettings.getInstallerPackageNameLPr(packageName); 18714 } 18715 } 18716 18717 public boolean isOrphaned(String packageName) { 18718 // reader 18719 synchronized (mPackages) { 18720 return mSettings.isOrphaned(packageName); 18721 } 18722 } 18723 18724 @Override 18725 public int getApplicationEnabledSetting(String packageName, int userId) { 18726 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18727 int uid = Binder.getCallingUid(); 18728 enforceCrossUserPermission(uid, userId, 18729 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18730 // reader 18731 synchronized (mPackages) { 18732 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18733 } 18734 } 18735 18736 @Override 18737 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18738 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18739 int uid = Binder.getCallingUid(); 18740 enforceCrossUserPermission(uid, userId, 18741 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18742 // reader 18743 synchronized (mPackages) { 18744 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18745 } 18746 } 18747 18748 @Override 18749 public void enterSafeMode() { 18750 enforceSystemOrRoot("Only the system can request entering safe mode"); 18751 18752 if (!mSystemReady) { 18753 mSafeMode = true; 18754 } 18755 } 18756 18757 @Override 18758 public void systemReady() { 18759 mSystemReady = true; 18760 18761 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18762 // disabled after already being started. 18763 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18764 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18765 18766 // Read the compatibilty setting when the system is ready. 18767 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18768 mContext.getContentResolver(), 18769 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18770 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18771 if (DEBUG_SETTINGS) { 18772 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18773 } 18774 18775 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18776 18777 synchronized (mPackages) { 18778 // Verify that all of the preferred activity components actually 18779 // exist. It is possible for applications to be updated and at 18780 // that point remove a previously declared activity component that 18781 // had been set as a preferred activity. We try to clean this up 18782 // the next time we encounter that preferred activity, but it is 18783 // possible for the user flow to never be able to return to that 18784 // situation so here we do a sanity check to make sure we haven't 18785 // left any junk around. 18786 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18787 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18788 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18789 removed.clear(); 18790 for (PreferredActivity pa : pir.filterSet()) { 18791 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18792 removed.add(pa); 18793 } 18794 } 18795 if (removed.size() > 0) { 18796 for (int r=0; r<removed.size(); r++) { 18797 PreferredActivity pa = removed.get(r); 18798 Slog.w(TAG, "Removing dangling preferred activity: " 18799 + pa.mPref.mComponent); 18800 pir.removeFilter(pa); 18801 } 18802 mSettings.writePackageRestrictionsLPr( 18803 mSettings.mPreferredActivities.keyAt(i)); 18804 } 18805 } 18806 18807 for (int userId : UserManagerService.getInstance().getUserIds()) { 18808 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18809 grantPermissionsUserIds = ArrayUtils.appendInt( 18810 grantPermissionsUserIds, userId); 18811 } 18812 } 18813 } 18814 sUserManager.systemReady(); 18815 18816 // If we upgraded grant all default permissions before kicking off. 18817 for (int userId : grantPermissionsUserIds) { 18818 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18819 } 18820 18821 // If we did not grant default permissions, we preload from this the 18822 // default permission exceptions lazily to ensure we don't hit the 18823 // disk on a new user creation. 18824 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18825 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18826 } 18827 18828 // Kick off any messages waiting for system ready 18829 if (mPostSystemReadyMessages != null) { 18830 for (Message msg : mPostSystemReadyMessages) { 18831 msg.sendToTarget(); 18832 } 18833 mPostSystemReadyMessages = null; 18834 } 18835 18836 // Watch for external volumes that come and go over time 18837 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18838 storage.registerListener(mStorageListener); 18839 18840 mInstallerService.systemReady(); 18841 mPackageDexOptimizer.systemReady(); 18842 18843 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18844 StorageManagerInternal.class); 18845 StorageManagerInternal.addExternalStoragePolicy( 18846 new StorageManagerInternal.ExternalStorageMountPolicy() { 18847 @Override 18848 public int getMountMode(int uid, String packageName) { 18849 if (Process.isIsolated(uid)) { 18850 return Zygote.MOUNT_EXTERNAL_NONE; 18851 } 18852 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18853 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18854 } 18855 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18856 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18857 } 18858 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18859 return Zygote.MOUNT_EXTERNAL_READ; 18860 } 18861 return Zygote.MOUNT_EXTERNAL_WRITE; 18862 } 18863 18864 @Override 18865 public boolean hasExternalStorage(int uid, String packageName) { 18866 return true; 18867 } 18868 }); 18869 18870 // Now that we're mostly running, clean up stale users and apps 18871 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18872 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18873 } 18874 18875 @Override 18876 public boolean isSafeMode() { 18877 return mSafeMode; 18878 } 18879 18880 @Override 18881 public boolean hasSystemUidErrors() { 18882 return mHasSystemUidErrors; 18883 } 18884 18885 static String arrayToString(int[] array) { 18886 StringBuffer buf = new StringBuffer(128); 18887 buf.append('['); 18888 if (array != null) { 18889 for (int i=0; i<array.length; i++) { 18890 if (i > 0) buf.append(", "); 18891 buf.append(array[i]); 18892 } 18893 } 18894 buf.append(']'); 18895 return buf.toString(); 18896 } 18897 18898 static class DumpState { 18899 public static final int DUMP_LIBS = 1 << 0; 18900 public static final int DUMP_FEATURES = 1 << 1; 18901 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18902 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18903 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18904 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18905 public static final int DUMP_PERMISSIONS = 1 << 6; 18906 public static final int DUMP_PACKAGES = 1 << 7; 18907 public static final int DUMP_SHARED_USERS = 1 << 8; 18908 public static final int DUMP_MESSAGES = 1 << 9; 18909 public static final int DUMP_PROVIDERS = 1 << 10; 18910 public static final int DUMP_VERIFIERS = 1 << 11; 18911 public static final int DUMP_PREFERRED = 1 << 12; 18912 public static final int DUMP_PREFERRED_XML = 1 << 13; 18913 public static final int DUMP_KEYSETS = 1 << 14; 18914 public static final int DUMP_VERSION = 1 << 15; 18915 public static final int DUMP_INSTALLS = 1 << 16; 18916 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18917 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18918 public static final int DUMP_FROZEN = 1 << 19; 18919 public static final int DUMP_DEXOPT = 1 << 20; 18920 public static final int DUMP_COMPILER_STATS = 1 << 21; 18921 18922 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18923 18924 private int mTypes; 18925 18926 private int mOptions; 18927 18928 private boolean mTitlePrinted; 18929 18930 private SharedUserSetting mSharedUser; 18931 18932 public boolean isDumping(int type) { 18933 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18934 return true; 18935 } 18936 18937 return (mTypes & type) != 0; 18938 } 18939 18940 public void setDump(int type) { 18941 mTypes |= type; 18942 } 18943 18944 public boolean isOptionEnabled(int option) { 18945 return (mOptions & option) != 0; 18946 } 18947 18948 public void setOptionEnabled(int option) { 18949 mOptions |= option; 18950 } 18951 18952 public boolean onTitlePrinted() { 18953 final boolean printed = mTitlePrinted; 18954 mTitlePrinted = true; 18955 return printed; 18956 } 18957 18958 public boolean getTitlePrinted() { 18959 return mTitlePrinted; 18960 } 18961 18962 public void setTitlePrinted(boolean enabled) { 18963 mTitlePrinted = enabled; 18964 } 18965 18966 public SharedUserSetting getSharedUser() { 18967 return mSharedUser; 18968 } 18969 18970 public void setSharedUser(SharedUserSetting user) { 18971 mSharedUser = user; 18972 } 18973 } 18974 18975 @Override 18976 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18977 FileDescriptor err, String[] args, ShellCallback callback, 18978 ResultReceiver resultReceiver) { 18979 (new PackageManagerShellCommand(this)).exec( 18980 this, in, out, err, args, callback, resultReceiver); 18981 } 18982 18983 @Override 18984 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18985 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18986 != PackageManager.PERMISSION_GRANTED) { 18987 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18988 + Binder.getCallingPid() 18989 + ", uid=" + Binder.getCallingUid() 18990 + " without permission " 18991 + android.Manifest.permission.DUMP); 18992 return; 18993 } 18994 18995 DumpState dumpState = new DumpState(); 18996 boolean fullPreferred = false; 18997 boolean checkin = false; 18998 18999 String packageName = null; 19000 ArraySet<String> permissionNames = null; 19001 19002 int opti = 0; 19003 while (opti < args.length) { 19004 String opt = args[opti]; 19005 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 19006 break; 19007 } 19008 opti++; 19009 19010 if ("-a".equals(opt)) { 19011 // Right now we only know how to print all. 19012 } else if ("-h".equals(opt)) { 19013 pw.println("Package manager dump options:"); 19014 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 19015 pw.println(" --checkin: dump for a checkin"); 19016 pw.println(" -f: print details of intent filters"); 19017 pw.println(" -h: print this help"); 19018 pw.println(" cmd may be one of:"); 19019 pw.println(" l[ibraries]: list known shared libraries"); 19020 pw.println(" f[eatures]: list device features"); 19021 pw.println(" k[eysets]: print known keysets"); 19022 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 19023 pw.println(" perm[issions]: dump permissions"); 19024 pw.println(" permission [name ...]: dump declaration and use of given permission"); 19025 pw.println(" pref[erred]: print preferred package settings"); 19026 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 19027 pw.println(" prov[iders]: dump content providers"); 19028 pw.println(" p[ackages]: dump installed packages"); 19029 pw.println(" s[hared-users]: dump shared user IDs"); 19030 pw.println(" m[essages]: print collected runtime messages"); 19031 pw.println(" v[erifiers]: print package verifier info"); 19032 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 19033 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 19034 pw.println(" version: print database version info"); 19035 pw.println(" write: write current settings now"); 19036 pw.println(" installs: details about install sessions"); 19037 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 19038 pw.println(" dexopt: dump dexopt state"); 19039 pw.println(" compiler-stats: dump compiler statistics"); 19040 pw.println(" <package.name>: info about given package"); 19041 return; 19042 } else if ("--checkin".equals(opt)) { 19043 checkin = true; 19044 } else if ("-f".equals(opt)) { 19045 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19046 } else { 19047 pw.println("Unknown argument: " + opt + "; use -h for help"); 19048 } 19049 } 19050 19051 // Is the caller requesting to dump a particular piece of data? 19052 if (opti < args.length) { 19053 String cmd = args[opti]; 19054 opti++; 19055 // Is this a package name? 19056 if ("android".equals(cmd) || cmd.contains(".")) { 19057 packageName = cmd; 19058 // When dumping a single package, we always dump all of its 19059 // filter information since the amount of data will be reasonable. 19060 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19061 } else if ("check-permission".equals(cmd)) { 19062 if (opti >= args.length) { 19063 pw.println("Error: check-permission missing permission argument"); 19064 return; 19065 } 19066 String perm = args[opti]; 19067 opti++; 19068 if (opti >= args.length) { 19069 pw.println("Error: check-permission missing package argument"); 19070 return; 19071 } 19072 String pkg = args[opti]; 19073 opti++; 19074 int user = UserHandle.getUserId(Binder.getCallingUid()); 19075 if (opti < args.length) { 19076 try { 19077 user = Integer.parseInt(args[opti]); 19078 } catch (NumberFormatException e) { 19079 pw.println("Error: check-permission user argument is not a number: " 19080 + args[opti]); 19081 return; 19082 } 19083 } 19084 pw.println(checkPermission(perm, pkg, user)); 19085 return; 19086 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 19087 dumpState.setDump(DumpState.DUMP_LIBS); 19088 } else if ("f".equals(cmd) || "features".equals(cmd)) { 19089 dumpState.setDump(DumpState.DUMP_FEATURES); 19090 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 19091 if (opti >= args.length) { 19092 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 19093 | DumpState.DUMP_SERVICE_RESOLVERS 19094 | DumpState.DUMP_RECEIVER_RESOLVERS 19095 | DumpState.DUMP_CONTENT_RESOLVERS); 19096 } else { 19097 while (opti < args.length) { 19098 String name = args[opti]; 19099 if ("a".equals(name) || "activity".equals(name)) { 19100 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 19101 } else if ("s".equals(name) || "service".equals(name)) { 19102 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 19103 } else if ("r".equals(name) || "receiver".equals(name)) { 19104 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 19105 } else if ("c".equals(name) || "content".equals(name)) { 19106 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 19107 } else { 19108 pw.println("Error: unknown resolver table type: " + name); 19109 return; 19110 } 19111 opti++; 19112 } 19113 } 19114 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 19115 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 19116 } else if ("permission".equals(cmd)) { 19117 if (opti >= args.length) { 19118 pw.println("Error: permission requires permission name"); 19119 return; 19120 } 19121 permissionNames = new ArraySet<>(); 19122 while (opti < args.length) { 19123 permissionNames.add(args[opti]); 19124 opti++; 19125 } 19126 dumpState.setDump(DumpState.DUMP_PERMISSIONS 19127 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 19128 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 19129 dumpState.setDump(DumpState.DUMP_PREFERRED); 19130 } else if ("preferred-xml".equals(cmd)) { 19131 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 19132 if (opti < args.length && "--full".equals(args[opti])) { 19133 fullPreferred = true; 19134 opti++; 19135 } 19136 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 19137 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 19138 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 19139 dumpState.setDump(DumpState.DUMP_PACKAGES); 19140 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 19141 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 19142 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 19143 dumpState.setDump(DumpState.DUMP_PROVIDERS); 19144 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 19145 dumpState.setDump(DumpState.DUMP_MESSAGES); 19146 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 19147 dumpState.setDump(DumpState.DUMP_VERIFIERS); 19148 } else if ("i".equals(cmd) || "ifv".equals(cmd) 19149 || "intent-filter-verifiers".equals(cmd)) { 19150 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 19151 } else if ("version".equals(cmd)) { 19152 dumpState.setDump(DumpState.DUMP_VERSION); 19153 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 19154 dumpState.setDump(DumpState.DUMP_KEYSETS); 19155 } else if ("installs".equals(cmd)) { 19156 dumpState.setDump(DumpState.DUMP_INSTALLS); 19157 } else if ("frozen".equals(cmd)) { 19158 dumpState.setDump(DumpState.DUMP_FROZEN); 19159 } else if ("dexopt".equals(cmd)) { 19160 dumpState.setDump(DumpState.DUMP_DEXOPT); 19161 } else if ("compiler-stats".equals(cmd)) { 19162 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 19163 } else if ("write".equals(cmd)) { 19164 synchronized (mPackages) { 19165 mSettings.writeLPr(); 19166 pw.println("Settings written."); 19167 return; 19168 } 19169 } 19170 } 19171 19172 if (checkin) { 19173 pw.println("vers,1"); 19174 } 19175 19176 // reader 19177 synchronized (mPackages) { 19178 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 19179 if (!checkin) { 19180 if (dumpState.onTitlePrinted()) 19181 pw.println(); 19182 pw.println("Database versions:"); 19183 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 19184 } 19185 } 19186 19187 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 19188 if (!checkin) { 19189 if (dumpState.onTitlePrinted()) 19190 pw.println(); 19191 pw.println("Verifiers:"); 19192 pw.print(" Required: "); 19193 pw.print(mRequiredVerifierPackage); 19194 pw.print(" (uid="); 19195 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19196 UserHandle.USER_SYSTEM)); 19197 pw.println(")"); 19198 } else if (mRequiredVerifierPackage != null) { 19199 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 19200 pw.print(","); 19201 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19202 UserHandle.USER_SYSTEM)); 19203 } 19204 } 19205 19206 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 19207 packageName == null) { 19208 if (mIntentFilterVerifierComponent != null) { 19209 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 19210 if (!checkin) { 19211 if (dumpState.onTitlePrinted()) 19212 pw.println(); 19213 pw.println("Intent Filter Verifier:"); 19214 pw.print(" Using: "); 19215 pw.print(verifierPackageName); 19216 pw.print(" (uid="); 19217 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19218 UserHandle.USER_SYSTEM)); 19219 pw.println(")"); 19220 } else if (verifierPackageName != null) { 19221 pw.print("ifv,"); pw.print(verifierPackageName); 19222 pw.print(","); 19223 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19224 UserHandle.USER_SYSTEM)); 19225 } 19226 } else { 19227 pw.println(); 19228 pw.println("No Intent Filter Verifier available!"); 19229 } 19230 } 19231 19232 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 19233 boolean printedHeader = false; 19234 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 19235 while (it.hasNext()) { 19236 String name = it.next(); 19237 SharedLibraryEntry ent = mSharedLibraries.get(name); 19238 if (!checkin) { 19239 if (!printedHeader) { 19240 if (dumpState.onTitlePrinted()) 19241 pw.println(); 19242 pw.println("Libraries:"); 19243 printedHeader = true; 19244 } 19245 pw.print(" "); 19246 } else { 19247 pw.print("lib,"); 19248 } 19249 pw.print(name); 19250 if (!checkin) { 19251 pw.print(" -> "); 19252 } 19253 if (ent.path != null) { 19254 if (!checkin) { 19255 pw.print("(jar) "); 19256 pw.print(ent.path); 19257 } else { 19258 pw.print(",jar,"); 19259 pw.print(ent.path); 19260 } 19261 } else { 19262 if (!checkin) { 19263 pw.print("(apk) "); 19264 pw.print(ent.apk); 19265 } else { 19266 pw.print(",apk,"); 19267 pw.print(ent.apk); 19268 } 19269 } 19270 pw.println(); 19271 } 19272 } 19273 19274 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19275 if (dumpState.onTitlePrinted()) 19276 pw.println(); 19277 if (!checkin) { 19278 pw.println("Features:"); 19279 } 19280 19281 for (FeatureInfo feat : mAvailableFeatures.values()) { 19282 if (checkin) { 19283 pw.print("feat,"); 19284 pw.print(feat.name); 19285 pw.print(","); 19286 pw.println(feat.version); 19287 } else { 19288 pw.print(" "); 19289 pw.print(feat.name); 19290 if (feat.version > 0) { 19291 pw.print(" version="); 19292 pw.print(feat.version); 19293 } 19294 pw.println(); 19295 } 19296 } 19297 } 19298 19299 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19300 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19301 : "Activity Resolver Table:", " ", packageName, 19302 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19303 dumpState.setTitlePrinted(true); 19304 } 19305 } 19306 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19307 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19308 : "Receiver Resolver Table:", " ", packageName, 19309 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19310 dumpState.setTitlePrinted(true); 19311 } 19312 } 19313 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19314 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19315 : "Service Resolver Table:", " ", packageName, 19316 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19317 dumpState.setTitlePrinted(true); 19318 } 19319 } 19320 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19321 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19322 : "Provider Resolver Table:", " ", packageName, 19323 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19324 dumpState.setTitlePrinted(true); 19325 } 19326 } 19327 19328 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19329 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19330 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19331 int user = mSettings.mPreferredActivities.keyAt(i); 19332 if (pir.dump(pw, 19333 dumpState.getTitlePrinted() 19334 ? "\nPreferred Activities User " + user + ":" 19335 : "Preferred Activities User " + user + ":", " ", 19336 packageName, true, false)) { 19337 dumpState.setTitlePrinted(true); 19338 } 19339 } 19340 } 19341 19342 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19343 pw.flush(); 19344 FileOutputStream fout = new FileOutputStream(fd); 19345 BufferedOutputStream str = new BufferedOutputStream(fout); 19346 XmlSerializer serializer = new FastXmlSerializer(); 19347 try { 19348 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19349 serializer.startDocument(null, true); 19350 serializer.setFeature( 19351 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19352 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19353 serializer.endDocument(); 19354 serializer.flush(); 19355 } catch (IllegalArgumentException e) { 19356 pw.println("Failed writing: " + e); 19357 } catch (IllegalStateException e) { 19358 pw.println("Failed writing: " + e); 19359 } catch (IOException e) { 19360 pw.println("Failed writing: " + e); 19361 } 19362 } 19363 19364 if (!checkin 19365 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19366 && packageName == null) { 19367 pw.println(); 19368 int count = mSettings.mPackages.size(); 19369 if (count == 0) { 19370 pw.println("No applications!"); 19371 pw.println(); 19372 } else { 19373 final String prefix = " "; 19374 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19375 if (allPackageSettings.size() == 0) { 19376 pw.println("No domain preferred apps!"); 19377 pw.println(); 19378 } else { 19379 pw.println("App verification status:"); 19380 pw.println(); 19381 count = 0; 19382 for (PackageSetting ps : allPackageSettings) { 19383 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19384 if (ivi == null || ivi.getPackageName() == null) continue; 19385 pw.println(prefix + "Package: " + ivi.getPackageName()); 19386 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19387 pw.println(prefix + "Status: " + ivi.getStatusString()); 19388 pw.println(); 19389 count++; 19390 } 19391 if (count == 0) { 19392 pw.println(prefix + "No app verification established."); 19393 pw.println(); 19394 } 19395 for (int userId : sUserManager.getUserIds()) { 19396 pw.println("App linkages for user " + userId + ":"); 19397 pw.println(); 19398 count = 0; 19399 for (PackageSetting ps : allPackageSettings) { 19400 final long status = ps.getDomainVerificationStatusForUser(userId); 19401 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19402 continue; 19403 } 19404 pw.println(prefix + "Package: " + ps.name); 19405 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19406 String statusStr = IntentFilterVerificationInfo. 19407 getStatusStringFromValue(status); 19408 pw.println(prefix + "Status: " + statusStr); 19409 pw.println(); 19410 count++; 19411 } 19412 if (count == 0) { 19413 pw.println(prefix + "No configured app linkages."); 19414 pw.println(); 19415 } 19416 } 19417 } 19418 } 19419 } 19420 19421 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19422 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19423 if (packageName == null && permissionNames == null) { 19424 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19425 if (iperm == 0) { 19426 if (dumpState.onTitlePrinted()) 19427 pw.println(); 19428 pw.println("AppOp Permissions:"); 19429 } 19430 pw.print(" AppOp Permission "); 19431 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19432 pw.println(":"); 19433 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19434 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19435 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19436 } 19437 } 19438 } 19439 } 19440 19441 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19442 boolean printedSomething = false; 19443 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19444 if (packageName != null && !packageName.equals(p.info.packageName)) { 19445 continue; 19446 } 19447 if (!printedSomething) { 19448 if (dumpState.onTitlePrinted()) 19449 pw.println(); 19450 pw.println("Registered ContentProviders:"); 19451 printedSomething = true; 19452 } 19453 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19454 pw.print(" "); pw.println(p.toString()); 19455 } 19456 printedSomething = false; 19457 for (Map.Entry<String, PackageParser.Provider> entry : 19458 mProvidersByAuthority.entrySet()) { 19459 PackageParser.Provider p = entry.getValue(); 19460 if (packageName != null && !packageName.equals(p.info.packageName)) { 19461 continue; 19462 } 19463 if (!printedSomething) { 19464 if (dumpState.onTitlePrinted()) 19465 pw.println(); 19466 pw.println("ContentProvider Authorities:"); 19467 printedSomething = true; 19468 } 19469 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19470 pw.print(" "); pw.println(p.toString()); 19471 if (p.info != null && p.info.applicationInfo != null) { 19472 final String appInfo = p.info.applicationInfo.toString(); 19473 pw.print(" applicationInfo="); pw.println(appInfo); 19474 } 19475 } 19476 } 19477 19478 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19479 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19480 } 19481 19482 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19483 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19484 } 19485 19486 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19487 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19488 } 19489 19490 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19491 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19492 } 19493 19494 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19495 // XXX should handle packageName != null by dumping only install data that 19496 // the given package is involved with. 19497 if (dumpState.onTitlePrinted()) pw.println(); 19498 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19499 } 19500 19501 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19502 // XXX should handle packageName != null by dumping only install data that 19503 // the given package is involved with. 19504 if (dumpState.onTitlePrinted()) pw.println(); 19505 19506 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19507 ipw.println(); 19508 ipw.println("Frozen packages:"); 19509 ipw.increaseIndent(); 19510 if (mFrozenPackages.size() == 0) { 19511 ipw.println("(none)"); 19512 } else { 19513 for (int i = 0; i < mFrozenPackages.size(); i++) { 19514 ipw.println(mFrozenPackages.valueAt(i)); 19515 } 19516 } 19517 ipw.decreaseIndent(); 19518 } 19519 19520 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19521 if (dumpState.onTitlePrinted()) pw.println(); 19522 dumpDexoptStateLPr(pw, packageName); 19523 } 19524 19525 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19526 if (dumpState.onTitlePrinted()) pw.println(); 19527 dumpCompilerStatsLPr(pw, packageName); 19528 } 19529 19530 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19531 if (dumpState.onTitlePrinted()) pw.println(); 19532 mSettings.dumpReadMessagesLPr(pw, dumpState); 19533 19534 pw.println(); 19535 pw.println("Package warning messages:"); 19536 BufferedReader in = null; 19537 String line = null; 19538 try { 19539 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19540 while ((line = in.readLine()) != null) { 19541 if (line.contains("ignored: updated version")) continue; 19542 pw.println(line); 19543 } 19544 } catch (IOException ignored) { 19545 } finally { 19546 IoUtils.closeQuietly(in); 19547 } 19548 } 19549 19550 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19551 BufferedReader in = null; 19552 String line = null; 19553 try { 19554 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19555 while ((line = in.readLine()) != null) { 19556 if (line.contains("ignored: updated version")) continue; 19557 pw.print("msg,"); 19558 pw.println(line); 19559 } 19560 } catch (IOException ignored) { 19561 } finally { 19562 IoUtils.closeQuietly(in); 19563 } 19564 } 19565 } 19566 } 19567 19568 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19569 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19570 ipw.println(); 19571 ipw.println("Dexopt state:"); 19572 ipw.increaseIndent(); 19573 Collection<PackageParser.Package> packages = null; 19574 if (packageName != null) { 19575 PackageParser.Package targetPackage = mPackages.get(packageName); 19576 if (targetPackage != null) { 19577 packages = Collections.singletonList(targetPackage); 19578 } else { 19579 ipw.println("Unable to find package: " + packageName); 19580 return; 19581 } 19582 } else { 19583 packages = mPackages.values(); 19584 } 19585 19586 for (PackageParser.Package pkg : packages) { 19587 ipw.println("[" + pkg.packageName + "]"); 19588 ipw.increaseIndent(); 19589 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19590 ipw.decreaseIndent(); 19591 } 19592 } 19593 19594 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19595 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19596 ipw.println(); 19597 ipw.println("Compiler stats:"); 19598 ipw.increaseIndent(); 19599 Collection<PackageParser.Package> packages = null; 19600 if (packageName != null) { 19601 PackageParser.Package targetPackage = mPackages.get(packageName); 19602 if (targetPackage != null) { 19603 packages = Collections.singletonList(targetPackage); 19604 } else { 19605 ipw.println("Unable to find package: " + packageName); 19606 return; 19607 } 19608 } else { 19609 packages = mPackages.values(); 19610 } 19611 19612 for (PackageParser.Package pkg : packages) { 19613 ipw.println("[" + pkg.packageName + "]"); 19614 ipw.increaseIndent(); 19615 19616 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19617 if (stats == null) { 19618 ipw.println("(No recorded stats)"); 19619 } else { 19620 stats.dump(ipw); 19621 } 19622 ipw.decreaseIndent(); 19623 } 19624 } 19625 19626 private String dumpDomainString(String packageName) { 19627 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19628 .getList(); 19629 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19630 19631 ArraySet<String> result = new ArraySet<>(); 19632 if (iviList.size() > 0) { 19633 for (IntentFilterVerificationInfo ivi : iviList) { 19634 for (String host : ivi.getDomains()) { 19635 result.add(host); 19636 } 19637 } 19638 } 19639 if (filters != null && filters.size() > 0) { 19640 for (IntentFilter filter : filters) { 19641 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19642 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19643 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19644 result.addAll(filter.getHostsList()); 19645 } 19646 } 19647 } 19648 19649 StringBuilder sb = new StringBuilder(result.size() * 16); 19650 for (String domain : result) { 19651 if (sb.length() > 0) sb.append(" "); 19652 sb.append(domain); 19653 } 19654 return sb.toString(); 19655 } 19656 19657 // ------- apps on sdcard specific code ------- 19658 static final boolean DEBUG_SD_INSTALL = false; 19659 19660 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19661 19662 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19663 19664 private boolean mMediaMounted = false; 19665 19666 static String getEncryptKey() { 19667 try { 19668 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19669 SD_ENCRYPTION_KEYSTORE_NAME); 19670 if (sdEncKey == null) { 19671 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19672 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19673 if (sdEncKey == null) { 19674 Slog.e(TAG, "Failed to create encryption keys"); 19675 return null; 19676 } 19677 } 19678 return sdEncKey; 19679 } catch (NoSuchAlgorithmException nsae) { 19680 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19681 return null; 19682 } catch (IOException ioe) { 19683 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19684 return null; 19685 } 19686 } 19687 19688 /* 19689 * Update media status on PackageManager. 19690 */ 19691 @Override 19692 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19693 int callingUid = Binder.getCallingUid(); 19694 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19695 throw new SecurityException("Media status can only be updated by the system"); 19696 } 19697 // reader; this apparently protects mMediaMounted, but should probably 19698 // be a different lock in that case. 19699 synchronized (mPackages) { 19700 Log.i(TAG, "Updating external media status from " 19701 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19702 + (mediaStatus ? "mounted" : "unmounted")); 19703 if (DEBUG_SD_INSTALL) 19704 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19705 + ", mMediaMounted=" + mMediaMounted); 19706 if (mediaStatus == mMediaMounted) { 19707 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19708 : 0, -1); 19709 mHandler.sendMessage(msg); 19710 return; 19711 } 19712 mMediaMounted = mediaStatus; 19713 } 19714 // Queue up an async operation since the package installation may take a 19715 // little while. 19716 mHandler.post(new Runnable() { 19717 public void run() { 19718 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19719 } 19720 }); 19721 } 19722 19723 /** 19724 * Called by StorageManagerService when the initial ASECs to scan are available. 19725 * Should block until all the ASEC containers are finished being scanned. 19726 */ 19727 public void scanAvailableAsecs() { 19728 updateExternalMediaStatusInner(true, false, false); 19729 } 19730 19731 /* 19732 * Collect information of applications on external media, map them against 19733 * existing containers and update information based on current mount status. 19734 * Please note that we always have to report status if reportStatus has been 19735 * set to true especially when unloading packages. 19736 */ 19737 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19738 boolean externalStorage) { 19739 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19740 int[] uidArr = EmptyArray.INT; 19741 19742 final String[] list = PackageHelper.getSecureContainerList(); 19743 if (ArrayUtils.isEmpty(list)) { 19744 Log.i(TAG, "No secure containers found"); 19745 } else { 19746 // Process list of secure containers and categorize them 19747 // as active or stale based on their package internal state. 19748 19749 // reader 19750 synchronized (mPackages) { 19751 for (String cid : list) { 19752 // Leave stages untouched for now; installer service owns them 19753 if (PackageInstallerService.isStageName(cid)) continue; 19754 19755 if (DEBUG_SD_INSTALL) 19756 Log.i(TAG, "Processing container " + cid); 19757 String pkgName = getAsecPackageName(cid); 19758 if (pkgName == null) { 19759 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19760 continue; 19761 } 19762 if (DEBUG_SD_INSTALL) 19763 Log.i(TAG, "Looking for pkg : " + pkgName); 19764 19765 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19766 if (ps == null) { 19767 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19768 continue; 19769 } 19770 19771 /* 19772 * Skip packages that are not external if we're unmounting 19773 * external storage. 19774 */ 19775 if (externalStorage && !isMounted && !isExternal(ps)) { 19776 continue; 19777 } 19778 19779 final AsecInstallArgs args = new AsecInstallArgs(cid, 19780 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19781 // The package status is changed only if the code path 19782 // matches between settings and the container id. 19783 if (ps.codePathString != null 19784 && ps.codePathString.startsWith(args.getCodePath())) { 19785 if (DEBUG_SD_INSTALL) { 19786 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19787 + " at code path: " + ps.codePathString); 19788 } 19789 19790 // We do have a valid package installed on sdcard 19791 processCids.put(args, ps.codePathString); 19792 final int uid = ps.appId; 19793 if (uid != -1) { 19794 uidArr = ArrayUtils.appendInt(uidArr, uid); 19795 } 19796 } else { 19797 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19798 + ps.codePathString); 19799 } 19800 } 19801 } 19802 19803 Arrays.sort(uidArr); 19804 } 19805 19806 // Process packages with valid entries. 19807 if (isMounted) { 19808 if (DEBUG_SD_INSTALL) 19809 Log.i(TAG, "Loading packages"); 19810 loadMediaPackages(processCids, uidArr, externalStorage); 19811 startCleaningPackages(); 19812 mInstallerService.onSecureContainersAvailable(); 19813 } else { 19814 if (DEBUG_SD_INSTALL) 19815 Log.i(TAG, "Unloading packages"); 19816 unloadMediaPackages(processCids, uidArr, reportStatus); 19817 } 19818 } 19819 19820 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19821 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19822 final int size = infos.size(); 19823 final String[] packageNames = new String[size]; 19824 final int[] packageUids = new int[size]; 19825 for (int i = 0; i < size; i++) { 19826 final ApplicationInfo info = infos.get(i); 19827 packageNames[i] = info.packageName; 19828 packageUids[i] = info.uid; 19829 } 19830 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19831 finishedReceiver); 19832 } 19833 19834 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19835 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19836 sendResourcesChangedBroadcast(mediaStatus, replacing, 19837 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19838 } 19839 19840 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19841 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19842 int size = pkgList.length; 19843 if (size > 0) { 19844 // Send broadcasts here 19845 Bundle extras = new Bundle(); 19846 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19847 if (uidArr != null) { 19848 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19849 } 19850 if (replacing) { 19851 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19852 } 19853 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19854 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19855 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19856 } 19857 } 19858 19859 /* 19860 * Look at potentially valid container ids from processCids If package 19861 * information doesn't match the one on record or package scanning fails, 19862 * the cid is added to list of removeCids. We currently don't delete stale 19863 * containers. 19864 */ 19865 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19866 boolean externalStorage) { 19867 ArrayList<String> pkgList = new ArrayList<String>(); 19868 Set<AsecInstallArgs> keys = processCids.keySet(); 19869 19870 for (AsecInstallArgs args : keys) { 19871 String codePath = processCids.get(args); 19872 if (DEBUG_SD_INSTALL) 19873 Log.i(TAG, "Loading container : " + args.cid); 19874 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19875 try { 19876 // Make sure there are no container errors first. 19877 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19878 Slog.e(TAG, "Failed to mount cid : " + args.cid 19879 + " when installing from sdcard"); 19880 continue; 19881 } 19882 // Check code path here. 19883 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19884 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19885 + " does not match one in settings " + codePath); 19886 continue; 19887 } 19888 // Parse package 19889 int parseFlags = mDefParseFlags; 19890 if (args.isExternalAsec()) { 19891 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19892 } 19893 if (args.isFwdLocked()) { 19894 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19895 } 19896 19897 synchronized (mInstallLock) { 19898 PackageParser.Package pkg = null; 19899 try { 19900 // Sadly we don't know the package name yet to freeze it 19901 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19902 SCAN_IGNORE_FROZEN, 0, null); 19903 } catch (PackageManagerException e) { 19904 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19905 } 19906 // Scan the package 19907 if (pkg != null) { 19908 /* 19909 * TODO why is the lock being held? doPostInstall is 19910 * called in other places without the lock. This needs 19911 * to be straightened out. 19912 */ 19913 // writer 19914 synchronized (mPackages) { 19915 retCode = PackageManager.INSTALL_SUCCEEDED; 19916 pkgList.add(pkg.packageName); 19917 // Post process args 19918 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19919 pkg.applicationInfo.uid); 19920 } 19921 } else { 19922 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19923 } 19924 } 19925 19926 } finally { 19927 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19928 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19929 } 19930 } 19931 } 19932 // writer 19933 synchronized (mPackages) { 19934 // If the platform SDK has changed since the last time we booted, 19935 // we need to re-grant app permission to catch any new ones that 19936 // appear. This is really a hack, and means that apps can in some 19937 // cases get permissions that the user didn't initially explicitly 19938 // allow... it would be nice to have some better way to handle 19939 // this situation. 19940 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19941 : mSettings.getInternalVersion(); 19942 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19943 : StorageManager.UUID_PRIVATE_INTERNAL; 19944 19945 int updateFlags = UPDATE_PERMISSIONS_ALL; 19946 if (ver.sdkVersion != mSdkVersion) { 19947 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19948 + mSdkVersion + "; regranting permissions for external"); 19949 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19950 } 19951 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19952 19953 // Yay, everything is now upgraded 19954 ver.forceCurrent(); 19955 19956 // can downgrade to reader 19957 // Persist settings 19958 mSettings.writeLPr(); 19959 } 19960 // Send a broadcast to let everyone know we are done processing 19961 if (pkgList.size() > 0) { 19962 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19963 } 19964 } 19965 19966 /* 19967 * Utility method to unload a list of specified containers 19968 */ 19969 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19970 // Just unmount all valid containers. 19971 for (AsecInstallArgs arg : cidArgs) { 19972 synchronized (mInstallLock) { 19973 arg.doPostDeleteLI(false); 19974 } 19975 } 19976 } 19977 19978 /* 19979 * Unload packages mounted on external media. This involves deleting package 19980 * data from internal structures, sending broadcasts about disabled packages, 19981 * gc'ing to free up references, unmounting all secure containers 19982 * corresponding to packages on external media, and posting a 19983 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19984 * that we always have to post this message if status has been requested no 19985 * matter what. 19986 */ 19987 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19988 final boolean reportStatus) { 19989 if (DEBUG_SD_INSTALL) 19990 Log.i(TAG, "unloading media packages"); 19991 ArrayList<String> pkgList = new ArrayList<String>(); 19992 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19993 final Set<AsecInstallArgs> keys = processCids.keySet(); 19994 for (AsecInstallArgs args : keys) { 19995 String pkgName = args.getPackageName(); 19996 if (DEBUG_SD_INSTALL) 19997 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19998 // Delete package internally 19999 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20000 synchronized (mInstallLock) { 20001 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20002 final boolean res; 20003 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 20004 "unloadMediaPackages")) { 20005 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 20006 null); 20007 } 20008 if (res) { 20009 pkgList.add(pkgName); 20010 } else { 20011 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 20012 failedList.add(args); 20013 } 20014 } 20015 } 20016 20017 // reader 20018 synchronized (mPackages) { 20019 // We didn't update the settings after removing each package; 20020 // write them now for all packages. 20021 mSettings.writeLPr(); 20022 } 20023 20024 // We have to absolutely send UPDATED_MEDIA_STATUS only 20025 // after confirming that all the receivers processed the ordered 20026 // broadcast when packages get disabled, force a gc to clean things up. 20027 // and unload all the containers. 20028 if (pkgList.size() > 0) { 20029 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 20030 new IIntentReceiver.Stub() { 20031 public void performReceive(Intent intent, int resultCode, String data, 20032 Bundle extras, boolean ordered, boolean sticky, 20033 int sendingUser) throws RemoteException { 20034 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 20035 reportStatus ? 1 : 0, 1, keys); 20036 mHandler.sendMessage(msg); 20037 } 20038 }); 20039 } else { 20040 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 20041 keys); 20042 mHandler.sendMessage(msg); 20043 } 20044 } 20045 20046 private void loadPrivatePackages(final VolumeInfo vol) { 20047 mHandler.post(new Runnable() { 20048 @Override 20049 public void run() { 20050 loadPrivatePackagesInner(vol); 20051 } 20052 }); 20053 } 20054 20055 private void loadPrivatePackagesInner(VolumeInfo vol) { 20056 final String volumeUuid = vol.fsUuid; 20057 if (TextUtils.isEmpty(volumeUuid)) { 20058 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 20059 return; 20060 } 20061 20062 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 20063 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 20064 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 20065 20066 final VersionInfo ver; 20067 final List<PackageSetting> packages; 20068 synchronized (mPackages) { 20069 ver = mSettings.findOrCreateVersion(volumeUuid); 20070 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20071 } 20072 20073 for (PackageSetting ps : packages) { 20074 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 20075 synchronized (mInstallLock) { 20076 final PackageParser.Package pkg; 20077 try { 20078 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 20079 loaded.add(pkg.applicationInfo); 20080 20081 } catch (PackageManagerException e) { 20082 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 20083 } 20084 20085 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 20086 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 20087 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 20088 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20089 } 20090 } 20091 } 20092 20093 // Reconcile app data for all started/unlocked users 20094 final StorageManager sm = mContext.getSystemService(StorageManager.class); 20095 final UserManager um = mContext.getSystemService(UserManager.class); 20096 UserManagerInternal umInternal = getUserManagerInternal(); 20097 for (UserInfo user : um.getUsers()) { 20098 final int flags; 20099 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20100 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20101 } else if (umInternal.isUserRunning(user.id)) { 20102 flags = StorageManager.FLAG_STORAGE_DE; 20103 } else { 20104 continue; 20105 } 20106 20107 try { 20108 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 20109 synchronized (mInstallLock) { 20110 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 20111 } 20112 } catch (IllegalStateException e) { 20113 // Device was probably ejected, and we'll process that event momentarily 20114 Slog.w(TAG, "Failed to prepare storage: " + e); 20115 } 20116 } 20117 20118 synchronized (mPackages) { 20119 int updateFlags = UPDATE_PERMISSIONS_ALL; 20120 if (ver.sdkVersion != mSdkVersion) { 20121 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20122 + mSdkVersion + "; regranting permissions for " + volumeUuid); 20123 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20124 } 20125 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20126 20127 // Yay, everything is now upgraded 20128 ver.forceCurrent(); 20129 20130 mSettings.writeLPr(); 20131 } 20132 20133 for (PackageFreezer freezer : freezers) { 20134 freezer.close(); 20135 } 20136 20137 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 20138 sendResourcesChangedBroadcast(true, false, loaded, null); 20139 } 20140 20141 private void unloadPrivatePackages(final VolumeInfo vol) { 20142 mHandler.post(new Runnable() { 20143 @Override 20144 public void run() { 20145 unloadPrivatePackagesInner(vol); 20146 } 20147 }); 20148 } 20149 20150 private void unloadPrivatePackagesInner(VolumeInfo vol) { 20151 final String volumeUuid = vol.fsUuid; 20152 if (TextUtils.isEmpty(volumeUuid)) { 20153 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 20154 return; 20155 } 20156 20157 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 20158 synchronized (mInstallLock) { 20159 synchronized (mPackages) { 20160 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 20161 for (PackageSetting ps : packages) { 20162 if (ps.pkg == null) continue; 20163 20164 final ApplicationInfo info = ps.pkg.applicationInfo; 20165 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20166 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20167 20168 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 20169 "unloadPrivatePackagesInner")) { 20170 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 20171 false, null)) { 20172 unloaded.add(info); 20173 } else { 20174 Slog.w(TAG, "Failed to unload " + ps.codePath); 20175 } 20176 } 20177 20178 // Try very hard to release any references to this package 20179 // so we don't risk the system server being killed due to 20180 // open FDs 20181 AttributeCache.instance().removePackage(ps.name); 20182 } 20183 20184 mSettings.writeLPr(); 20185 } 20186 } 20187 20188 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 20189 sendResourcesChangedBroadcast(false, false, unloaded, null); 20190 20191 // Try very hard to release any references to this path so we don't risk 20192 // the system server being killed due to open FDs 20193 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 20194 20195 for (int i = 0; i < 3; i++) { 20196 System.gc(); 20197 System.runFinalization(); 20198 } 20199 } 20200 20201 /** 20202 * Prepare storage areas for given user on all mounted devices. 20203 */ 20204 void prepareUserData(int userId, int userSerial, int flags) { 20205 synchronized (mInstallLock) { 20206 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20207 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20208 final String volumeUuid = vol.getFsUuid(); 20209 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 20210 } 20211 } 20212 } 20213 20214 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 20215 boolean allowRecover) { 20216 // Prepare storage and verify that serial numbers are consistent; if 20217 // there's a mismatch we need to destroy to avoid leaking data 20218 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20219 try { 20220 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 20221 20222 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 20223 UserManagerService.enforceSerialNumber( 20224 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 20225 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20226 UserManagerService.enforceSerialNumber( 20227 Environment.getDataSystemDeDirectory(userId), userSerial); 20228 } 20229 } 20230 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 20231 UserManagerService.enforceSerialNumber( 20232 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 20233 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20234 UserManagerService.enforceSerialNumber( 20235 Environment.getDataSystemCeDirectory(userId), userSerial); 20236 } 20237 } 20238 20239 synchronized (mInstallLock) { 20240 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20241 } 20242 } catch (Exception e) { 20243 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20244 + " because we failed to prepare: " + e); 20245 destroyUserDataLI(volumeUuid, userId, 20246 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20247 20248 if (allowRecover) { 20249 // Try one last time; if we fail again we're really in trouble 20250 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20251 } 20252 } 20253 } 20254 20255 /** 20256 * Destroy storage areas for given user on all mounted devices. 20257 */ 20258 void destroyUserData(int userId, int flags) { 20259 synchronized (mInstallLock) { 20260 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20261 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20262 final String volumeUuid = vol.getFsUuid(); 20263 destroyUserDataLI(volumeUuid, userId, flags); 20264 } 20265 } 20266 } 20267 20268 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20269 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20270 try { 20271 // Clean up app data, profile data, and media data 20272 mInstaller.destroyUserData(volumeUuid, userId, flags); 20273 20274 // Clean up system data 20275 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20276 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20277 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20278 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20279 } 20280 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20281 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20282 } 20283 } 20284 20285 // Data with special labels is now gone, so finish the job 20286 storage.destroyUserStorage(volumeUuid, userId, flags); 20287 20288 } catch (Exception e) { 20289 logCriticalInfo(Log.WARN, 20290 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20291 } 20292 } 20293 20294 /** 20295 * Examine all users present on given mounted volume, and destroy data 20296 * belonging to users that are no longer valid, or whose user ID has been 20297 * recycled. 20298 */ 20299 private void reconcileUsers(String volumeUuid) { 20300 final List<File> files = new ArrayList<>(); 20301 Collections.addAll(files, FileUtils 20302 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20303 Collections.addAll(files, FileUtils 20304 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20305 Collections.addAll(files, FileUtils 20306 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20307 Collections.addAll(files, FileUtils 20308 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20309 for (File file : files) { 20310 if (!file.isDirectory()) continue; 20311 20312 final int userId; 20313 final UserInfo info; 20314 try { 20315 userId = Integer.parseInt(file.getName()); 20316 info = sUserManager.getUserInfo(userId); 20317 } catch (NumberFormatException e) { 20318 Slog.w(TAG, "Invalid user directory " + file); 20319 continue; 20320 } 20321 20322 boolean destroyUser = false; 20323 if (info == null) { 20324 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20325 + " because no matching user was found"); 20326 destroyUser = true; 20327 } else if (!mOnlyCore) { 20328 try { 20329 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20330 } catch (IOException e) { 20331 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20332 + " because we failed to enforce serial number: " + e); 20333 destroyUser = true; 20334 } 20335 } 20336 20337 if (destroyUser) { 20338 synchronized (mInstallLock) { 20339 destroyUserDataLI(volumeUuid, userId, 20340 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20341 } 20342 } 20343 } 20344 } 20345 20346 private void assertPackageKnown(String volumeUuid, String packageName) 20347 throws PackageManagerException { 20348 synchronized (mPackages) { 20349 // Normalize package name to handle renamed packages 20350 packageName = normalizePackageNameLPr(packageName); 20351 20352 final PackageSetting ps = mSettings.mPackages.get(packageName); 20353 if (ps == null) { 20354 throw new PackageManagerException("Package " + packageName + " is unknown"); 20355 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20356 throw new PackageManagerException( 20357 "Package " + packageName + " found on unknown volume " + volumeUuid 20358 + "; expected volume " + ps.volumeUuid); 20359 } 20360 } 20361 } 20362 20363 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20364 throws PackageManagerException { 20365 synchronized (mPackages) { 20366 // Normalize package name to handle renamed packages 20367 packageName = normalizePackageNameLPr(packageName); 20368 20369 final PackageSetting ps = mSettings.mPackages.get(packageName); 20370 if (ps == null) { 20371 throw new PackageManagerException("Package " + packageName + " is unknown"); 20372 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20373 throw new PackageManagerException( 20374 "Package " + packageName + " found on unknown volume " + volumeUuid 20375 + "; expected volume " + ps.volumeUuid); 20376 } else if (!ps.getInstalled(userId)) { 20377 throw new PackageManagerException( 20378 "Package " + packageName + " not installed for user " + userId); 20379 } 20380 } 20381 } 20382 20383 /** 20384 * Examine all apps present on given mounted volume, and destroy apps that 20385 * aren't expected, either due to uninstallation or reinstallation on 20386 * another volume. 20387 */ 20388 private void reconcileApps(String volumeUuid) { 20389 final File[] files = FileUtils 20390 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20391 for (File file : files) { 20392 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20393 && !PackageInstallerService.isStageName(file.getName()); 20394 if (!isPackage) { 20395 // Ignore entries which are not packages 20396 continue; 20397 } 20398 20399 try { 20400 final PackageLite pkg = PackageParser.parsePackageLite(file, 20401 PackageParser.PARSE_MUST_BE_APK); 20402 assertPackageKnown(volumeUuid, pkg.packageName); 20403 20404 } catch (PackageParserException | PackageManagerException e) { 20405 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20406 synchronized (mInstallLock) { 20407 removeCodePathLI(file); 20408 } 20409 } 20410 } 20411 } 20412 20413 /** 20414 * Reconcile all app data for the given user. 20415 * <p> 20416 * Verifies that directories exist and that ownership and labeling is 20417 * correct for all installed apps on all mounted volumes. 20418 */ 20419 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20420 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20421 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20422 final String volumeUuid = vol.getFsUuid(); 20423 synchronized (mInstallLock) { 20424 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20425 } 20426 } 20427 } 20428 20429 /** 20430 * Reconcile all app data on given mounted volume. 20431 * <p> 20432 * Destroys app data that isn't expected, either due to uninstallation or 20433 * reinstallation on another volume. 20434 * <p> 20435 * Verifies that directories exist and that ownership and labeling is 20436 * correct for all installed apps. 20437 */ 20438 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20439 boolean migrateAppData) { 20440 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20441 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20442 20443 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20444 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20445 20446 // First look for stale data that doesn't belong, and check if things 20447 // have changed since we did our last restorecon 20448 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20449 if (StorageManager.isFileEncryptedNativeOrEmulated() 20450 && !StorageManager.isUserKeyUnlocked(userId)) { 20451 throw new RuntimeException( 20452 "Yikes, someone asked us to reconcile CE storage while " + userId 20453 + " was still locked; this would have caused massive data loss!"); 20454 } 20455 20456 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20457 for (File file : files) { 20458 final String packageName = file.getName(); 20459 try { 20460 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20461 } catch (PackageManagerException e) { 20462 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20463 try { 20464 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20465 StorageManager.FLAG_STORAGE_CE, 0); 20466 } catch (InstallerException e2) { 20467 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20468 } 20469 } 20470 } 20471 } 20472 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20473 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20474 for (File file : files) { 20475 final String packageName = file.getName(); 20476 try { 20477 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20478 } catch (PackageManagerException e) { 20479 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20480 try { 20481 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20482 StorageManager.FLAG_STORAGE_DE, 0); 20483 } catch (InstallerException e2) { 20484 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20485 } 20486 } 20487 } 20488 } 20489 20490 // Ensure that data directories are ready to roll for all packages 20491 // installed for this volume and user 20492 final List<PackageSetting> packages; 20493 synchronized (mPackages) { 20494 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20495 } 20496 int preparedCount = 0; 20497 for (PackageSetting ps : packages) { 20498 final String packageName = ps.name; 20499 if (ps.pkg == null) { 20500 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20501 // TODO: might be due to legacy ASEC apps; we should circle back 20502 // and reconcile again once they're scanned 20503 continue; 20504 } 20505 20506 if (ps.getInstalled(userId)) { 20507 prepareAppDataLIF(ps.pkg, userId, flags); 20508 20509 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20510 // We may have just shuffled around app data directories, so 20511 // prepare them one more time 20512 prepareAppDataLIF(ps.pkg, userId, flags); 20513 } 20514 20515 preparedCount++; 20516 } 20517 } 20518 20519 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20520 } 20521 20522 /** 20523 * Prepare app data for the given app just after it was installed or 20524 * upgraded. This method carefully only touches users that it's installed 20525 * for, and it forces a restorecon to handle any seinfo changes. 20526 * <p> 20527 * Verifies that directories exist and that ownership and labeling is 20528 * correct for all installed apps. If there is an ownership mismatch, it 20529 * will try recovering system apps by wiping data; third-party app data is 20530 * left intact. 20531 * <p> 20532 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20533 */ 20534 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20535 final PackageSetting ps; 20536 synchronized (mPackages) { 20537 ps = mSettings.mPackages.get(pkg.packageName); 20538 mSettings.writeKernelMappingLPr(ps); 20539 } 20540 20541 final UserManager um = mContext.getSystemService(UserManager.class); 20542 UserManagerInternal umInternal = getUserManagerInternal(); 20543 for (UserInfo user : um.getUsers()) { 20544 final int flags; 20545 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20546 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20547 } else if (umInternal.isUserRunning(user.id)) { 20548 flags = StorageManager.FLAG_STORAGE_DE; 20549 } else { 20550 continue; 20551 } 20552 20553 if (ps.getInstalled(user.id)) { 20554 // TODO: when user data is locked, mark that we're still dirty 20555 prepareAppDataLIF(pkg, user.id, flags); 20556 } 20557 } 20558 } 20559 20560 /** 20561 * Prepare app data for the given app. 20562 * <p> 20563 * Verifies that directories exist and that ownership and labeling is 20564 * correct for all installed apps. If there is an ownership mismatch, this 20565 * will try recovering system apps by wiping data; third-party app data is 20566 * left intact. 20567 */ 20568 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20569 if (pkg == null) { 20570 Slog.wtf(TAG, "Package was null!", new Throwable()); 20571 return; 20572 } 20573 prepareAppDataLeafLIF(pkg, userId, flags); 20574 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20575 for (int i = 0; i < childCount; i++) { 20576 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20577 } 20578 } 20579 20580 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20581 if (DEBUG_APP_DATA) { 20582 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20583 + Integer.toHexString(flags)); 20584 } 20585 20586 final String volumeUuid = pkg.volumeUuid; 20587 final String packageName = pkg.packageName; 20588 final ApplicationInfo app = pkg.applicationInfo; 20589 final int appId = UserHandle.getAppId(app.uid); 20590 20591 Preconditions.checkNotNull(app.seinfo); 20592 20593 long ceDataInode = -1; 20594 try { 20595 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20596 appId, app.seinfo, app.targetSdkVersion); 20597 } catch (InstallerException e) { 20598 if (app.isSystemApp()) { 20599 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20600 + ", but trying to recover: " + e); 20601 destroyAppDataLeafLIF(pkg, userId, flags); 20602 try { 20603 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20604 appId, app.seinfo, app.targetSdkVersion); 20605 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20606 } catch (InstallerException e2) { 20607 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20608 } 20609 } else { 20610 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20611 } 20612 } 20613 20614 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20615 // TODO: mark this structure as dirty so we persist it! 20616 synchronized (mPackages) { 20617 final PackageSetting ps = mSettings.mPackages.get(packageName); 20618 if (ps != null) { 20619 ps.setCeDataInode(ceDataInode, userId); 20620 } 20621 } 20622 } 20623 20624 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20625 } 20626 20627 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20628 if (pkg == null) { 20629 Slog.wtf(TAG, "Package was null!", new Throwable()); 20630 return; 20631 } 20632 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20633 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20634 for (int i = 0; i < childCount; i++) { 20635 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20636 } 20637 } 20638 20639 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20640 final String volumeUuid = pkg.volumeUuid; 20641 final String packageName = pkg.packageName; 20642 final ApplicationInfo app = pkg.applicationInfo; 20643 20644 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20645 // Create a native library symlink only if we have native libraries 20646 // and if the native libraries are 32 bit libraries. We do not provide 20647 // this symlink for 64 bit libraries. 20648 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20649 final String nativeLibPath = app.nativeLibraryDir; 20650 try { 20651 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20652 nativeLibPath, userId); 20653 } catch (InstallerException e) { 20654 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20655 } 20656 } 20657 } 20658 } 20659 20660 /** 20661 * For system apps on non-FBE devices, this method migrates any existing 20662 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20663 * requested by the app. 20664 */ 20665 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20666 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20667 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20668 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20669 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20670 try { 20671 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20672 storageTarget); 20673 } catch (InstallerException e) { 20674 logCriticalInfo(Log.WARN, 20675 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20676 } 20677 return true; 20678 } else { 20679 return false; 20680 } 20681 } 20682 20683 public PackageFreezer freezePackage(String packageName, String killReason) { 20684 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20685 } 20686 20687 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20688 return new PackageFreezer(packageName, userId, killReason); 20689 } 20690 20691 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20692 String killReason) { 20693 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20694 } 20695 20696 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20697 String killReason) { 20698 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20699 return new PackageFreezer(); 20700 } else { 20701 return freezePackage(packageName, userId, killReason); 20702 } 20703 } 20704 20705 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20706 String killReason) { 20707 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20708 } 20709 20710 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20711 String killReason) { 20712 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20713 return new PackageFreezer(); 20714 } else { 20715 return freezePackage(packageName, userId, killReason); 20716 } 20717 } 20718 20719 /** 20720 * Class that freezes and kills the given package upon creation, and 20721 * unfreezes it upon closing. This is typically used when doing surgery on 20722 * app code/data to prevent the app from running while you're working. 20723 */ 20724 private class PackageFreezer implements AutoCloseable { 20725 private final String mPackageName; 20726 private final PackageFreezer[] mChildren; 20727 20728 private final boolean mWeFroze; 20729 20730 private final AtomicBoolean mClosed = new AtomicBoolean(); 20731 private final CloseGuard mCloseGuard = CloseGuard.get(); 20732 20733 /** 20734 * Create and return a stub freezer that doesn't actually do anything, 20735 * typically used when someone requested 20736 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20737 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20738 */ 20739 public PackageFreezer() { 20740 mPackageName = null; 20741 mChildren = null; 20742 mWeFroze = false; 20743 mCloseGuard.open("close"); 20744 } 20745 20746 public PackageFreezer(String packageName, int userId, String killReason) { 20747 synchronized (mPackages) { 20748 mPackageName = packageName; 20749 mWeFroze = mFrozenPackages.add(mPackageName); 20750 20751 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20752 if (ps != null) { 20753 killApplication(ps.name, ps.appId, userId, killReason); 20754 } 20755 20756 final PackageParser.Package p = mPackages.get(packageName); 20757 if (p != null && p.childPackages != null) { 20758 final int N = p.childPackages.size(); 20759 mChildren = new PackageFreezer[N]; 20760 for (int i = 0; i < N; i++) { 20761 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20762 userId, killReason); 20763 } 20764 } else { 20765 mChildren = null; 20766 } 20767 } 20768 mCloseGuard.open("close"); 20769 } 20770 20771 @Override 20772 protected void finalize() throws Throwable { 20773 try { 20774 mCloseGuard.warnIfOpen(); 20775 close(); 20776 } finally { 20777 super.finalize(); 20778 } 20779 } 20780 20781 @Override 20782 public void close() { 20783 mCloseGuard.close(); 20784 if (mClosed.compareAndSet(false, true)) { 20785 synchronized (mPackages) { 20786 if (mWeFroze) { 20787 mFrozenPackages.remove(mPackageName); 20788 } 20789 20790 if (mChildren != null) { 20791 for (PackageFreezer freezer : mChildren) { 20792 freezer.close(); 20793 } 20794 } 20795 } 20796 } 20797 } 20798 } 20799 20800 /** 20801 * Verify that given package is currently frozen. 20802 */ 20803 private void checkPackageFrozen(String packageName) { 20804 synchronized (mPackages) { 20805 if (!mFrozenPackages.contains(packageName)) { 20806 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20807 } 20808 } 20809 } 20810 20811 @Override 20812 public int movePackage(final String packageName, final String volumeUuid) { 20813 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20814 20815 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20816 final int moveId = mNextMoveId.getAndIncrement(); 20817 mHandler.post(new Runnable() { 20818 @Override 20819 public void run() { 20820 try { 20821 movePackageInternal(packageName, volumeUuid, moveId, user); 20822 } catch (PackageManagerException e) { 20823 Slog.w(TAG, "Failed to move " + packageName, e); 20824 mMoveCallbacks.notifyStatusChanged(moveId, 20825 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20826 } 20827 } 20828 }); 20829 return moveId; 20830 } 20831 20832 private void movePackageInternal(final String packageName, final String volumeUuid, 20833 final int moveId, UserHandle user) throws PackageManagerException { 20834 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20835 final PackageManager pm = mContext.getPackageManager(); 20836 20837 final boolean currentAsec; 20838 final String currentVolumeUuid; 20839 final File codeFile; 20840 final String installerPackageName; 20841 final String packageAbiOverride; 20842 final int appId; 20843 final String seinfo; 20844 final String label; 20845 final int targetSdkVersion; 20846 final PackageFreezer freezer; 20847 final int[] installedUserIds; 20848 20849 // reader 20850 synchronized (mPackages) { 20851 final PackageParser.Package pkg = mPackages.get(packageName); 20852 final PackageSetting ps = mSettings.mPackages.get(packageName); 20853 if (pkg == null || ps == null) { 20854 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20855 } 20856 20857 if (pkg.applicationInfo.isSystemApp()) { 20858 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20859 "Cannot move system application"); 20860 } 20861 20862 if (pkg.applicationInfo.isExternalAsec()) { 20863 currentAsec = true; 20864 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20865 } else if (pkg.applicationInfo.isForwardLocked()) { 20866 currentAsec = true; 20867 currentVolumeUuid = "forward_locked"; 20868 } else { 20869 currentAsec = false; 20870 currentVolumeUuid = ps.volumeUuid; 20871 20872 final File probe = new File(pkg.codePath); 20873 final File probeOat = new File(probe, "oat"); 20874 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20875 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20876 "Move only supported for modern cluster style installs"); 20877 } 20878 } 20879 20880 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20881 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20882 "Package already moved to " + volumeUuid); 20883 } 20884 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20885 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20886 "Device admin cannot be moved"); 20887 } 20888 20889 if (mFrozenPackages.contains(packageName)) { 20890 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20891 "Failed to move already frozen package"); 20892 } 20893 20894 codeFile = new File(pkg.codePath); 20895 installerPackageName = ps.installerPackageName; 20896 packageAbiOverride = ps.cpuAbiOverrideString; 20897 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20898 seinfo = pkg.applicationInfo.seinfo; 20899 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20900 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20901 freezer = freezePackage(packageName, "movePackageInternal"); 20902 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20903 } 20904 20905 final Bundle extras = new Bundle(); 20906 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20907 extras.putString(Intent.EXTRA_TITLE, label); 20908 mMoveCallbacks.notifyCreated(moveId, extras); 20909 20910 int installFlags; 20911 final boolean moveCompleteApp; 20912 final File measurePath; 20913 20914 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20915 installFlags = INSTALL_INTERNAL; 20916 moveCompleteApp = !currentAsec; 20917 measurePath = Environment.getDataAppDirectory(volumeUuid); 20918 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20919 installFlags = INSTALL_EXTERNAL; 20920 moveCompleteApp = false; 20921 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20922 } else { 20923 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20924 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20925 || !volume.isMountedWritable()) { 20926 freezer.close(); 20927 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20928 "Move location not mounted private volume"); 20929 } 20930 20931 Preconditions.checkState(!currentAsec); 20932 20933 installFlags = INSTALL_INTERNAL; 20934 moveCompleteApp = true; 20935 measurePath = Environment.getDataAppDirectory(volumeUuid); 20936 } 20937 20938 final PackageStats stats = new PackageStats(null, -1); 20939 synchronized (mInstaller) { 20940 for (int userId : installedUserIds) { 20941 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20942 freezer.close(); 20943 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20944 "Failed to measure package size"); 20945 } 20946 } 20947 } 20948 20949 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20950 + stats.dataSize); 20951 20952 final long startFreeBytes = measurePath.getFreeSpace(); 20953 final long sizeBytes; 20954 if (moveCompleteApp) { 20955 sizeBytes = stats.codeSize + stats.dataSize; 20956 } else { 20957 sizeBytes = stats.codeSize; 20958 } 20959 20960 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20961 freezer.close(); 20962 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20963 "Not enough free space to move"); 20964 } 20965 20966 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20967 20968 final CountDownLatch installedLatch = new CountDownLatch(1); 20969 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20970 @Override 20971 public void onUserActionRequired(Intent intent) throws RemoteException { 20972 throw new IllegalStateException(); 20973 } 20974 20975 @Override 20976 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20977 Bundle extras) throws RemoteException { 20978 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20979 + PackageManager.installStatusToString(returnCode, msg)); 20980 20981 installedLatch.countDown(); 20982 freezer.close(); 20983 20984 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20985 switch (status) { 20986 case PackageInstaller.STATUS_SUCCESS: 20987 mMoveCallbacks.notifyStatusChanged(moveId, 20988 PackageManager.MOVE_SUCCEEDED); 20989 break; 20990 case PackageInstaller.STATUS_FAILURE_STORAGE: 20991 mMoveCallbacks.notifyStatusChanged(moveId, 20992 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20993 break; 20994 default: 20995 mMoveCallbacks.notifyStatusChanged(moveId, 20996 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20997 break; 20998 } 20999 } 21000 }; 21001 21002 final MoveInfo move; 21003 if (moveCompleteApp) { 21004 // Kick off a thread to report progress estimates 21005 new Thread() { 21006 @Override 21007 public void run() { 21008 while (true) { 21009 try { 21010 if (installedLatch.await(1, TimeUnit.SECONDS)) { 21011 break; 21012 } 21013 } catch (InterruptedException ignored) { 21014 } 21015 21016 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 21017 final int progress = 10 + (int) MathUtils.constrain( 21018 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 21019 mMoveCallbacks.notifyStatusChanged(moveId, progress); 21020 } 21021 } 21022 }.start(); 21023 21024 final String dataAppName = codeFile.getName(); 21025 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 21026 dataAppName, appId, seinfo, targetSdkVersion); 21027 } else { 21028 move = null; 21029 } 21030 21031 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 21032 21033 final Message msg = mHandler.obtainMessage(INIT_COPY); 21034 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 21035 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 21036 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 21037 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 21038 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 21039 msg.obj = params; 21040 21041 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 21042 System.identityHashCode(msg.obj)); 21043 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 21044 System.identityHashCode(msg.obj)); 21045 21046 mHandler.sendMessage(msg); 21047 } 21048 21049 @Override 21050 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 21051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21052 21053 final int realMoveId = mNextMoveId.getAndIncrement(); 21054 final Bundle extras = new Bundle(); 21055 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 21056 mMoveCallbacks.notifyCreated(realMoveId, extras); 21057 21058 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 21059 @Override 21060 public void onCreated(int moveId, Bundle extras) { 21061 // Ignored 21062 } 21063 21064 @Override 21065 public void onStatusChanged(int moveId, int status, long estMillis) { 21066 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 21067 } 21068 }; 21069 21070 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21071 storage.setPrimaryStorageUuid(volumeUuid, callback); 21072 return realMoveId; 21073 } 21074 21075 @Override 21076 public int getMoveStatus(int moveId) { 21077 mContext.enforceCallingOrSelfPermission( 21078 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21079 return mMoveCallbacks.mLastStatus.get(moveId); 21080 } 21081 21082 @Override 21083 public void registerMoveCallback(IPackageMoveObserver callback) { 21084 mContext.enforceCallingOrSelfPermission( 21085 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21086 mMoveCallbacks.register(callback); 21087 } 21088 21089 @Override 21090 public void unregisterMoveCallback(IPackageMoveObserver callback) { 21091 mContext.enforceCallingOrSelfPermission( 21092 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21093 mMoveCallbacks.unregister(callback); 21094 } 21095 21096 @Override 21097 public boolean setInstallLocation(int loc) { 21098 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 21099 null); 21100 if (getInstallLocation() == loc) { 21101 return true; 21102 } 21103 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 21104 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 21105 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 21106 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 21107 return true; 21108 } 21109 return false; 21110 } 21111 21112 @Override 21113 public int getInstallLocation() { 21114 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 21115 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 21116 PackageHelper.APP_INSTALL_AUTO); 21117 } 21118 21119 /** Called by UserManagerService */ 21120 void cleanUpUser(UserManagerService userManager, int userHandle) { 21121 synchronized (mPackages) { 21122 mDirtyUsers.remove(userHandle); 21123 mUserNeedsBadging.delete(userHandle); 21124 mSettings.removeUserLPw(userHandle); 21125 mPendingBroadcasts.remove(userHandle); 21126 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 21127 removeUnusedPackagesLPw(userManager, userHandle); 21128 } 21129 } 21130 21131 /** 21132 * We're removing userHandle and would like to remove any downloaded packages 21133 * that are no longer in use by any other user. 21134 * @param userHandle the user being removed 21135 */ 21136 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 21137 final boolean DEBUG_CLEAN_APKS = false; 21138 int [] users = userManager.getUserIds(); 21139 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 21140 while (psit.hasNext()) { 21141 PackageSetting ps = psit.next(); 21142 if (ps.pkg == null) { 21143 continue; 21144 } 21145 final String packageName = ps.pkg.packageName; 21146 // Skip over if system app 21147 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 21148 continue; 21149 } 21150 if (DEBUG_CLEAN_APKS) { 21151 Slog.i(TAG, "Checking package " + packageName); 21152 } 21153 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 21154 if (keep) { 21155 if (DEBUG_CLEAN_APKS) { 21156 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 21157 } 21158 } else { 21159 for (int i = 0; i < users.length; i++) { 21160 if (users[i] != userHandle && ps.getInstalled(users[i])) { 21161 keep = true; 21162 if (DEBUG_CLEAN_APKS) { 21163 Slog.i(TAG, " Keeping package " + packageName + " for user " 21164 + users[i]); 21165 } 21166 break; 21167 } 21168 } 21169 } 21170 if (!keep) { 21171 if (DEBUG_CLEAN_APKS) { 21172 Slog.i(TAG, " Removing package " + packageName); 21173 } 21174 mHandler.post(new Runnable() { 21175 public void run() { 21176 deletePackageX(packageName, userHandle, 0); 21177 } //end run 21178 }); 21179 } 21180 } 21181 } 21182 21183 /** Called by UserManagerService */ 21184 void createNewUser(int userId, String[] disallowedPackages) { 21185 synchronized (mInstallLock) { 21186 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 21187 } 21188 synchronized (mPackages) { 21189 scheduleWritePackageRestrictionsLocked(userId); 21190 scheduleWritePackageListLocked(userId); 21191 applyFactoryDefaultBrowserLPw(userId); 21192 primeDomainVerificationsLPw(userId); 21193 } 21194 } 21195 21196 void onNewUserCreated(final int userId) { 21197 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21198 // If permission review for legacy apps is required, we represent 21199 // dagerous permissions for such apps as always granted runtime 21200 // permissions to keep per user flag state whether review is needed. 21201 // Hence, if a new user is added we have to propagate dangerous 21202 // permission grants for these legacy apps. 21203 if (mPermissionReviewRequired) { 21204 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 21205 | UPDATE_PERMISSIONS_REPLACE_ALL); 21206 } 21207 } 21208 21209 @Override 21210 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 21211 mContext.enforceCallingOrSelfPermission( 21212 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 21213 "Only package verification agents can read the verifier device identity"); 21214 21215 synchronized (mPackages) { 21216 return mSettings.getVerifierDeviceIdentityLPw(); 21217 } 21218 } 21219 21220 @Override 21221 public void setPermissionEnforced(String permission, boolean enforced) { 21222 // TODO: Now that we no longer change GID for storage, this should to away. 21223 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 21224 "setPermissionEnforced"); 21225 if (READ_EXTERNAL_STORAGE.equals(permission)) { 21226 synchronized (mPackages) { 21227 if (mSettings.mReadExternalStorageEnforced == null 21228 || mSettings.mReadExternalStorageEnforced != enforced) { 21229 mSettings.mReadExternalStorageEnforced = enforced; 21230 mSettings.writeLPr(); 21231 } 21232 } 21233 // kill any non-foreground processes so we restart them and 21234 // grant/revoke the GID. 21235 final IActivityManager am = ActivityManager.getService(); 21236 if (am != null) { 21237 final long token = Binder.clearCallingIdentity(); 21238 try { 21239 am.killProcessesBelowForeground("setPermissionEnforcement"); 21240 } catch (RemoteException e) { 21241 } finally { 21242 Binder.restoreCallingIdentity(token); 21243 } 21244 } 21245 } else { 21246 throw new IllegalArgumentException("No selective enforcement for " + permission); 21247 } 21248 } 21249 21250 @Override 21251 @Deprecated 21252 public boolean isPermissionEnforced(String permission) { 21253 return true; 21254 } 21255 21256 @Override 21257 public boolean isStorageLow() { 21258 final long token = Binder.clearCallingIdentity(); 21259 try { 21260 final DeviceStorageMonitorInternal 21261 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21262 if (dsm != null) { 21263 return dsm.isMemoryLow(); 21264 } else { 21265 return false; 21266 } 21267 } finally { 21268 Binder.restoreCallingIdentity(token); 21269 } 21270 } 21271 21272 @Override 21273 public IPackageInstaller getPackageInstaller() { 21274 return mInstallerService; 21275 } 21276 21277 private boolean userNeedsBadging(int userId) { 21278 int index = mUserNeedsBadging.indexOfKey(userId); 21279 if (index < 0) { 21280 final UserInfo userInfo; 21281 final long token = Binder.clearCallingIdentity(); 21282 try { 21283 userInfo = sUserManager.getUserInfo(userId); 21284 } finally { 21285 Binder.restoreCallingIdentity(token); 21286 } 21287 final boolean b; 21288 if (userInfo != null && userInfo.isManagedProfile()) { 21289 b = true; 21290 } else { 21291 b = false; 21292 } 21293 mUserNeedsBadging.put(userId, b); 21294 return b; 21295 } 21296 return mUserNeedsBadging.valueAt(index); 21297 } 21298 21299 @Override 21300 public KeySet getKeySetByAlias(String packageName, String alias) { 21301 if (packageName == null || alias == null) { 21302 return null; 21303 } 21304 synchronized(mPackages) { 21305 final PackageParser.Package pkg = mPackages.get(packageName); 21306 if (pkg == null) { 21307 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21308 throw new IllegalArgumentException("Unknown package: " + packageName); 21309 } 21310 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21311 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21312 } 21313 } 21314 21315 @Override 21316 public KeySet getSigningKeySet(String packageName) { 21317 if (packageName == null) { 21318 return null; 21319 } 21320 synchronized(mPackages) { 21321 final PackageParser.Package pkg = mPackages.get(packageName); 21322 if (pkg == null) { 21323 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21324 throw new IllegalArgumentException("Unknown package: " + packageName); 21325 } 21326 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21327 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21328 throw new SecurityException("May not access signing KeySet of other apps."); 21329 } 21330 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21331 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21332 } 21333 } 21334 21335 @Override 21336 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21337 if (packageName == null || ks == null) { 21338 return false; 21339 } 21340 synchronized(mPackages) { 21341 final PackageParser.Package pkg = mPackages.get(packageName); 21342 if (pkg == null) { 21343 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21344 throw new IllegalArgumentException("Unknown package: " + packageName); 21345 } 21346 IBinder ksh = ks.getToken(); 21347 if (ksh instanceof KeySetHandle) { 21348 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21349 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21350 } 21351 return false; 21352 } 21353 } 21354 21355 @Override 21356 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21357 if (packageName == null || ks == null) { 21358 return false; 21359 } 21360 synchronized(mPackages) { 21361 final PackageParser.Package pkg = mPackages.get(packageName); 21362 if (pkg == null) { 21363 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21364 throw new IllegalArgumentException("Unknown package: " + packageName); 21365 } 21366 IBinder ksh = ks.getToken(); 21367 if (ksh instanceof KeySetHandle) { 21368 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21369 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21370 } 21371 return false; 21372 } 21373 } 21374 21375 private void deletePackageIfUnusedLPr(final String packageName) { 21376 PackageSetting ps = mSettings.mPackages.get(packageName); 21377 if (ps == null) { 21378 return; 21379 } 21380 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21381 // TODO Implement atomic delete if package is unused 21382 // It is currently possible that the package will be deleted even if it is installed 21383 // after this method returns. 21384 mHandler.post(new Runnable() { 21385 public void run() { 21386 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21387 } 21388 }); 21389 } 21390 } 21391 21392 /** 21393 * Check and throw if the given before/after packages would be considered a 21394 * downgrade. 21395 */ 21396 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21397 throws PackageManagerException { 21398 if (after.versionCode < before.mVersionCode) { 21399 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21400 "Update version code " + after.versionCode + " is older than current " 21401 + before.mVersionCode); 21402 } else if (after.versionCode == before.mVersionCode) { 21403 if (after.baseRevisionCode < before.baseRevisionCode) { 21404 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21405 "Update base revision code " + after.baseRevisionCode 21406 + " is older than current " + before.baseRevisionCode); 21407 } 21408 21409 if (!ArrayUtils.isEmpty(after.splitNames)) { 21410 for (int i = 0; i < after.splitNames.length; i++) { 21411 final String splitName = after.splitNames[i]; 21412 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21413 if (j != -1) { 21414 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21415 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21416 "Update split " + splitName + " revision code " 21417 + after.splitRevisionCodes[i] + " is older than current " 21418 + before.splitRevisionCodes[j]); 21419 } 21420 } 21421 } 21422 } 21423 } 21424 } 21425 21426 private static class MoveCallbacks extends Handler { 21427 private static final int MSG_CREATED = 1; 21428 private static final int MSG_STATUS_CHANGED = 2; 21429 21430 private final RemoteCallbackList<IPackageMoveObserver> 21431 mCallbacks = new RemoteCallbackList<>(); 21432 21433 private final SparseIntArray mLastStatus = new SparseIntArray(); 21434 21435 public MoveCallbacks(Looper looper) { 21436 super(looper); 21437 } 21438 21439 public void register(IPackageMoveObserver callback) { 21440 mCallbacks.register(callback); 21441 } 21442 21443 public void unregister(IPackageMoveObserver callback) { 21444 mCallbacks.unregister(callback); 21445 } 21446 21447 @Override 21448 public void handleMessage(Message msg) { 21449 final SomeArgs args = (SomeArgs) msg.obj; 21450 final int n = mCallbacks.beginBroadcast(); 21451 for (int i = 0; i < n; i++) { 21452 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21453 try { 21454 invokeCallback(callback, msg.what, args); 21455 } catch (RemoteException ignored) { 21456 } 21457 } 21458 mCallbacks.finishBroadcast(); 21459 args.recycle(); 21460 } 21461 21462 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21463 throws RemoteException { 21464 switch (what) { 21465 case MSG_CREATED: { 21466 callback.onCreated(args.argi1, (Bundle) args.arg2); 21467 break; 21468 } 21469 case MSG_STATUS_CHANGED: { 21470 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21471 break; 21472 } 21473 } 21474 } 21475 21476 private void notifyCreated(int moveId, Bundle extras) { 21477 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21478 21479 final SomeArgs args = SomeArgs.obtain(); 21480 args.argi1 = moveId; 21481 args.arg2 = extras; 21482 obtainMessage(MSG_CREATED, args).sendToTarget(); 21483 } 21484 21485 private void notifyStatusChanged(int moveId, int status) { 21486 notifyStatusChanged(moveId, status, -1); 21487 } 21488 21489 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21490 Slog.v(TAG, "Move " + moveId + " status " + status); 21491 21492 final SomeArgs args = SomeArgs.obtain(); 21493 args.argi1 = moveId; 21494 args.argi2 = status; 21495 args.arg3 = estMillis; 21496 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21497 21498 synchronized (mLastStatus) { 21499 mLastStatus.put(moveId, status); 21500 } 21501 } 21502 } 21503 21504 private final static class OnPermissionChangeListeners extends Handler { 21505 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21506 21507 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21508 new RemoteCallbackList<>(); 21509 21510 public OnPermissionChangeListeners(Looper looper) { 21511 super(looper); 21512 } 21513 21514 @Override 21515 public void handleMessage(Message msg) { 21516 switch (msg.what) { 21517 case MSG_ON_PERMISSIONS_CHANGED: { 21518 final int uid = msg.arg1; 21519 handleOnPermissionsChanged(uid); 21520 } break; 21521 } 21522 } 21523 21524 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21525 mPermissionListeners.register(listener); 21526 21527 } 21528 21529 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21530 mPermissionListeners.unregister(listener); 21531 } 21532 21533 public void onPermissionsChanged(int uid) { 21534 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21535 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21536 } 21537 } 21538 21539 private void handleOnPermissionsChanged(int uid) { 21540 final int count = mPermissionListeners.beginBroadcast(); 21541 try { 21542 for (int i = 0; i < count; i++) { 21543 IOnPermissionsChangeListener callback = mPermissionListeners 21544 .getBroadcastItem(i); 21545 try { 21546 callback.onPermissionsChanged(uid); 21547 } catch (RemoteException e) { 21548 Log.e(TAG, "Permission listener is dead", e); 21549 } 21550 } 21551 } finally { 21552 mPermissionListeners.finishBroadcast(); 21553 } 21554 } 21555 } 21556 21557 private class PackageManagerInternalImpl extends PackageManagerInternal { 21558 @Override 21559 public void setLocationPackagesProvider(PackagesProvider provider) { 21560 synchronized (mPackages) { 21561 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21562 } 21563 } 21564 21565 @Override 21566 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21567 synchronized (mPackages) { 21568 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21569 } 21570 } 21571 21572 @Override 21573 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21574 synchronized (mPackages) { 21575 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21576 } 21577 } 21578 21579 @Override 21580 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21581 synchronized (mPackages) { 21582 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21583 } 21584 } 21585 21586 @Override 21587 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21588 synchronized (mPackages) { 21589 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21590 } 21591 } 21592 21593 @Override 21594 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21595 synchronized (mPackages) { 21596 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21597 } 21598 } 21599 21600 @Override 21601 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21602 synchronized (mPackages) { 21603 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21604 packageName, userId); 21605 } 21606 } 21607 21608 @Override 21609 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21610 synchronized (mPackages) { 21611 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21612 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21613 packageName, userId); 21614 } 21615 } 21616 21617 @Override 21618 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21619 synchronized (mPackages) { 21620 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21621 packageName, userId); 21622 } 21623 } 21624 21625 @Override 21626 public void setKeepUninstalledPackages(final List<String> packageList) { 21627 Preconditions.checkNotNull(packageList); 21628 List<String> removedFromList = null; 21629 synchronized (mPackages) { 21630 if (mKeepUninstalledPackages != null) { 21631 final int packagesCount = mKeepUninstalledPackages.size(); 21632 for (int i = 0; i < packagesCount; i++) { 21633 String oldPackage = mKeepUninstalledPackages.get(i); 21634 if (packageList != null && packageList.contains(oldPackage)) { 21635 continue; 21636 } 21637 if (removedFromList == null) { 21638 removedFromList = new ArrayList<>(); 21639 } 21640 removedFromList.add(oldPackage); 21641 } 21642 } 21643 mKeepUninstalledPackages = new ArrayList<>(packageList); 21644 if (removedFromList != null) { 21645 final int removedCount = removedFromList.size(); 21646 for (int i = 0; i < removedCount; i++) { 21647 deletePackageIfUnusedLPr(removedFromList.get(i)); 21648 } 21649 } 21650 } 21651 } 21652 21653 @Override 21654 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21655 synchronized (mPackages) { 21656 // If we do not support permission review, done. 21657 if (!mPermissionReviewRequired) { 21658 return false; 21659 } 21660 21661 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21662 if (packageSetting == null) { 21663 return false; 21664 } 21665 21666 // Permission review applies only to apps not supporting the new permission model. 21667 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21668 return false; 21669 } 21670 21671 // Legacy apps have the permission and get user consent on launch. 21672 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21673 return permissionsState.isPermissionReviewRequired(userId); 21674 } 21675 } 21676 21677 @Override 21678 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21679 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21680 } 21681 21682 @Override 21683 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21684 int userId) { 21685 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21686 } 21687 21688 @Override 21689 public void setDeviceAndProfileOwnerPackages( 21690 int deviceOwnerUserId, String deviceOwnerPackage, 21691 SparseArray<String> profileOwnerPackages) { 21692 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21693 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21694 } 21695 21696 @Override 21697 public boolean isPackageDataProtected(int userId, String packageName) { 21698 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21699 } 21700 21701 @Override 21702 public boolean isPackageEphemeral(int userId, String packageName) { 21703 synchronized (mPackages) { 21704 PackageParser.Package p = mPackages.get(packageName); 21705 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21706 } 21707 } 21708 21709 @Override 21710 public boolean wasPackageEverLaunched(String packageName, int userId) { 21711 synchronized (mPackages) { 21712 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21713 } 21714 } 21715 21716 @Override 21717 public void grantRuntimePermission(String packageName, String name, int userId, 21718 boolean overridePolicy) { 21719 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21720 overridePolicy); 21721 } 21722 21723 @Override 21724 public void revokeRuntimePermission(String packageName, String name, int userId, 21725 boolean overridePolicy) { 21726 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21727 overridePolicy); 21728 } 21729 21730 @Override 21731 public String getNameForUid(int uid) { 21732 return PackageManagerService.this.getNameForUid(uid); 21733 } 21734 21735 @Override 21736 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21737 Intent origIntent, String resolvedType, Intent launchIntent, 21738 String callingPackage, int userId) { 21739 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21740 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21741 } 21742 21743 public String getSetupWizardPackageName() { 21744 return mSetupWizardPackage; 21745 } 21746 } 21747 21748 @Override 21749 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21750 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21751 synchronized (mPackages) { 21752 final long identity = Binder.clearCallingIdentity(); 21753 try { 21754 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21755 packageNames, userId); 21756 } finally { 21757 Binder.restoreCallingIdentity(identity); 21758 } 21759 } 21760 } 21761 21762 private static void enforceSystemOrPhoneCaller(String tag) { 21763 int callingUid = Binder.getCallingUid(); 21764 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21765 throw new SecurityException( 21766 "Cannot call " + tag + " from UID " + callingUid); 21767 } 21768 } 21769 21770 boolean isHistoricalPackageUsageAvailable() { 21771 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21772 } 21773 21774 /** 21775 * Return a <b>copy</b> of the collection of packages known to the package manager. 21776 * @return A copy of the values of mPackages. 21777 */ 21778 Collection<PackageParser.Package> getPackages() { 21779 synchronized (mPackages) { 21780 return new ArrayList<>(mPackages.values()); 21781 } 21782 } 21783 21784 /** 21785 * Logs process start information (including base APK hash) to the security log. 21786 * @hide 21787 */ 21788 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21789 String apkFile, int pid) { 21790 if (!SecurityLog.isLoggingEnabled()) { 21791 return; 21792 } 21793 Bundle data = new Bundle(); 21794 data.putLong("startTimestamp", System.currentTimeMillis()); 21795 data.putString("processName", processName); 21796 data.putInt("uid", uid); 21797 data.putString("seinfo", seinfo); 21798 data.putString("apkFile", apkFile); 21799 data.putInt("pid", pid); 21800 Message msg = mProcessLoggingHandler.obtainMessage( 21801 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21802 msg.setData(data); 21803 mProcessLoggingHandler.sendMessage(msg); 21804 } 21805 21806 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21807 return mCompilerStats.getPackageStats(pkgName); 21808 } 21809 21810 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21811 return getOrCreateCompilerPackageStats(pkg.packageName); 21812 } 21813 21814 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21815 return mCompilerStats.getOrCreatePackageStats(pkgName); 21816 } 21817 21818 public void deleteCompilerPackageStats(String pkgName) { 21819 mCompilerStats.deletePackageStats(pkgName); 21820 } 21821} 21822