PackageManagerService.java revision 42a386b7717300bf6d75cbd3b4f7ad00f294be0d
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; 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 87import static com.android.internal.util.ArrayUtils.appendInt; 88import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 100 101import android.Manifest; 102import android.annotation.NonNull; 103import android.annotation.Nullable; 104import android.app.ActivityManager; 105import android.app.AppOpsManager; 106import android.app.IActivityManager; 107import android.app.ResourcesManager; 108import android.app.admin.IDevicePolicyManager; 109import android.app.admin.SecurityLog; 110import android.app.backup.IBackupManager; 111import android.content.BroadcastReceiver; 112import android.content.ComponentName; 113import android.content.ContentResolver; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralRequest; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResponse; 129import android.content.pm.FallbackCategoryProvider; 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. Also 1716 // for legacy apps in permission review mode we clear the permission 1717 // review flag which is used to emulate runtime permissions for 1718 // legacy apps. 1719 if (grantPermissions) { 1720 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1721 } 1722 1723 final boolean update = res.removedInfo != null 1724 && res.removedInfo.removedPackage != null; 1725 1726 // If this is the first time we have child packages for a disabled privileged 1727 // app that had no children, we grant requested runtime permissions to the new 1728 // children if the parent on the system image had them already granted. 1729 if (res.pkg.parentPackage != null) { 1730 synchronized (mPackages) { 1731 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1732 } 1733 } 1734 1735 synchronized (mPackages) { 1736 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1737 } 1738 1739 final String packageName = res.pkg.applicationInfo.packageName; 1740 1741 // Determine the set of users who are adding this package for 1742 // the first time vs. those who are seeing an update. 1743 int[] firstUsers = EMPTY_INT_ARRAY; 1744 int[] updateUsers = EMPTY_INT_ARRAY; 1745 if (res.origUsers == null || res.origUsers.length == 0) { 1746 firstUsers = res.newUsers; 1747 } else { 1748 for (int newUser : res.newUsers) { 1749 boolean isNew = true; 1750 for (int origUser : res.origUsers) { 1751 if (origUser == newUser) { 1752 isNew = false; 1753 break; 1754 } 1755 } 1756 if (isNew) { 1757 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1758 } else { 1759 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1760 } 1761 } 1762 } 1763 1764 // Send installed broadcasts if the install/update is not ephemeral 1765 if (!isEphemeral(res.pkg)) { 1766 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1767 1768 // Send added for users that see the package for the first time 1769 // sendPackageAddedForNewUsers also deals with system apps 1770 int appId = UserHandle.getAppId(res.uid); 1771 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1772 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1773 1774 // Send added for users that don't see the package for the first time 1775 Bundle extras = new Bundle(1); 1776 extras.putInt(Intent.EXTRA_UID, res.uid); 1777 if (update) { 1778 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1779 } 1780 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1781 extras, 0 /*flags*/, null /*targetPackage*/, 1782 null /*finishedReceiver*/, updateUsers); 1783 1784 // Send replaced for users that don't see the package for the first time 1785 if (update) { 1786 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1787 packageName, extras, 0 /*flags*/, 1788 null /*targetPackage*/, null /*finishedReceiver*/, 1789 updateUsers); 1790 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1791 null /*package*/, null /*extras*/, 0 /*flags*/, 1792 packageName /*targetPackage*/, 1793 null /*finishedReceiver*/, updateUsers); 1794 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1795 // First-install and we did a restore, so we're responsible for the 1796 // first-launch broadcast. 1797 if (DEBUG_BACKUP) { 1798 Slog.i(TAG, "Post-restore of " + packageName 1799 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1800 } 1801 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1802 } 1803 1804 // Send broadcast package appeared if forward locked/external for all users 1805 // treat asec-hosted packages like removable media on upgrade 1806 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1807 if (DEBUG_INSTALL) { 1808 Slog.i(TAG, "upgrading pkg " + res.pkg 1809 + " is ASEC-hosted -> AVAILABLE"); 1810 } 1811 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1812 ArrayList<String> pkgList = new ArrayList<>(1); 1813 pkgList.add(packageName); 1814 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1815 } 1816 } 1817 1818 // Work that needs to happen on first install within each user 1819 if (firstUsers != null && firstUsers.length > 0) { 1820 synchronized (mPackages) { 1821 for (int userId : firstUsers) { 1822 // If this app is a browser and it's newly-installed for some 1823 // users, clear any default-browser state in those users. The 1824 // app's nature doesn't depend on the user, so we can just check 1825 // its browser nature in any user and generalize. 1826 if (packageIsBrowser(packageName, userId)) { 1827 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1828 } 1829 1830 // We may also need to apply pending (restored) runtime 1831 // permission grants within these users. 1832 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1833 } 1834 } 1835 } 1836 1837 // Log current value of "unknown sources" setting 1838 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1839 getUnknownSourcesSettings()); 1840 1841 // Force a gc to clear up things 1842 Runtime.getRuntime().gc(); 1843 1844 // Remove the replaced package's older resources safely now 1845 // We delete after a gc for applications on sdcard. 1846 if (res.removedInfo != null && res.removedInfo.args != null) { 1847 synchronized (mInstallLock) { 1848 res.removedInfo.args.doPostDeleteLI(true); 1849 } 1850 } 1851 } 1852 1853 // If someone is watching installs - notify them 1854 if (installObserver != null) { 1855 try { 1856 Bundle extras = extrasForInstallResult(res); 1857 installObserver.onPackageInstalled(res.name, res.returnCode, 1858 res.returnMsg, extras); 1859 } catch (RemoteException e) { 1860 Slog.i(TAG, "Observer no longer exists."); 1861 } 1862 } 1863 } 1864 1865 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1866 PackageParser.Package pkg) { 1867 if (pkg.parentPackage == null) { 1868 return; 1869 } 1870 if (pkg.requestedPermissions == null) { 1871 return; 1872 } 1873 final PackageSetting disabledSysParentPs = mSettings 1874 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1875 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1876 || !disabledSysParentPs.isPrivileged() 1877 || (disabledSysParentPs.childPackageNames != null 1878 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1879 return; 1880 } 1881 final int[] allUserIds = sUserManager.getUserIds(); 1882 final int permCount = pkg.requestedPermissions.size(); 1883 for (int i = 0; i < permCount; i++) { 1884 String permission = pkg.requestedPermissions.get(i); 1885 BasePermission bp = mSettings.mPermissions.get(permission); 1886 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1887 continue; 1888 } 1889 for (int userId : allUserIds) { 1890 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1891 permission, userId)) { 1892 grantRuntimePermission(pkg.packageName, permission, userId); 1893 } 1894 } 1895 } 1896 } 1897 1898 private StorageEventListener mStorageListener = new StorageEventListener() { 1899 @Override 1900 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1901 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1902 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1903 final String volumeUuid = vol.getFsUuid(); 1904 1905 // Clean up any users or apps that were removed or recreated 1906 // while this volume was missing 1907 reconcileUsers(volumeUuid); 1908 reconcileApps(volumeUuid); 1909 1910 // Clean up any install sessions that expired or were 1911 // cancelled while this volume was missing 1912 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1913 1914 loadPrivatePackages(vol); 1915 1916 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1917 unloadPrivatePackages(vol); 1918 } 1919 } 1920 1921 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1922 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1923 updateExternalMediaStatus(true, false); 1924 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1925 updateExternalMediaStatus(false, false); 1926 } 1927 } 1928 } 1929 1930 @Override 1931 public void onVolumeForgotten(String fsUuid) { 1932 if (TextUtils.isEmpty(fsUuid)) { 1933 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1934 return; 1935 } 1936 1937 // Remove any apps installed on the forgotten volume 1938 synchronized (mPackages) { 1939 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1940 for (PackageSetting ps : packages) { 1941 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1942 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1943 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1944 1945 // Try very hard to release any references to this package 1946 // so we don't risk the system server being killed due to 1947 // open FDs 1948 AttributeCache.instance().removePackage(ps.name); 1949 } 1950 1951 mSettings.onVolumeForgotten(fsUuid); 1952 mSettings.writeLPr(); 1953 } 1954 } 1955 }; 1956 1957 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1958 String[] grantedPermissions) { 1959 for (int userId : userIds) { 1960 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1961 } 1962 } 1963 1964 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1965 String[] grantedPermissions) { 1966 SettingBase sb = (SettingBase) pkg.mExtras; 1967 if (sb == null) { 1968 return; 1969 } 1970 1971 PermissionsState permissionsState = sb.getPermissionsState(); 1972 1973 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1974 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1975 1976 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 1977 >= Build.VERSION_CODES.M; 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 if (supportsRuntimePermissions) { 1989 // Installer cannot change immutable permissions. 1990 if ((flags & immutableFlags) == 0) { 1991 grantRuntimePermission(pkg.packageName, permission, userId); 1992 } 1993 } else if (mPermissionReviewRequired) { 1994 // In permission review mode we clear the review flag when we 1995 // are asked to install the app with all permissions granted. 1996 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 1997 updatePermissionFlags(permission, pkg.packageName, 1998 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 1999 } 2000 } 2001 } 2002 } 2003 } 2004 2005 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2006 Bundle extras = null; 2007 switch (res.returnCode) { 2008 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2009 extras = new Bundle(); 2010 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2011 res.origPermission); 2012 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2013 res.origPackage); 2014 break; 2015 } 2016 case PackageManager.INSTALL_SUCCEEDED: { 2017 extras = new Bundle(); 2018 extras.putBoolean(Intent.EXTRA_REPLACING, 2019 res.removedInfo != null && res.removedInfo.removedPackage != null); 2020 break; 2021 } 2022 } 2023 return extras; 2024 } 2025 2026 void scheduleWriteSettingsLocked() { 2027 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2028 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2029 } 2030 } 2031 2032 void scheduleWritePackageListLocked(int userId) { 2033 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2034 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2035 msg.arg1 = userId; 2036 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2037 } 2038 } 2039 2040 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2041 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2042 scheduleWritePackageRestrictionsLocked(userId); 2043 } 2044 2045 void scheduleWritePackageRestrictionsLocked(int userId) { 2046 final int[] userIds = (userId == UserHandle.USER_ALL) 2047 ? sUserManager.getUserIds() : new int[]{userId}; 2048 for (int nextUserId : userIds) { 2049 if (!sUserManager.exists(nextUserId)) return; 2050 mDirtyUsers.add(nextUserId); 2051 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2052 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2053 } 2054 } 2055 } 2056 2057 public static PackageManagerService main(Context context, Installer installer, 2058 boolean factoryTest, boolean onlyCore) { 2059 // Self-check for initial settings. 2060 PackageManagerServiceCompilerMapping.checkProperties(); 2061 2062 PackageManagerService m = new PackageManagerService(context, installer, 2063 factoryTest, onlyCore); 2064 m.enableSystemUserPackages(); 2065 ServiceManager.addService("package", m); 2066 return m; 2067 } 2068 2069 private void enableSystemUserPackages() { 2070 if (!UserManager.isSplitSystemUser()) { 2071 return; 2072 } 2073 // For system user, enable apps based on the following conditions: 2074 // - app is whitelisted or belong to one of these groups: 2075 // -- system app which has no launcher icons 2076 // -- system app which has INTERACT_ACROSS_USERS permission 2077 // -- system IME app 2078 // - app is not in the blacklist 2079 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2080 Set<String> enableApps = new ArraySet<>(); 2081 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2082 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2083 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2084 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2085 enableApps.addAll(wlApps); 2086 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2087 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2088 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2089 enableApps.removeAll(blApps); 2090 Log.i(TAG, "Applications installed for system user: " + enableApps); 2091 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2092 UserHandle.SYSTEM); 2093 final int allAppsSize = allAps.size(); 2094 synchronized (mPackages) { 2095 for (int i = 0; i < allAppsSize; i++) { 2096 String pName = allAps.get(i); 2097 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2098 // Should not happen, but we shouldn't be failing if it does 2099 if (pkgSetting == null) { 2100 continue; 2101 } 2102 boolean install = enableApps.contains(pName); 2103 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2104 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2105 + " for system user"); 2106 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2107 } 2108 } 2109 } 2110 } 2111 2112 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2113 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2114 Context.DISPLAY_SERVICE); 2115 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2116 } 2117 2118 /** 2119 * Requests that files preopted on a secondary system partition be copied to the data partition 2120 * if possible. Note that the actual copying of the files is accomplished by init for security 2121 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2122 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2123 */ 2124 private static void requestCopyPreoptedFiles() { 2125 final int WAIT_TIME_MS = 100; 2126 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2127 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2128 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2129 // We will wait for up to 100 seconds. 2130 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2131 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2132 try { 2133 Thread.sleep(WAIT_TIME_MS); 2134 } catch (InterruptedException e) { 2135 // Do nothing 2136 } 2137 if (SystemClock.uptimeMillis() > timeEnd) { 2138 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2139 Slog.wtf(TAG, "cppreopt did not finish!"); 2140 break; 2141 } 2142 } 2143 } 2144 } 2145 2146 public PackageManagerService(Context context, Installer installer, 2147 boolean factoryTest, boolean onlyCore) { 2148 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2149 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2150 SystemClock.uptimeMillis()); 2151 2152 if (mSdkVersion <= 0) { 2153 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2154 } 2155 2156 mContext = context; 2157 2158 mPermissionReviewRequired = context.getResources().getBoolean( 2159 R.bool.config_permissionReviewRequired); 2160 2161 mFactoryTest = factoryTest; 2162 mOnlyCore = onlyCore; 2163 mMetrics = new DisplayMetrics(); 2164 mSettings = new Settings(mPackages); 2165 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2166 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2167 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2168 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2169 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2170 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2171 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2172 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2173 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2174 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2175 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2176 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2177 2178 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2179 if (separateProcesses != null && separateProcesses.length() > 0) { 2180 if ("*".equals(separateProcesses)) { 2181 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2182 mSeparateProcesses = null; 2183 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2184 } else { 2185 mDefParseFlags = 0; 2186 mSeparateProcesses = separateProcesses.split(","); 2187 Slog.w(TAG, "Running with debug.separate_processes: " 2188 + separateProcesses); 2189 } 2190 } else { 2191 mDefParseFlags = 0; 2192 mSeparateProcesses = null; 2193 } 2194 2195 mInstaller = installer; 2196 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2197 "*dexopt*"); 2198 mDexManager = new DexManager(); 2199 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2200 2201 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2202 FgThread.get().getLooper()); 2203 2204 getDefaultDisplayMetrics(context, mMetrics); 2205 2206 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2207 SystemConfig systemConfig = SystemConfig.getInstance(); 2208 mGlobalGids = systemConfig.getGlobalGids(); 2209 mSystemPermissions = systemConfig.getSystemPermissions(); 2210 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2211 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2212 2213 mProtectedPackages = new ProtectedPackages(mContext); 2214 2215 synchronized (mInstallLock) { 2216 // writer 2217 synchronized (mPackages) { 2218 mHandlerThread = new ServiceThread(TAG, 2219 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2220 mHandlerThread.start(); 2221 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2222 mProcessLoggingHandler = new ProcessLoggingHandler(); 2223 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2224 2225 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2226 2227 File dataDir = Environment.getDataDirectory(); 2228 mAppInstallDir = new File(dataDir, "app"); 2229 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2230 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2231 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2232 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2233 2234 sUserManager = new UserManagerService(context, this, mPackages); 2235 2236 // Propagate permission configuration in to package manager. 2237 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2238 = systemConfig.getPermissions(); 2239 for (int i=0; i<permConfig.size(); i++) { 2240 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2241 BasePermission bp = mSettings.mPermissions.get(perm.name); 2242 if (bp == null) { 2243 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2244 mSettings.mPermissions.put(perm.name, bp); 2245 } 2246 if (perm.gids != null) { 2247 bp.setGids(perm.gids, perm.perUser); 2248 } 2249 } 2250 2251 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2252 for (int i=0; i<libConfig.size(); i++) { 2253 mSharedLibraries.put(libConfig.keyAt(i), 2254 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2255 } 2256 2257 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2258 2259 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2260 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2261 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2262 2263 // Clean up orphaned packages for which the code path doesn't exist 2264 // and they are an update to a system app - caused by bug/32321269 2265 final int packageSettingCount = mSettings.mPackages.size(); 2266 for (int i = packageSettingCount - 1; i >= 0; i--) { 2267 PackageSetting ps = mSettings.mPackages.valueAt(i); 2268 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2269 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2270 mSettings.mPackages.removeAt(i); 2271 mSettings.enableSystemPackageLPw(ps.name); 2272 } 2273 } 2274 2275 if (mFirstBoot) { 2276 requestCopyPreoptedFiles(); 2277 } 2278 2279 String customResolverActivity = Resources.getSystem().getString( 2280 R.string.config_customResolverActivity); 2281 if (TextUtils.isEmpty(customResolverActivity)) { 2282 customResolverActivity = null; 2283 } else { 2284 mCustomResolverComponentName = ComponentName.unflattenFromString( 2285 customResolverActivity); 2286 } 2287 2288 long startTime = SystemClock.uptimeMillis(); 2289 2290 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2291 startTime); 2292 2293 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2294 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2295 2296 if (bootClassPath == null) { 2297 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2298 } 2299 2300 if (systemServerClassPath == null) { 2301 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2302 } 2303 2304 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2305 final String[] dexCodeInstructionSets = 2306 getDexCodeInstructionSets( 2307 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2308 2309 /** 2310 * Ensure all external libraries have had dexopt run on them. 2311 */ 2312 if (mSharedLibraries.size() > 0) { 2313 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2314 // NOTE: For now, we're compiling these system "shared libraries" 2315 // (and framework jars) into all available architectures. It's possible 2316 // to compile them only when we come across an app that uses them (there's 2317 // already logic for that in scanPackageLI) but that adds some complexity. 2318 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2319 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2320 final String lib = libEntry.path; 2321 if (lib == null) { 2322 continue; 2323 } 2324 2325 try { 2326 // Shared libraries do not have profiles so we perform a full 2327 // AOT compilation (if needed). 2328 int dexoptNeeded = DexFile.getDexOptNeeded( 2329 lib, dexCodeInstructionSet, 2330 getCompilerFilterForReason(REASON_SHARED_APK), 2331 false /* newProfile */); 2332 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2333 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2334 dexCodeInstructionSet, dexoptNeeded, null, 2335 DEXOPT_PUBLIC, 2336 getCompilerFilterForReason(REASON_SHARED_APK), 2337 StorageManager.UUID_PRIVATE_INTERNAL, 2338 SKIP_SHARED_LIBRARY_CHECK); 2339 } 2340 } catch (FileNotFoundException e) { 2341 Slog.w(TAG, "Library not found: " + lib); 2342 } catch (IOException | InstallerException e) { 2343 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2344 + e.getMessage()); 2345 } 2346 } 2347 } 2348 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2349 } 2350 2351 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2352 2353 final VersionInfo ver = mSettings.getInternalVersion(); 2354 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2355 2356 // when upgrading from pre-M, promote system app permissions from install to runtime 2357 mPromoteSystemApps = 2358 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2359 2360 // When upgrading from pre-N, we need to handle package extraction like first boot, 2361 // as there is no profiling data available. 2362 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2363 2364 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2365 2366 // save off the names of pre-existing system packages prior to scanning; we don't 2367 // want to automatically grant runtime permissions for new system apps 2368 if (mPromoteSystemApps) { 2369 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2370 while (pkgSettingIter.hasNext()) { 2371 PackageSetting ps = pkgSettingIter.next(); 2372 if (isSystemApp(ps)) { 2373 mExistingSystemPackages.add(ps.name); 2374 } 2375 } 2376 } 2377 2378 mCacheDir = preparePackageParserCache(mIsUpgrade); 2379 2380 // Set flag to monitor and not change apk file paths when 2381 // scanning install directories. 2382 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2383 2384 if (mIsUpgrade || mFirstBoot) { 2385 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2386 } 2387 2388 // Collect vendor overlay packages. (Do this before scanning any apps.) 2389 // For security and version matching reason, only consider 2390 // overlay packages if they reside in the right directory. 2391 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2392 if (overlayThemeDir.isEmpty()) { 2393 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2394 } 2395 if (!overlayThemeDir.isEmpty()) { 2396 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2397 | PackageParser.PARSE_IS_SYSTEM 2398 | PackageParser.PARSE_IS_SYSTEM_DIR 2399 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2400 } 2401 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2402 | PackageParser.PARSE_IS_SYSTEM 2403 | PackageParser.PARSE_IS_SYSTEM_DIR 2404 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2405 2406 // Find base frameworks (resource packages without code). 2407 scanDirTracedLI(frameworkDir, mDefParseFlags 2408 | PackageParser.PARSE_IS_SYSTEM 2409 | PackageParser.PARSE_IS_SYSTEM_DIR 2410 | PackageParser.PARSE_IS_PRIVILEGED, 2411 scanFlags | SCAN_NO_DEX, 0); 2412 2413 // Collected privileged system packages. 2414 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2415 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2416 | PackageParser.PARSE_IS_SYSTEM 2417 | PackageParser.PARSE_IS_SYSTEM_DIR 2418 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2419 2420 // Collect ordinary system packages. 2421 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2422 scanDirTracedLI(systemAppDir, mDefParseFlags 2423 | PackageParser.PARSE_IS_SYSTEM 2424 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2425 2426 // Collect all vendor packages. 2427 File vendorAppDir = new File("/vendor/app"); 2428 try { 2429 vendorAppDir = vendorAppDir.getCanonicalFile(); 2430 } catch (IOException e) { 2431 // failed to look up canonical path, continue with original one 2432 } 2433 scanDirTracedLI(vendorAppDir, mDefParseFlags 2434 | PackageParser.PARSE_IS_SYSTEM 2435 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2436 2437 // Collect all OEM packages. 2438 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2439 scanDirTracedLI(oemAppDir, mDefParseFlags 2440 | PackageParser.PARSE_IS_SYSTEM 2441 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2442 2443 // Prune any system packages that no longer exist. 2444 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2445 if (!mOnlyCore) { 2446 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2447 while (psit.hasNext()) { 2448 PackageSetting ps = psit.next(); 2449 2450 /* 2451 * If this is not a system app, it can't be a 2452 * disable system app. 2453 */ 2454 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2455 continue; 2456 } 2457 2458 /* 2459 * If the package is scanned, it's not erased. 2460 */ 2461 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2462 if (scannedPkg != null) { 2463 /* 2464 * If the system app is both scanned and in the 2465 * disabled packages list, then it must have been 2466 * added via OTA. Remove it from the currently 2467 * scanned package so the previously user-installed 2468 * application can be scanned. 2469 */ 2470 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2471 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2472 + ps.name + "; removing system app. Last known codePath=" 2473 + ps.codePathString + ", installStatus=" + ps.installStatus 2474 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2475 + scannedPkg.mVersionCode); 2476 removePackageLI(scannedPkg, true); 2477 mExpectingBetter.put(ps.name, ps.codePath); 2478 } 2479 2480 continue; 2481 } 2482 2483 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2484 psit.remove(); 2485 logCriticalInfo(Log.WARN, "System package " + ps.name 2486 + " no longer exists; it's data will be wiped"); 2487 // Actual deletion of code and data will be handled by later 2488 // reconciliation step 2489 } else { 2490 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2491 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2492 possiblyDeletedUpdatedSystemApps.add(ps.name); 2493 } 2494 } 2495 } 2496 } 2497 2498 //look for any incomplete package installations 2499 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2500 for (int i = 0; i < deletePkgsList.size(); i++) { 2501 // Actual deletion of code and data will be handled by later 2502 // reconciliation step 2503 final String packageName = deletePkgsList.get(i).name; 2504 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2505 synchronized (mPackages) { 2506 mSettings.removePackageLPw(packageName); 2507 } 2508 } 2509 2510 //delete tmp files 2511 deleteTempPackageFiles(); 2512 2513 // Remove any shared userIDs that have no associated packages 2514 mSettings.pruneSharedUsersLPw(); 2515 2516 if (!mOnlyCore) { 2517 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2518 SystemClock.uptimeMillis()); 2519 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2520 2521 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2522 | PackageParser.PARSE_FORWARD_LOCK, 2523 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2524 2525 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2526 | PackageParser.PARSE_IS_EPHEMERAL, 2527 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2528 2529 /** 2530 * Remove disable package settings for any updated system 2531 * apps that were removed via an OTA. If they're not a 2532 * previously-updated app, remove them completely. 2533 * Otherwise, just revoke their system-level permissions. 2534 */ 2535 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2536 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2537 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2538 2539 String msg; 2540 if (deletedPkg == null) { 2541 msg = "Updated system package " + deletedAppName 2542 + " no longer exists; it's data will be wiped"; 2543 // Actual deletion of code and data will be handled by later 2544 // reconciliation step 2545 } else { 2546 msg = "Updated system app + " + deletedAppName 2547 + " no longer present; removing system privileges for " 2548 + deletedAppName; 2549 2550 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2551 2552 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2553 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2554 } 2555 logCriticalInfo(Log.WARN, msg); 2556 } 2557 2558 /** 2559 * Make sure all system apps that we expected to appear on 2560 * the userdata partition actually showed up. If they never 2561 * appeared, crawl back and revive the system version. 2562 */ 2563 for (int i = 0; i < mExpectingBetter.size(); i++) { 2564 final String packageName = mExpectingBetter.keyAt(i); 2565 if (!mPackages.containsKey(packageName)) { 2566 final File scanFile = mExpectingBetter.valueAt(i); 2567 2568 logCriticalInfo(Log.WARN, "Expected better " + packageName 2569 + " but never showed up; reverting to system"); 2570 2571 int reparseFlags = mDefParseFlags; 2572 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2573 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2574 | PackageParser.PARSE_IS_SYSTEM_DIR 2575 | PackageParser.PARSE_IS_PRIVILEGED; 2576 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2577 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2578 | PackageParser.PARSE_IS_SYSTEM_DIR; 2579 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2580 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR; 2582 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2583 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2584 | PackageParser.PARSE_IS_SYSTEM_DIR; 2585 } else { 2586 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2587 continue; 2588 } 2589 2590 mSettings.enableSystemPackageLPw(packageName); 2591 2592 try { 2593 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2594 } catch (PackageManagerException e) { 2595 Slog.e(TAG, "Failed to parse original system package: " 2596 + e.getMessage()); 2597 } 2598 } 2599 } 2600 } 2601 mExpectingBetter.clear(); 2602 2603 // Resolve the storage manager. 2604 mStorageManagerPackage = getStorageManagerPackageName(); 2605 2606 // Resolve protected action filters. Only the setup wizard is allowed to 2607 // have a high priority filter for these actions. 2608 mSetupWizardPackage = getSetupWizardPackageName(); 2609 if (mProtectedFilters.size() > 0) { 2610 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2611 Slog.i(TAG, "No setup wizard;" 2612 + " All protected intents capped to priority 0"); 2613 } 2614 for (ActivityIntentInfo filter : mProtectedFilters) { 2615 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2616 if (DEBUG_FILTERS) { 2617 Slog.i(TAG, "Found setup wizard;" 2618 + " allow priority " + filter.getPriority() + ";" 2619 + " package: " + filter.activity.info.packageName 2620 + " activity: " + filter.activity.className 2621 + " priority: " + filter.getPriority()); 2622 } 2623 // skip setup wizard; allow it to keep the high priority filter 2624 continue; 2625 } 2626 Slog.w(TAG, "Protected action; cap priority to 0;" 2627 + " package: " + filter.activity.info.packageName 2628 + " activity: " + filter.activity.className 2629 + " origPrio: " + filter.getPriority()); 2630 filter.setPriority(0); 2631 } 2632 } 2633 mDeferProtectedFilters = false; 2634 mProtectedFilters.clear(); 2635 2636 // Now that we know all of the shared libraries, update all clients to have 2637 // the correct library paths. 2638 updateAllSharedLibrariesLPw(); 2639 2640 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2641 // NOTE: We ignore potential failures here during a system scan (like 2642 // the rest of the commands above) because there's precious little we 2643 // can do about it. A settings error is reported, though. 2644 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2645 } 2646 2647 // Now that we know all the packages we are keeping, 2648 // read and update their last usage times. 2649 mPackageUsage.read(mPackages); 2650 mCompilerStats.read(); 2651 2652 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2653 SystemClock.uptimeMillis()); 2654 Slog.i(TAG, "Time to scan packages: " 2655 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2656 + " seconds"); 2657 2658 // If the platform SDK has changed since the last time we booted, 2659 // we need to re-grant app permission to catch any new ones that 2660 // appear. This is really a hack, and means that apps can in some 2661 // cases get permissions that the user didn't initially explicitly 2662 // allow... it would be nice to have some better way to handle 2663 // this situation. 2664 int updateFlags = UPDATE_PERMISSIONS_ALL; 2665 if (ver.sdkVersion != mSdkVersion) { 2666 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2667 + mSdkVersion + "; regranting permissions for internal storage"); 2668 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2669 } 2670 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2671 ver.sdkVersion = mSdkVersion; 2672 2673 // If this is the first boot or an update from pre-M, and it is a normal 2674 // boot, then we need to initialize the default preferred apps across 2675 // all defined users. 2676 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2677 for (UserInfo user : sUserManager.getUsers(true)) { 2678 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2679 applyFactoryDefaultBrowserLPw(user.id); 2680 primeDomainVerificationsLPw(user.id); 2681 } 2682 } 2683 2684 // Prepare storage for system user really early during boot, 2685 // since core system apps like SettingsProvider and SystemUI 2686 // can't wait for user to start 2687 final int storageFlags; 2688 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2689 storageFlags = StorageManager.FLAG_STORAGE_DE; 2690 } else { 2691 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2692 } 2693 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2694 storageFlags, true /* migrateAppData */); 2695 2696 // If this is first boot after an OTA, and a normal boot, then 2697 // we need to clear code cache directories. 2698 // Note that we do *not* clear the application profiles. These remain valid 2699 // across OTAs and are used to drive profile verification (post OTA) and 2700 // profile compilation (without waiting to collect a fresh set of profiles). 2701 if (mIsUpgrade && !onlyCore) { 2702 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2703 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2704 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2705 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2706 // No apps are running this early, so no need to freeze 2707 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2708 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2709 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2710 } 2711 } 2712 ver.fingerprint = Build.FINGERPRINT; 2713 } 2714 2715 checkDefaultBrowser(); 2716 2717 // clear only after permissions and other defaults have been updated 2718 mExistingSystemPackages.clear(); 2719 mPromoteSystemApps = false; 2720 2721 // All the changes are done during package scanning. 2722 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2723 2724 // can downgrade to reader 2725 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2726 mSettings.writeLPr(); 2727 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2728 2729 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2730 // early on (before the package manager declares itself as early) because other 2731 // components in the system server might ask for package contexts for these apps. 2732 // 2733 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2734 // (i.e, that the data partition is unavailable). 2735 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2736 long start = System.nanoTime(); 2737 List<PackageParser.Package> coreApps = new ArrayList<>(); 2738 for (PackageParser.Package pkg : mPackages.values()) { 2739 if (pkg.coreApp) { 2740 coreApps.add(pkg); 2741 } 2742 } 2743 2744 int[] stats = performDexOptUpgrade(coreApps, false, 2745 getCompilerFilterForReason(REASON_CORE_APP)); 2746 2747 final int elapsedTimeSeconds = 2748 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2749 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2750 2751 if (DEBUG_DEXOPT) { 2752 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2753 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2754 } 2755 2756 2757 // TODO: Should we log these stats to tron too ? 2758 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2759 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2760 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2761 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2762 } 2763 2764 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2765 SystemClock.uptimeMillis()); 2766 2767 if (!mOnlyCore) { 2768 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2769 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2770 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2771 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2772 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2773 mIntentFilterVerifierComponent); 2774 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2775 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2776 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2777 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2778 } else { 2779 mRequiredVerifierPackage = null; 2780 mRequiredInstallerPackage = null; 2781 mRequiredUninstallerPackage = null; 2782 mIntentFilterVerifierComponent = null; 2783 mIntentFilterVerifier = null; 2784 mServicesSystemSharedLibraryPackageName = null; 2785 mSharedSystemSharedLibraryPackageName = null; 2786 } 2787 2788 mInstallerService = new PackageInstallerService(context, this); 2789 2790 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2791 if (ephemeralResolverComponent != null) { 2792 if (DEBUG_EPHEMERAL) { 2793 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2794 } 2795 mEphemeralResolverConnection = 2796 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2797 } else { 2798 mEphemeralResolverConnection = null; 2799 } 2800 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2801 if (mEphemeralInstallerComponent != null) { 2802 if (DEBUG_EPHEMERAL) { 2803 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2804 } 2805 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2806 } 2807 2808 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2809 2810 // Read and update the usage of dex files. 2811 // Do this at the end of PM init so that all the packages have their 2812 // data directory reconciled. 2813 // At this point we know the code paths of the packages, so we can validate 2814 // the disk file and build the internal cache. 2815 // The usage file is expected to be small so loading and verifying it 2816 // should take a fairly small time compare to the other activities (e.g. package 2817 // scanning). 2818 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2819 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2820 for (int userId : currentUserIds) { 2821 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2822 } 2823 mDexManager.load(userPackages); 2824 } // synchronized (mPackages) 2825 } // synchronized (mInstallLock) 2826 2827 // Now after opening every single application zip, make sure they 2828 // are all flushed. Not really needed, but keeps things nice and 2829 // tidy. 2830 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2831 Runtime.getRuntime().gc(); 2832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2833 2834 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2835 FallbackCategoryProvider.loadFallbacks(); 2836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2837 2838 // The initial scanning above does many calls into installd while 2839 // holding the mPackages lock, but we're mostly interested in yelling 2840 // once we have a booted system. 2841 mInstaller.setWarnIfHeld(mPackages); 2842 2843 // Expose private service for system components to use. 2844 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2845 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2846 } 2847 2848 private static File preparePackageParserCache(boolean isUpgrade) { 2849 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2850 return null; 2851 } 2852 2853 // Disable package parsing on eng builds to allow for faster incremental development. 2854 if ("eng".equals(Build.TYPE)) { 2855 return null; 2856 } 2857 2858 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2859 Slog.i(TAG, "Disabling package parser cache due to system property."); 2860 return null; 2861 } 2862 2863 // The base directory for the package parser cache lives under /data/system/. 2864 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2865 "package_cache"); 2866 if (cacheBaseDir == null) { 2867 return null; 2868 } 2869 2870 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2871 // This also serves to "GC" unused entries when the package cache version changes (which 2872 // can only happen during upgrades). 2873 if (isUpgrade) { 2874 FileUtils.deleteContents(cacheBaseDir); 2875 } 2876 2877 2878 // Return the versioned package cache directory. This is something like 2879 // "/data/system/package_cache/1" 2880 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2881 2882 // The following is a workaround to aid development on non-numbered userdebug 2883 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2884 // the system partition is newer. 2885 // 2886 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2887 // that starts with "eng." to signify that this is an engineering build and not 2888 // destined for release. 2889 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2890 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2891 2892 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2893 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2894 // in general and should not be used for production changes. In this specific case, 2895 // we know that they will work. 2896 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2897 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2898 FileUtils.deleteContents(cacheBaseDir); 2899 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2900 } 2901 } 2902 2903 return cacheDir; 2904 } 2905 2906 @Override 2907 public boolean isFirstBoot() { 2908 return mFirstBoot; 2909 } 2910 2911 @Override 2912 public boolean isOnlyCoreApps() { 2913 return mOnlyCore; 2914 } 2915 2916 @Override 2917 public boolean isUpgrade() { 2918 return mIsUpgrade; 2919 } 2920 2921 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2922 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2923 2924 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2925 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2926 UserHandle.USER_SYSTEM); 2927 if (matches.size() == 1) { 2928 return matches.get(0).getComponentInfo().packageName; 2929 } else if (matches.size() == 0) { 2930 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2931 return null; 2932 } 2933 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2934 } 2935 2936 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2937 synchronized (mPackages) { 2938 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2939 if (libraryEntry == null) { 2940 throw new IllegalStateException("Missing required shared library:" + libraryName); 2941 } 2942 return libraryEntry.apk; 2943 } 2944 } 2945 2946 private @NonNull String getRequiredInstallerLPr() { 2947 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2948 intent.addCategory(Intent.CATEGORY_DEFAULT); 2949 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2950 2951 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2952 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2953 UserHandle.USER_SYSTEM); 2954 if (matches.size() == 1) { 2955 ResolveInfo resolveInfo = matches.get(0); 2956 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2957 throw new RuntimeException("The installer must be a privileged app"); 2958 } 2959 return matches.get(0).getComponentInfo().packageName; 2960 } else { 2961 throw new RuntimeException("There must be exactly one installer; found " + matches); 2962 } 2963 } 2964 2965 private @NonNull String getRequiredUninstallerLPr() { 2966 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2967 intent.addCategory(Intent.CATEGORY_DEFAULT); 2968 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2969 2970 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2971 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2972 UserHandle.USER_SYSTEM); 2973 if (resolveInfo == null || 2974 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2975 throw new RuntimeException("There must be exactly one uninstaller; found " 2976 + resolveInfo); 2977 } 2978 return resolveInfo.getComponentInfo().packageName; 2979 } 2980 2981 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2982 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2983 2984 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2985 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2986 UserHandle.USER_SYSTEM); 2987 ResolveInfo best = null; 2988 final int N = matches.size(); 2989 for (int i = 0; i < N; i++) { 2990 final ResolveInfo cur = matches.get(i); 2991 final String packageName = cur.getComponentInfo().packageName; 2992 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2993 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2994 continue; 2995 } 2996 2997 if (best == null || cur.priority > best.priority) { 2998 best = cur; 2999 } 3000 } 3001 3002 if (best != null) { 3003 return best.getComponentInfo().getComponentName(); 3004 } else { 3005 throw new RuntimeException("There must be at least one intent filter verifier"); 3006 } 3007 } 3008 3009 private @Nullable ComponentName getEphemeralResolverLPr() { 3010 final String[] packageArray = 3011 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3012 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3013 if (DEBUG_EPHEMERAL) { 3014 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3015 } 3016 return null; 3017 } 3018 3019 final int resolveFlags = 3020 MATCH_DIRECT_BOOT_AWARE 3021 | MATCH_DIRECT_BOOT_UNAWARE 3022 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3023 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3024 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3025 resolveFlags, UserHandle.USER_SYSTEM); 3026 3027 final int N = resolvers.size(); 3028 if (N == 0) { 3029 if (DEBUG_EPHEMERAL) { 3030 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3031 } 3032 return null; 3033 } 3034 3035 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3036 for (int i = 0; i < N; i++) { 3037 final ResolveInfo info = resolvers.get(i); 3038 3039 if (info.serviceInfo == null) { 3040 continue; 3041 } 3042 3043 final String packageName = info.serviceInfo.packageName; 3044 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3045 if (DEBUG_EPHEMERAL) { 3046 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3047 + " pkg: " + packageName + ", info:" + info); 3048 } 3049 continue; 3050 } 3051 3052 if (DEBUG_EPHEMERAL) { 3053 Slog.v(TAG, "Ephemeral resolver found;" 3054 + " pkg: " + packageName + ", info:" + info); 3055 } 3056 return new ComponentName(packageName, info.serviceInfo.name); 3057 } 3058 if (DEBUG_EPHEMERAL) { 3059 Slog.v(TAG, "Ephemeral resolver NOT found"); 3060 } 3061 return null; 3062 } 3063 3064 private @Nullable ComponentName getEphemeralInstallerLPr() { 3065 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3066 intent.addCategory(Intent.CATEGORY_DEFAULT); 3067 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3068 3069 final int resolveFlags = 3070 MATCH_DIRECT_BOOT_AWARE 3071 | MATCH_DIRECT_BOOT_UNAWARE 3072 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3073 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3074 resolveFlags, UserHandle.USER_SYSTEM); 3075 Iterator<ResolveInfo> iter = matches.iterator(); 3076 while (iter.hasNext()) { 3077 final ResolveInfo rInfo = iter.next(); 3078 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3079 if (ps != null) { 3080 final PermissionsState permissionsState = ps.getPermissionsState(); 3081 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3082 continue; 3083 } 3084 } 3085 iter.remove(); 3086 } 3087 if (matches.size() == 0) { 3088 return null; 3089 } else if (matches.size() == 1) { 3090 return matches.get(0).getComponentInfo().getComponentName(); 3091 } else { 3092 throw new RuntimeException( 3093 "There must be at most one ephemeral installer; found " + matches); 3094 } 3095 } 3096 3097 private void primeDomainVerificationsLPw(int userId) { 3098 if (DEBUG_DOMAIN_VERIFICATION) { 3099 Slog.d(TAG, "Priming domain verifications in user " + userId); 3100 } 3101 3102 SystemConfig systemConfig = SystemConfig.getInstance(); 3103 ArraySet<String> packages = systemConfig.getLinkedApps(); 3104 3105 for (String packageName : packages) { 3106 PackageParser.Package pkg = mPackages.get(packageName); 3107 if (pkg != null) { 3108 if (!pkg.isSystemApp()) { 3109 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3110 continue; 3111 } 3112 3113 ArraySet<String> domains = null; 3114 for (PackageParser.Activity a : pkg.activities) { 3115 for (ActivityIntentInfo filter : a.intents) { 3116 if (hasValidDomains(filter)) { 3117 if (domains == null) { 3118 domains = new ArraySet<String>(); 3119 } 3120 domains.addAll(filter.getHostsList()); 3121 } 3122 } 3123 } 3124 3125 if (domains != null && domains.size() > 0) { 3126 if (DEBUG_DOMAIN_VERIFICATION) { 3127 Slog.v(TAG, " + " + packageName); 3128 } 3129 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3130 // state w.r.t. the formal app-linkage "no verification attempted" state; 3131 // and then 'always' in the per-user state actually used for intent resolution. 3132 final IntentFilterVerificationInfo ivi; 3133 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3134 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3135 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3136 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3137 } else { 3138 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3139 + "' does not handle web links"); 3140 } 3141 } else { 3142 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3143 } 3144 } 3145 3146 scheduleWritePackageRestrictionsLocked(userId); 3147 scheduleWriteSettingsLocked(); 3148 } 3149 3150 private void applyFactoryDefaultBrowserLPw(int userId) { 3151 // The default browser app's package name is stored in a string resource, 3152 // with a product-specific overlay used for vendor customization. 3153 String browserPkg = mContext.getResources().getString( 3154 com.android.internal.R.string.default_browser); 3155 if (!TextUtils.isEmpty(browserPkg)) { 3156 // non-empty string => required to be a known package 3157 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3158 if (ps == null) { 3159 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3160 browserPkg = null; 3161 } else { 3162 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3163 } 3164 } 3165 3166 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3167 // default. If there's more than one, just leave everything alone. 3168 if (browserPkg == null) { 3169 calculateDefaultBrowserLPw(userId); 3170 } 3171 } 3172 3173 private void calculateDefaultBrowserLPw(int userId) { 3174 List<String> allBrowsers = resolveAllBrowserApps(userId); 3175 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3176 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3177 } 3178 3179 private List<String> resolveAllBrowserApps(int userId) { 3180 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3181 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3182 PackageManager.MATCH_ALL, userId); 3183 3184 final int count = list.size(); 3185 List<String> result = new ArrayList<String>(count); 3186 for (int i=0; i<count; i++) { 3187 ResolveInfo info = list.get(i); 3188 if (info.activityInfo == null 3189 || !info.handleAllWebDataURI 3190 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3191 || result.contains(info.activityInfo.packageName)) { 3192 continue; 3193 } 3194 result.add(info.activityInfo.packageName); 3195 } 3196 3197 return result; 3198 } 3199 3200 private boolean packageIsBrowser(String packageName, int userId) { 3201 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3202 PackageManager.MATCH_ALL, userId); 3203 final int N = list.size(); 3204 for (int i = 0; i < N; i++) { 3205 ResolveInfo info = list.get(i); 3206 if (packageName.equals(info.activityInfo.packageName)) { 3207 return true; 3208 } 3209 } 3210 return false; 3211 } 3212 3213 private void checkDefaultBrowser() { 3214 final int myUserId = UserHandle.myUserId(); 3215 final String packageName = getDefaultBrowserPackageName(myUserId); 3216 if (packageName != null) { 3217 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3218 if (info == null) { 3219 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3220 synchronized (mPackages) { 3221 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3222 } 3223 } 3224 } 3225 } 3226 3227 @Override 3228 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3229 throws RemoteException { 3230 try { 3231 return super.onTransact(code, data, reply, flags); 3232 } catch (RuntimeException e) { 3233 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3234 Slog.wtf(TAG, "Package Manager Crash", e); 3235 } 3236 throw e; 3237 } 3238 } 3239 3240 static int[] appendInts(int[] cur, int[] add) { 3241 if (add == null) return cur; 3242 if (cur == null) return add; 3243 final int N = add.length; 3244 for (int i=0; i<N; i++) { 3245 cur = appendInt(cur, add[i]); 3246 } 3247 return cur; 3248 } 3249 3250 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3251 if (!sUserManager.exists(userId)) return null; 3252 if (ps == null) { 3253 return null; 3254 } 3255 final PackageParser.Package p = ps.pkg; 3256 if (p == null) { 3257 return null; 3258 } 3259 3260 final PermissionsState permissionsState = ps.getPermissionsState(); 3261 3262 // Compute GIDs only if requested 3263 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3264 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3265 // Compute granted permissions only if package has requested permissions 3266 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3267 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3268 final PackageUserState state = ps.readUserState(userId); 3269 3270 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3271 && ps.isSystem()) { 3272 flags |= MATCH_ANY_USER; 3273 } 3274 3275 return PackageParser.generatePackageInfo(p, gids, flags, 3276 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3277 } 3278 3279 @Override 3280 public void checkPackageStartable(String packageName, int userId) { 3281 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3282 3283 synchronized (mPackages) { 3284 final PackageSetting ps = mSettings.mPackages.get(packageName); 3285 if (ps == null) { 3286 throw new SecurityException("Package " + packageName + " was not found!"); 3287 } 3288 3289 if (!ps.getInstalled(userId)) { 3290 throw new SecurityException( 3291 "Package " + packageName + " was not installed for user " + userId + "!"); 3292 } 3293 3294 if (mSafeMode && !ps.isSystem()) { 3295 throw new SecurityException("Package " + packageName + " not a system app!"); 3296 } 3297 3298 if (mFrozenPackages.contains(packageName)) { 3299 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3300 } 3301 3302 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3303 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3304 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3305 } 3306 } 3307 } 3308 3309 @Override 3310 public boolean isPackageAvailable(String packageName, int userId) { 3311 if (!sUserManager.exists(userId)) return false; 3312 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3313 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3314 synchronized (mPackages) { 3315 PackageParser.Package p = mPackages.get(packageName); 3316 if (p != null) { 3317 final PackageSetting ps = (PackageSetting) p.mExtras; 3318 if (ps != null) { 3319 final PackageUserState state = ps.readUserState(userId); 3320 if (state != null) { 3321 return PackageParser.isAvailable(state); 3322 } 3323 } 3324 } 3325 } 3326 return false; 3327 } 3328 3329 @Override 3330 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3331 if (!sUserManager.exists(userId)) return null; 3332 flags = updateFlagsForPackage(flags, userId, packageName); 3333 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3334 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3335 3336 // reader 3337 synchronized (mPackages) { 3338 // Normalize package name to hanlde renamed packages 3339 packageName = normalizePackageNameLPr(packageName); 3340 3341 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3342 PackageParser.Package p = null; 3343 if (matchFactoryOnly) { 3344 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3345 if (ps != null) { 3346 return generatePackageInfo(ps, flags, userId); 3347 } 3348 } 3349 if (p == null) { 3350 p = mPackages.get(packageName); 3351 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3352 return null; 3353 } 3354 } 3355 if (DEBUG_PACKAGE_INFO) 3356 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3357 if (p != null) { 3358 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3359 } 3360 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3361 final PackageSetting ps = mSettings.mPackages.get(packageName); 3362 return generatePackageInfo(ps, flags, userId); 3363 } 3364 } 3365 return null; 3366 } 3367 3368 @Override 3369 public String[] currentToCanonicalPackageNames(String[] names) { 3370 String[] out = new String[names.length]; 3371 // reader 3372 synchronized (mPackages) { 3373 for (int i=names.length-1; i>=0; i--) { 3374 PackageSetting ps = mSettings.mPackages.get(names[i]); 3375 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3376 } 3377 } 3378 return out; 3379 } 3380 3381 @Override 3382 public String[] canonicalToCurrentPackageNames(String[] names) { 3383 String[] out = new String[names.length]; 3384 // reader 3385 synchronized (mPackages) { 3386 for (int i=names.length-1; i>=0; i--) { 3387 String cur = mSettings.getRenamedPackageLPr(names[i]); 3388 out[i] = cur != null ? cur : names[i]; 3389 } 3390 } 3391 return out; 3392 } 3393 3394 @Override 3395 public int getPackageUid(String packageName, int flags, int userId) { 3396 if (!sUserManager.exists(userId)) return -1; 3397 flags = updateFlagsForPackage(flags, userId, packageName); 3398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3399 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3400 3401 // reader 3402 synchronized (mPackages) { 3403 final PackageParser.Package p = mPackages.get(packageName); 3404 if (p != null && p.isMatch(flags)) { 3405 return UserHandle.getUid(userId, p.applicationInfo.uid); 3406 } 3407 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3408 final PackageSetting ps = mSettings.mPackages.get(packageName); 3409 if (ps != null && ps.isMatch(flags)) { 3410 return UserHandle.getUid(userId, ps.appId); 3411 } 3412 } 3413 } 3414 3415 return -1; 3416 } 3417 3418 @Override 3419 public int[] getPackageGids(String packageName, int flags, int userId) { 3420 if (!sUserManager.exists(userId)) return null; 3421 flags = updateFlagsForPackage(flags, userId, packageName); 3422 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3423 false /* requireFullPermission */, false /* checkShell */, 3424 "getPackageGids"); 3425 3426 // reader 3427 synchronized (mPackages) { 3428 final PackageParser.Package p = mPackages.get(packageName); 3429 if (p != null && p.isMatch(flags)) { 3430 PackageSetting ps = (PackageSetting) p.mExtras; 3431 // TODO: Shouldn't this be checking for package installed state for userId and 3432 // return null? 3433 return ps.getPermissionsState().computeGids(userId); 3434 } 3435 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3436 final PackageSetting ps = mSettings.mPackages.get(packageName); 3437 if (ps != null && ps.isMatch(flags)) { 3438 return ps.getPermissionsState().computeGids(userId); 3439 } 3440 } 3441 } 3442 3443 return null; 3444 } 3445 3446 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3447 if (bp.perm != null) { 3448 return PackageParser.generatePermissionInfo(bp.perm, flags); 3449 } 3450 PermissionInfo pi = new PermissionInfo(); 3451 pi.name = bp.name; 3452 pi.packageName = bp.sourcePackage; 3453 pi.nonLocalizedLabel = bp.name; 3454 pi.protectionLevel = bp.protectionLevel; 3455 return pi; 3456 } 3457 3458 @Override 3459 public PermissionInfo getPermissionInfo(String name, int flags) { 3460 // reader 3461 synchronized (mPackages) { 3462 final BasePermission p = mSettings.mPermissions.get(name); 3463 if (p != null) { 3464 return generatePermissionInfo(p, flags); 3465 } 3466 return null; 3467 } 3468 } 3469 3470 @Override 3471 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3472 int flags) { 3473 // reader 3474 synchronized (mPackages) { 3475 if (group != null && !mPermissionGroups.containsKey(group)) { 3476 // This is thrown as NameNotFoundException 3477 return null; 3478 } 3479 3480 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3481 for (BasePermission p : mSettings.mPermissions.values()) { 3482 if (group == null) { 3483 if (p.perm == null || p.perm.info.group == null) { 3484 out.add(generatePermissionInfo(p, flags)); 3485 } 3486 } else { 3487 if (p.perm != null && group.equals(p.perm.info.group)) { 3488 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3489 } 3490 } 3491 } 3492 return new ParceledListSlice<>(out); 3493 } 3494 } 3495 3496 @Override 3497 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3498 // reader 3499 synchronized (mPackages) { 3500 return PackageParser.generatePermissionGroupInfo( 3501 mPermissionGroups.get(name), flags); 3502 } 3503 } 3504 3505 @Override 3506 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3507 // reader 3508 synchronized (mPackages) { 3509 final int N = mPermissionGroups.size(); 3510 ArrayList<PermissionGroupInfo> out 3511 = new ArrayList<PermissionGroupInfo>(N); 3512 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3513 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3514 } 3515 return new ParceledListSlice<>(out); 3516 } 3517 } 3518 3519 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3520 int userId) { 3521 if (!sUserManager.exists(userId)) return null; 3522 PackageSetting ps = mSettings.mPackages.get(packageName); 3523 if (ps != null) { 3524 if (ps.pkg == null) { 3525 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3526 if (pInfo != null) { 3527 return pInfo.applicationInfo; 3528 } 3529 return null; 3530 } 3531 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3532 ps.readUserState(userId), userId); 3533 } 3534 return null; 3535 } 3536 3537 @Override 3538 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3539 if (!sUserManager.exists(userId)) return null; 3540 flags = updateFlagsForApplication(flags, userId, packageName); 3541 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3542 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3543 3544 // writer 3545 synchronized (mPackages) { 3546 // Normalize package name to hanlde renamed packages 3547 packageName = normalizePackageNameLPr(packageName); 3548 3549 PackageParser.Package p = mPackages.get(packageName); 3550 if (DEBUG_PACKAGE_INFO) Log.v( 3551 TAG, "getApplicationInfo " + packageName 3552 + ": " + p); 3553 if (p != null) { 3554 PackageSetting ps = mSettings.mPackages.get(packageName); 3555 if (ps == null) return null; 3556 // Note: isEnabledLP() does not apply here - always return info 3557 return PackageParser.generateApplicationInfo( 3558 p, flags, ps.readUserState(userId), userId); 3559 } 3560 if ("android".equals(packageName)||"system".equals(packageName)) { 3561 return mAndroidApplication; 3562 } 3563 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3564 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3565 } 3566 } 3567 return null; 3568 } 3569 3570 private String normalizePackageNameLPr(String packageName) { 3571 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3572 return normalizedPackageName != null ? normalizedPackageName : packageName; 3573 } 3574 3575 @Override 3576 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3577 final IPackageDataObserver observer) { 3578 mContext.enforceCallingOrSelfPermission( 3579 android.Manifest.permission.CLEAR_APP_CACHE, null); 3580 // Queue up an async operation since clearing cache may take a little while. 3581 mHandler.post(new Runnable() { 3582 public void run() { 3583 mHandler.removeCallbacks(this); 3584 boolean success = true; 3585 synchronized (mInstallLock) { 3586 try { 3587 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3588 } catch (InstallerException e) { 3589 Slog.w(TAG, "Couldn't clear application caches: " + e); 3590 success = false; 3591 } 3592 } 3593 if (observer != null) { 3594 try { 3595 observer.onRemoveCompleted(null, success); 3596 } catch (RemoteException e) { 3597 Slog.w(TAG, "RemoveException when invoking call back"); 3598 } 3599 } 3600 } 3601 }); 3602 } 3603 3604 @Override 3605 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3606 final IntentSender pi) { 3607 mContext.enforceCallingOrSelfPermission( 3608 android.Manifest.permission.CLEAR_APP_CACHE, null); 3609 // Queue up an async operation since clearing cache may take a little while. 3610 mHandler.post(new Runnable() { 3611 public void run() { 3612 mHandler.removeCallbacks(this); 3613 boolean success = true; 3614 synchronized (mInstallLock) { 3615 try { 3616 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3617 } catch (InstallerException e) { 3618 Slog.w(TAG, "Couldn't clear application caches: " + e); 3619 success = false; 3620 } 3621 } 3622 if(pi != null) { 3623 try { 3624 // Callback via pending intent 3625 int code = success ? 1 : 0; 3626 pi.sendIntent(null, code, null, 3627 null, null); 3628 } catch (SendIntentException e1) { 3629 Slog.i(TAG, "Failed to send pending intent"); 3630 } 3631 } 3632 } 3633 }); 3634 } 3635 3636 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3637 synchronized (mInstallLock) { 3638 try { 3639 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3640 } catch (InstallerException e) { 3641 throw new IOException("Failed to free enough space", e); 3642 } 3643 } 3644 } 3645 3646 /** 3647 * Update given flags based on encryption status of current user. 3648 */ 3649 private int updateFlags(int flags, int userId) { 3650 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3651 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3652 // Caller expressed an explicit opinion about what encryption 3653 // aware/unaware components they want to see, so fall through and 3654 // give them what they want 3655 } else { 3656 // Caller expressed no opinion, so match based on user state 3657 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3658 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3659 } else { 3660 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3661 } 3662 } 3663 return flags; 3664 } 3665 3666 private UserManagerInternal getUserManagerInternal() { 3667 if (mUserManagerInternal == null) { 3668 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3669 } 3670 return mUserManagerInternal; 3671 } 3672 3673 /** 3674 * Update given flags when being used to request {@link PackageInfo}. 3675 */ 3676 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3677 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3678 boolean triaged = true; 3679 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3680 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3681 // Caller is asking for component details, so they'd better be 3682 // asking for specific encryption matching behavior, or be triaged 3683 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3684 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3685 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3686 triaged = false; 3687 } 3688 } 3689 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3690 | PackageManager.MATCH_SYSTEM_ONLY 3691 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3692 triaged = false; 3693 } 3694 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3695 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3696 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3697 + Debug.getCallers(5)); 3698 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3699 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3700 // If the caller wants all packages and has a restricted profile associated with it, 3701 // then match all users. This is to make sure that launchers that need to access work 3702 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3703 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3704 flags |= PackageManager.MATCH_ANY_USER; 3705 } 3706 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3707 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3708 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3709 } 3710 return updateFlags(flags, userId); 3711 } 3712 3713 /** 3714 * Update given flags when being used to request {@link ApplicationInfo}. 3715 */ 3716 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3717 return updateFlagsForPackage(flags, userId, cookie); 3718 } 3719 3720 /** 3721 * Update given flags when being used to request {@link ComponentInfo}. 3722 */ 3723 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3724 if (cookie instanceof Intent) { 3725 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3726 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3727 } 3728 } 3729 3730 boolean triaged = true; 3731 // Caller is asking for component details, so they'd better be 3732 // asking for specific encryption matching behavior, or be triaged 3733 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3734 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3735 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3736 triaged = false; 3737 } 3738 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3739 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3740 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3741 } 3742 3743 return updateFlags(flags, userId); 3744 } 3745 3746 /** 3747 * Update given flags when being used to request {@link ResolveInfo}. 3748 */ 3749 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3750 // Safe mode means we shouldn't match any third-party components 3751 if (mSafeMode) { 3752 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3753 } 3754 final int callingUid = Binder.getCallingUid(); 3755 if (callingUid == Process.SYSTEM_UID || callingUid == 0) { 3756 // The system sees all components 3757 flags |= PackageManager.MATCH_EPHEMERAL; 3758 } else if (getEphemeralPackageName(callingUid) != null) { 3759 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3760 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3761 flags |= PackageManager.MATCH_EPHEMERAL; 3762 } else { 3763 // Otherwise, prevent leaking ephemeral components 3764 flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3765 flags &= ~PackageManager.MATCH_EPHEMERAL; 3766 } 3767 return updateFlagsForComponent(flags, userId, cookie); 3768 } 3769 3770 @Override 3771 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3772 if (!sUserManager.exists(userId)) return null; 3773 flags = updateFlagsForComponent(flags, userId, component); 3774 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3775 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3776 synchronized (mPackages) { 3777 PackageParser.Activity a = mActivities.mActivities.get(component); 3778 3779 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3780 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3781 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3782 if (ps == null) return null; 3783 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3784 userId); 3785 } 3786 if (mResolveComponentName.equals(component)) { 3787 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3788 new PackageUserState(), userId); 3789 } 3790 } 3791 return null; 3792 } 3793 3794 @Override 3795 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3796 String resolvedType) { 3797 synchronized (mPackages) { 3798 if (component.equals(mResolveComponentName)) { 3799 // The resolver supports EVERYTHING! 3800 return true; 3801 } 3802 PackageParser.Activity a = mActivities.mActivities.get(component); 3803 if (a == null) { 3804 return false; 3805 } 3806 for (int i=0; i<a.intents.size(); i++) { 3807 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3808 intent.getData(), intent.getCategories(), TAG) >= 0) { 3809 return true; 3810 } 3811 } 3812 return false; 3813 } 3814 } 3815 3816 @Override 3817 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3818 if (!sUserManager.exists(userId)) return null; 3819 flags = updateFlagsForComponent(flags, userId, component); 3820 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3821 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3822 synchronized (mPackages) { 3823 PackageParser.Activity a = mReceivers.mActivities.get(component); 3824 if (DEBUG_PACKAGE_INFO) Log.v( 3825 TAG, "getReceiverInfo " + component + ": " + a); 3826 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3827 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3828 if (ps == null) return null; 3829 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3830 userId); 3831 } 3832 } 3833 return null; 3834 } 3835 3836 @Override 3837 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3838 if (!sUserManager.exists(userId)) return null; 3839 flags = updateFlagsForComponent(flags, userId, component); 3840 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3841 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3842 synchronized (mPackages) { 3843 PackageParser.Service s = mServices.mServices.get(component); 3844 if (DEBUG_PACKAGE_INFO) Log.v( 3845 TAG, "getServiceInfo " + component + ": " + s); 3846 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3847 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3848 if (ps == null) return null; 3849 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3850 userId); 3851 } 3852 } 3853 return null; 3854 } 3855 3856 @Override 3857 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3858 if (!sUserManager.exists(userId)) return null; 3859 flags = updateFlagsForComponent(flags, userId, component); 3860 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3861 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3862 synchronized (mPackages) { 3863 PackageParser.Provider p = mProviders.mProviders.get(component); 3864 if (DEBUG_PACKAGE_INFO) Log.v( 3865 TAG, "getProviderInfo " + component + ": " + p); 3866 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3867 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3868 if (ps == null) return null; 3869 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3870 userId); 3871 } 3872 } 3873 return null; 3874 } 3875 3876 @Override 3877 public String[] getSystemSharedLibraryNames() { 3878 Set<String> libSet; 3879 synchronized (mPackages) { 3880 libSet = mSharedLibraries.keySet(); 3881 int size = libSet.size(); 3882 if (size > 0) { 3883 String[] libs = new String[size]; 3884 libSet.toArray(libs); 3885 return libs; 3886 } 3887 } 3888 return null; 3889 } 3890 3891 @Override 3892 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3893 synchronized (mPackages) { 3894 return mServicesSystemSharedLibraryPackageName; 3895 } 3896 } 3897 3898 @Override 3899 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3900 synchronized (mPackages) { 3901 return mSharedSystemSharedLibraryPackageName; 3902 } 3903 } 3904 3905 @Override 3906 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3907 synchronized (mPackages) { 3908 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3909 3910 final FeatureInfo fi = new FeatureInfo(); 3911 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3912 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3913 res.add(fi); 3914 3915 return new ParceledListSlice<>(res); 3916 } 3917 } 3918 3919 @Override 3920 public boolean hasSystemFeature(String name, int version) { 3921 synchronized (mPackages) { 3922 final FeatureInfo feat = mAvailableFeatures.get(name); 3923 if (feat == null) { 3924 return false; 3925 } else { 3926 return feat.version >= version; 3927 } 3928 } 3929 } 3930 3931 @Override 3932 public int checkPermission(String permName, String pkgName, int userId) { 3933 if (!sUserManager.exists(userId)) { 3934 return PackageManager.PERMISSION_DENIED; 3935 } 3936 3937 synchronized (mPackages) { 3938 final PackageParser.Package p = mPackages.get(pkgName); 3939 if (p != null && p.mExtras != null) { 3940 final PackageSetting ps = (PackageSetting) p.mExtras; 3941 final PermissionsState permissionsState = ps.getPermissionsState(); 3942 if (permissionsState.hasPermission(permName, userId)) { 3943 return PackageManager.PERMISSION_GRANTED; 3944 } 3945 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3946 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3947 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3948 return PackageManager.PERMISSION_GRANTED; 3949 } 3950 } 3951 } 3952 3953 return PackageManager.PERMISSION_DENIED; 3954 } 3955 3956 @Override 3957 public int checkUidPermission(String permName, int uid) { 3958 final int userId = UserHandle.getUserId(uid); 3959 3960 if (!sUserManager.exists(userId)) { 3961 return PackageManager.PERMISSION_DENIED; 3962 } 3963 3964 synchronized (mPackages) { 3965 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3966 if (obj != null) { 3967 final SettingBase ps = (SettingBase) obj; 3968 final PermissionsState permissionsState = ps.getPermissionsState(); 3969 if (permissionsState.hasPermission(permName, userId)) { 3970 return PackageManager.PERMISSION_GRANTED; 3971 } 3972 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3973 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3974 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3975 return PackageManager.PERMISSION_GRANTED; 3976 } 3977 } else { 3978 ArraySet<String> perms = mSystemPermissions.get(uid); 3979 if (perms != null) { 3980 if (perms.contains(permName)) { 3981 return PackageManager.PERMISSION_GRANTED; 3982 } 3983 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3984 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3985 return PackageManager.PERMISSION_GRANTED; 3986 } 3987 } 3988 } 3989 } 3990 3991 return PackageManager.PERMISSION_DENIED; 3992 } 3993 3994 @Override 3995 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3996 if (UserHandle.getCallingUserId() != userId) { 3997 mContext.enforceCallingPermission( 3998 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3999 "isPermissionRevokedByPolicy for user " + userId); 4000 } 4001 4002 if (checkPermission(permission, packageName, userId) 4003 == PackageManager.PERMISSION_GRANTED) { 4004 return false; 4005 } 4006 4007 final long identity = Binder.clearCallingIdentity(); 4008 try { 4009 final int flags = getPermissionFlags(permission, packageName, userId); 4010 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4011 } finally { 4012 Binder.restoreCallingIdentity(identity); 4013 } 4014 } 4015 4016 @Override 4017 public String getPermissionControllerPackageName() { 4018 synchronized (mPackages) { 4019 return mRequiredInstallerPackage; 4020 } 4021 } 4022 4023 /** 4024 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4025 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4026 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4027 * @param message the message to log on security exception 4028 */ 4029 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4030 boolean checkShell, String message) { 4031 if (userId < 0) { 4032 throw new IllegalArgumentException("Invalid userId " + userId); 4033 } 4034 if (checkShell) { 4035 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4036 } 4037 if (userId == UserHandle.getUserId(callingUid)) return; 4038 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4039 if (requireFullPermission) { 4040 mContext.enforceCallingOrSelfPermission( 4041 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4042 } else { 4043 try { 4044 mContext.enforceCallingOrSelfPermission( 4045 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4046 } catch (SecurityException se) { 4047 mContext.enforceCallingOrSelfPermission( 4048 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4049 } 4050 } 4051 } 4052 } 4053 4054 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4055 if (callingUid == Process.SHELL_UID) { 4056 if (userHandle >= 0 4057 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4058 throw new SecurityException("Shell does not have permission to access user " 4059 + userHandle); 4060 } else if (userHandle < 0) { 4061 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4062 + Debug.getCallers(3)); 4063 } 4064 } 4065 } 4066 4067 private BasePermission findPermissionTreeLP(String permName) { 4068 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4069 if (permName.startsWith(bp.name) && 4070 permName.length() > bp.name.length() && 4071 permName.charAt(bp.name.length()) == '.') { 4072 return bp; 4073 } 4074 } 4075 return null; 4076 } 4077 4078 private BasePermission checkPermissionTreeLP(String permName) { 4079 if (permName != null) { 4080 BasePermission bp = findPermissionTreeLP(permName); 4081 if (bp != null) { 4082 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4083 return bp; 4084 } 4085 throw new SecurityException("Calling uid " 4086 + Binder.getCallingUid() 4087 + " is not allowed to add to permission tree " 4088 + bp.name + " owned by uid " + bp.uid); 4089 } 4090 } 4091 throw new SecurityException("No permission tree found for " + permName); 4092 } 4093 4094 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4095 if (s1 == null) { 4096 return s2 == null; 4097 } 4098 if (s2 == null) { 4099 return false; 4100 } 4101 if (s1.getClass() != s2.getClass()) { 4102 return false; 4103 } 4104 return s1.equals(s2); 4105 } 4106 4107 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4108 if (pi1.icon != pi2.icon) return false; 4109 if (pi1.logo != pi2.logo) return false; 4110 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4111 if (!compareStrings(pi1.name, pi2.name)) return false; 4112 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4113 // We'll take care of setting this one. 4114 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4115 // These are not currently stored in settings. 4116 //if (!compareStrings(pi1.group, pi2.group)) return false; 4117 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4118 //if (pi1.labelRes != pi2.labelRes) return false; 4119 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4120 return true; 4121 } 4122 4123 int permissionInfoFootprint(PermissionInfo info) { 4124 int size = info.name.length(); 4125 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4126 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4127 return size; 4128 } 4129 4130 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4131 int size = 0; 4132 for (BasePermission perm : mSettings.mPermissions.values()) { 4133 if (perm.uid == tree.uid) { 4134 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4135 } 4136 } 4137 return size; 4138 } 4139 4140 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4141 // We calculate the max size of permissions defined by this uid and throw 4142 // if that plus the size of 'info' would exceed our stated maximum. 4143 if (tree.uid != Process.SYSTEM_UID) { 4144 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4145 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4146 throw new SecurityException("Permission tree size cap exceeded"); 4147 } 4148 } 4149 } 4150 4151 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4152 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4153 throw new SecurityException("Label must be specified in permission"); 4154 } 4155 BasePermission tree = checkPermissionTreeLP(info.name); 4156 BasePermission bp = mSettings.mPermissions.get(info.name); 4157 boolean added = bp == null; 4158 boolean changed = true; 4159 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4160 if (added) { 4161 enforcePermissionCapLocked(info, tree); 4162 bp = new BasePermission(info.name, tree.sourcePackage, 4163 BasePermission.TYPE_DYNAMIC); 4164 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4165 throw new SecurityException( 4166 "Not allowed to modify non-dynamic permission " 4167 + info.name); 4168 } else { 4169 if (bp.protectionLevel == fixedLevel 4170 && bp.perm.owner.equals(tree.perm.owner) 4171 && bp.uid == tree.uid 4172 && comparePermissionInfos(bp.perm.info, info)) { 4173 changed = false; 4174 } 4175 } 4176 bp.protectionLevel = fixedLevel; 4177 info = new PermissionInfo(info); 4178 info.protectionLevel = fixedLevel; 4179 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4180 bp.perm.info.packageName = tree.perm.info.packageName; 4181 bp.uid = tree.uid; 4182 if (added) { 4183 mSettings.mPermissions.put(info.name, bp); 4184 } 4185 if (changed) { 4186 if (!async) { 4187 mSettings.writeLPr(); 4188 } else { 4189 scheduleWriteSettingsLocked(); 4190 } 4191 } 4192 return added; 4193 } 4194 4195 @Override 4196 public boolean addPermission(PermissionInfo info) { 4197 synchronized (mPackages) { 4198 return addPermissionLocked(info, false); 4199 } 4200 } 4201 4202 @Override 4203 public boolean addPermissionAsync(PermissionInfo info) { 4204 synchronized (mPackages) { 4205 return addPermissionLocked(info, true); 4206 } 4207 } 4208 4209 @Override 4210 public void removePermission(String name) { 4211 synchronized (mPackages) { 4212 checkPermissionTreeLP(name); 4213 BasePermission bp = mSettings.mPermissions.get(name); 4214 if (bp != null) { 4215 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4216 throw new SecurityException( 4217 "Not allowed to modify non-dynamic permission " 4218 + name); 4219 } 4220 mSettings.mPermissions.remove(name); 4221 mSettings.writeLPr(); 4222 } 4223 } 4224 } 4225 4226 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4227 BasePermission bp) { 4228 int index = pkg.requestedPermissions.indexOf(bp.name); 4229 if (index == -1) { 4230 throw new SecurityException("Package " + pkg.packageName 4231 + " has not requested permission " + bp.name); 4232 } 4233 if (!bp.isRuntime() && !bp.isDevelopment()) { 4234 throw new SecurityException("Permission " + bp.name 4235 + " is not a changeable permission type"); 4236 } 4237 } 4238 4239 @Override 4240 public void grantRuntimePermission(String packageName, String name, final int userId) { 4241 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4242 } 4243 4244 private void grantRuntimePermission(String packageName, String name, final int userId, 4245 boolean overridePolicy) { 4246 if (!sUserManager.exists(userId)) { 4247 Log.e(TAG, "No such user:" + userId); 4248 return; 4249 } 4250 4251 mContext.enforceCallingOrSelfPermission( 4252 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4253 "grantRuntimePermission"); 4254 4255 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4256 true /* requireFullPermission */, true /* checkShell */, 4257 "grantRuntimePermission"); 4258 4259 final int uid; 4260 final SettingBase sb; 4261 4262 synchronized (mPackages) { 4263 final PackageParser.Package pkg = mPackages.get(packageName); 4264 if (pkg == null) { 4265 throw new IllegalArgumentException("Unknown package: " + packageName); 4266 } 4267 4268 final BasePermission bp = mSettings.mPermissions.get(name); 4269 if (bp == null) { 4270 throw new IllegalArgumentException("Unknown permission: " + name); 4271 } 4272 4273 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4274 4275 // If a permission review is required for legacy apps we represent 4276 // their permissions as always granted runtime ones since we need 4277 // to keep the review required permission flag per user while an 4278 // install permission's state is shared across all users. 4279 if (mPermissionReviewRequired 4280 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4281 && bp.isRuntime()) { 4282 return; 4283 } 4284 4285 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4286 sb = (SettingBase) pkg.mExtras; 4287 if (sb == null) { 4288 throw new IllegalArgumentException("Unknown package: " + packageName); 4289 } 4290 4291 final PermissionsState permissionsState = sb.getPermissionsState(); 4292 4293 final int flags = permissionsState.getPermissionFlags(name, userId); 4294 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4295 throw new SecurityException("Cannot grant system fixed permission " 4296 + name + " for package " + packageName); 4297 } 4298 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4299 throw new SecurityException("Cannot grant policy fixed permission " 4300 + name + " for package " + packageName); 4301 } 4302 4303 if (bp.isDevelopment()) { 4304 // Development permissions must be handled specially, since they are not 4305 // normal runtime permissions. For now they apply to all users. 4306 if (permissionsState.grantInstallPermission(bp) != 4307 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4308 scheduleWriteSettingsLocked(); 4309 } 4310 return; 4311 } 4312 4313 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4314 throw new SecurityException("Cannot grant non-ephemeral permission" 4315 + name + " for package " + packageName); 4316 } 4317 4318 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4319 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4320 return; 4321 } 4322 4323 final int result = permissionsState.grantRuntimePermission(bp, userId); 4324 switch (result) { 4325 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4326 return; 4327 } 4328 4329 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4330 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4331 mHandler.post(new Runnable() { 4332 @Override 4333 public void run() { 4334 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4335 } 4336 }); 4337 } 4338 break; 4339 } 4340 4341 if (bp.isRuntime()) { 4342 logPermissionGranted(mContext, name, packageName); 4343 } 4344 4345 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4346 4347 // Not critical if that is lost - app has to request again. 4348 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4349 } 4350 4351 // Only need to do this if user is initialized. Otherwise it's a new user 4352 // and there are no processes running as the user yet and there's no need 4353 // to make an expensive call to remount processes for the changed permissions. 4354 if (READ_EXTERNAL_STORAGE.equals(name) 4355 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4356 final long token = Binder.clearCallingIdentity(); 4357 try { 4358 if (sUserManager.isInitialized(userId)) { 4359 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4360 StorageManagerInternal.class); 4361 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4362 } 4363 } finally { 4364 Binder.restoreCallingIdentity(token); 4365 } 4366 } 4367 } 4368 4369 @Override 4370 public void revokeRuntimePermission(String packageName, String name, int userId) { 4371 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4372 } 4373 4374 private void revokeRuntimePermission(String packageName, String name, int userId, 4375 boolean overridePolicy) { 4376 if (!sUserManager.exists(userId)) { 4377 Log.e(TAG, "No such user:" + userId); 4378 return; 4379 } 4380 4381 mContext.enforceCallingOrSelfPermission( 4382 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4383 "revokeRuntimePermission"); 4384 4385 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4386 true /* requireFullPermission */, true /* checkShell */, 4387 "revokeRuntimePermission"); 4388 4389 final int appId; 4390 4391 synchronized (mPackages) { 4392 final PackageParser.Package pkg = mPackages.get(packageName); 4393 if (pkg == null) { 4394 throw new IllegalArgumentException("Unknown package: " + packageName); 4395 } 4396 4397 final BasePermission bp = mSettings.mPermissions.get(name); 4398 if (bp == null) { 4399 throw new IllegalArgumentException("Unknown permission: " + name); 4400 } 4401 4402 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4403 4404 // If a permission review is required for legacy apps we represent 4405 // their permissions as always granted runtime ones since we need 4406 // to keep the review required permission flag per user while an 4407 // install permission's state is shared across all users. 4408 if (mPermissionReviewRequired 4409 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4410 && bp.isRuntime()) { 4411 return; 4412 } 4413 4414 SettingBase sb = (SettingBase) pkg.mExtras; 4415 if (sb == null) { 4416 throw new IllegalArgumentException("Unknown package: " + packageName); 4417 } 4418 4419 final PermissionsState permissionsState = sb.getPermissionsState(); 4420 4421 final int flags = permissionsState.getPermissionFlags(name, userId); 4422 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4423 throw new SecurityException("Cannot revoke system fixed permission " 4424 + name + " for package " + packageName); 4425 } 4426 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4427 throw new SecurityException("Cannot revoke policy fixed permission " 4428 + name + " for package " + packageName); 4429 } 4430 4431 if (bp.isDevelopment()) { 4432 // Development permissions must be handled specially, since they are not 4433 // normal runtime permissions. For now they apply to all users. 4434 if (permissionsState.revokeInstallPermission(bp) != 4435 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4436 scheduleWriteSettingsLocked(); 4437 } 4438 return; 4439 } 4440 4441 if (permissionsState.revokeRuntimePermission(bp, userId) == 4442 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4443 return; 4444 } 4445 4446 if (bp.isRuntime()) { 4447 logPermissionRevoked(mContext, name, packageName); 4448 } 4449 4450 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4451 4452 // Critical, after this call app should never have the permission. 4453 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4454 4455 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4456 } 4457 4458 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4459 } 4460 4461 /** 4462 * Get the first event id for the permission. 4463 * 4464 * <p>There are four events for each permission: <ul> 4465 * <li>Request permission: first id + 0</li> 4466 * <li>Grant permission: first id + 1</li> 4467 * <li>Request for permission denied: first id + 2</li> 4468 * <li>Revoke permission: first id + 3</li> 4469 * </ul></p> 4470 * 4471 * @param name name of the permission 4472 * 4473 * @return The first event id for the permission 4474 */ 4475 private static int getBaseEventId(@NonNull String name) { 4476 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4477 4478 if (eventIdIndex == -1) { 4479 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4480 || "user".equals(Build.TYPE)) { 4481 Log.i(TAG, "Unknown permission " + name); 4482 4483 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4484 } else { 4485 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4486 // 4487 // Also update 4488 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4489 // - metrics_constants.proto 4490 throw new IllegalStateException("Unknown permission " + name); 4491 } 4492 } 4493 4494 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4495 } 4496 4497 /** 4498 * Log that a permission was revoked. 4499 * 4500 * @param context Context of the caller 4501 * @param name name of the permission 4502 * @param packageName package permission if for 4503 */ 4504 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4505 @NonNull String packageName) { 4506 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4507 } 4508 4509 /** 4510 * Log that a permission request was granted. 4511 * 4512 * @param context Context of the caller 4513 * @param name name of the permission 4514 * @param packageName package permission if for 4515 */ 4516 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4517 @NonNull String packageName) { 4518 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4519 } 4520 4521 @Override 4522 public void resetRuntimePermissions() { 4523 mContext.enforceCallingOrSelfPermission( 4524 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4525 "revokeRuntimePermission"); 4526 4527 int callingUid = Binder.getCallingUid(); 4528 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4529 mContext.enforceCallingOrSelfPermission( 4530 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4531 "resetRuntimePermissions"); 4532 } 4533 4534 synchronized (mPackages) { 4535 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4536 for (int userId : UserManagerService.getInstance().getUserIds()) { 4537 final int packageCount = mPackages.size(); 4538 for (int i = 0; i < packageCount; i++) { 4539 PackageParser.Package pkg = mPackages.valueAt(i); 4540 if (!(pkg.mExtras instanceof PackageSetting)) { 4541 continue; 4542 } 4543 PackageSetting ps = (PackageSetting) pkg.mExtras; 4544 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4545 } 4546 } 4547 } 4548 } 4549 4550 @Override 4551 public int getPermissionFlags(String name, String packageName, int userId) { 4552 if (!sUserManager.exists(userId)) { 4553 return 0; 4554 } 4555 4556 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4557 4558 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4559 true /* requireFullPermission */, false /* checkShell */, 4560 "getPermissionFlags"); 4561 4562 synchronized (mPackages) { 4563 final PackageParser.Package pkg = mPackages.get(packageName); 4564 if (pkg == null) { 4565 return 0; 4566 } 4567 4568 final BasePermission bp = mSettings.mPermissions.get(name); 4569 if (bp == null) { 4570 return 0; 4571 } 4572 4573 SettingBase sb = (SettingBase) pkg.mExtras; 4574 if (sb == null) { 4575 return 0; 4576 } 4577 4578 PermissionsState permissionsState = sb.getPermissionsState(); 4579 return permissionsState.getPermissionFlags(name, userId); 4580 } 4581 } 4582 4583 @Override 4584 public void updatePermissionFlags(String name, String packageName, int flagMask, 4585 int flagValues, int userId) { 4586 if (!sUserManager.exists(userId)) { 4587 return; 4588 } 4589 4590 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4591 4592 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4593 true /* requireFullPermission */, true /* checkShell */, 4594 "updatePermissionFlags"); 4595 4596 // Only the system can change these flags and nothing else. 4597 if (getCallingUid() != Process.SYSTEM_UID) { 4598 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4599 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4600 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4601 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4602 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4603 } 4604 4605 synchronized (mPackages) { 4606 final PackageParser.Package pkg = mPackages.get(packageName); 4607 if (pkg == null) { 4608 throw new IllegalArgumentException("Unknown package: " + packageName); 4609 } 4610 4611 final BasePermission bp = mSettings.mPermissions.get(name); 4612 if (bp == null) { 4613 throw new IllegalArgumentException("Unknown permission: " + name); 4614 } 4615 4616 SettingBase sb = (SettingBase) pkg.mExtras; 4617 if (sb == null) { 4618 throw new IllegalArgumentException("Unknown package: " + packageName); 4619 } 4620 4621 PermissionsState permissionsState = sb.getPermissionsState(); 4622 4623 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4624 4625 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4626 // Install and runtime permissions are stored in different places, 4627 // so figure out what permission changed and persist the change. 4628 if (permissionsState.getInstallPermissionState(name) != null) { 4629 scheduleWriteSettingsLocked(); 4630 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4631 || hadState) { 4632 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4633 } 4634 } 4635 } 4636 } 4637 4638 /** 4639 * Update the permission flags for all packages and runtime permissions of a user in order 4640 * to allow device or profile owner to remove POLICY_FIXED. 4641 */ 4642 @Override 4643 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4644 if (!sUserManager.exists(userId)) { 4645 return; 4646 } 4647 4648 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4649 4650 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4651 true /* requireFullPermission */, true /* checkShell */, 4652 "updatePermissionFlagsForAllApps"); 4653 4654 // Only the system can change system fixed flags. 4655 if (getCallingUid() != Process.SYSTEM_UID) { 4656 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4657 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4658 } 4659 4660 synchronized (mPackages) { 4661 boolean changed = false; 4662 final int packageCount = mPackages.size(); 4663 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4664 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4665 SettingBase sb = (SettingBase) pkg.mExtras; 4666 if (sb == null) { 4667 continue; 4668 } 4669 PermissionsState permissionsState = sb.getPermissionsState(); 4670 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4671 userId, flagMask, flagValues); 4672 } 4673 if (changed) { 4674 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4675 } 4676 } 4677 } 4678 4679 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4680 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4681 != PackageManager.PERMISSION_GRANTED 4682 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4683 != PackageManager.PERMISSION_GRANTED) { 4684 throw new SecurityException(message + " requires " 4685 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4686 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4687 } 4688 } 4689 4690 @Override 4691 public boolean shouldShowRequestPermissionRationale(String permissionName, 4692 String packageName, int userId) { 4693 if (UserHandle.getCallingUserId() != userId) { 4694 mContext.enforceCallingPermission( 4695 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4696 "canShowRequestPermissionRationale for user " + userId); 4697 } 4698 4699 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4700 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4701 return false; 4702 } 4703 4704 if (checkPermission(permissionName, packageName, userId) 4705 == PackageManager.PERMISSION_GRANTED) { 4706 return false; 4707 } 4708 4709 final int flags; 4710 4711 final long identity = Binder.clearCallingIdentity(); 4712 try { 4713 flags = getPermissionFlags(permissionName, 4714 packageName, userId); 4715 } finally { 4716 Binder.restoreCallingIdentity(identity); 4717 } 4718 4719 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4720 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4721 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4722 4723 if ((flags & fixedFlags) != 0) { 4724 return false; 4725 } 4726 4727 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4728 } 4729 4730 @Override 4731 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4732 mContext.enforceCallingOrSelfPermission( 4733 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4734 "addOnPermissionsChangeListener"); 4735 4736 synchronized (mPackages) { 4737 mOnPermissionChangeListeners.addListenerLocked(listener); 4738 } 4739 } 4740 4741 @Override 4742 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4743 synchronized (mPackages) { 4744 mOnPermissionChangeListeners.removeListenerLocked(listener); 4745 } 4746 } 4747 4748 @Override 4749 public boolean isProtectedBroadcast(String actionName) { 4750 synchronized (mPackages) { 4751 if (mProtectedBroadcasts.contains(actionName)) { 4752 return true; 4753 } else if (actionName != null) { 4754 // TODO: remove these terrible hacks 4755 if (actionName.startsWith("android.net.netmon.lingerExpired") 4756 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4757 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4758 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4759 return true; 4760 } 4761 } 4762 } 4763 return false; 4764 } 4765 4766 @Override 4767 public int checkSignatures(String pkg1, String pkg2) { 4768 synchronized (mPackages) { 4769 final PackageParser.Package p1 = mPackages.get(pkg1); 4770 final PackageParser.Package p2 = mPackages.get(pkg2); 4771 if (p1 == null || p1.mExtras == null 4772 || p2 == null || p2.mExtras == null) { 4773 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4774 } 4775 return compareSignatures(p1.mSignatures, p2.mSignatures); 4776 } 4777 } 4778 4779 @Override 4780 public int checkUidSignatures(int uid1, int uid2) { 4781 // Map to base uids. 4782 uid1 = UserHandle.getAppId(uid1); 4783 uid2 = UserHandle.getAppId(uid2); 4784 // reader 4785 synchronized (mPackages) { 4786 Signature[] s1; 4787 Signature[] s2; 4788 Object obj = mSettings.getUserIdLPr(uid1); 4789 if (obj != null) { 4790 if (obj instanceof SharedUserSetting) { 4791 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4792 } else if (obj instanceof PackageSetting) { 4793 s1 = ((PackageSetting)obj).signatures.mSignatures; 4794 } else { 4795 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4796 } 4797 } else { 4798 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4799 } 4800 obj = mSettings.getUserIdLPr(uid2); 4801 if (obj != null) { 4802 if (obj instanceof SharedUserSetting) { 4803 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4804 } else if (obj instanceof PackageSetting) { 4805 s2 = ((PackageSetting)obj).signatures.mSignatures; 4806 } else { 4807 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4808 } 4809 } else { 4810 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4811 } 4812 return compareSignatures(s1, s2); 4813 } 4814 } 4815 4816 /** 4817 * This method should typically only be used when granting or revoking 4818 * permissions, since the app may immediately restart after this call. 4819 * <p> 4820 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4821 * guard your work against the app being relaunched. 4822 */ 4823 private void killUid(int appId, int userId, String reason) { 4824 final long identity = Binder.clearCallingIdentity(); 4825 try { 4826 IActivityManager am = ActivityManager.getService(); 4827 if (am != null) { 4828 try { 4829 am.killUid(appId, userId, reason); 4830 } catch (RemoteException e) { 4831 /* ignore - same process */ 4832 } 4833 } 4834 } finally { 4835 Binder.restoreCallingIdentity(identity); 4836 } 4837 } 4838 4839 /** 4840 * Compares two sets of signatures. Returns: 4841 * <br /> 4842 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4843 * <br /> 4844 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4845 * <br /> 4846 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4847 * <br /> 4848 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4849 * <br /> 4850 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4851 */ 4852 static int compareSignatures(Signature[] s1, Signature[] s2) { 4853 if (s1 == null) { 4854 return s2 == null 4855 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4856 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4857 } 4858 4859 if (s2 == null) { 4860 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4861 } 4862 4863 if (s1.length != s2.length) { 4864 return PackageManager.SIGNATURE_NO_MATCH; 4865 } 4866 4867 // Since both signature sets are of size 1, we can compare without HashSets. 4868 if (s1.length == 1) { 4869 return s1[0].equals(s2[0]) ? 4870 PackageManager.SIGNATURE_MATCH : 4871 PackageManager.SIGNATURE_NO_MATCH; 4872 } 4873 4874 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4875 for (Signature sig : s1) { 4876 set1.add(sig); 4877 } 4878 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4879 for (Signature sig : s2) { 4880 set2.add(sig); 4881 } 4882 // Make sure s2 contains all signatures in s1. 4883 if (set1.equals(set2)) { 4884 return PackageManager.SIGNATURE_MATCH; 4885 } 4886 return PackageManager.SIGNATURE_NO_MATCH; 4887 } 4888 4889 /** 4890 * If the database version for this type of package (internal storage or 4891 * external storage) is less than the version where package signatures 4892 * were updated, return true. 4893 */ 4894 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4895 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4896 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4897 } 4898 4899 /** 4900 * Used for backward compatibility to make sure any packages with 4901 * certificate chains get upgraded to the new style. {@code existingSigs} 4902 * will be in the old format (since they were stored on disk from before the 4903 * system upgrade) and {@code scannedSigs} will be in the newer format. 4904 */ 4905 private int compareSignaturesCompat(PackageSignatures existingSigs, 4906 PackageParser.Package scannedPkg) { 4907 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4908 return PackageManager.SIGNATURE_NO_MATCH; 4909 } 4910 4911 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4912 for (Signature sig : existingSigs.mSignatures) { 4913 existingSet.add(sig); 4914 } 4915 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4916 for (Signature sig : scannedPkg.mSignatures) { 4917 try { 4918 Signature[] chainSignatures = sig.getChainSignatures(); 4919 for (Signature chainSig : chainSignatures) { 4920 scannedCompatSet.add(chainSig); 4921 } 4922 } catch (CertificateEncodingException e) { 4923 scannedCompatSet.add(sig); 4924 } 4925 } 4926 /* 4927 * Make sure the expanded scanned set contains all signatures in the 4928 * existing one. 4929 */ 4930 if (scannedCompatSet.equals(existingSet)) { 4931 // Migrate the old signatures to the new scheme. 4932 existingSigs.assignSignatures(scannedPkg.mSignatures); 4933 // The new KeySets will be re-added later in the scanning process. 4934 synchronized (mPackages) { 4935 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4936 } 4937 return PackageManager.SIGNATURE_MATCH; 4938 } 4939 return PackageManager.SIGNATURE_NO_MATCH; 4940 } 4941 4942 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4943 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4944 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4945 } 4946 4947 private int compareSignaturesRecover(PackageSignatures existingSigs, 4948 PackageParser.Package scannedPkg) { 4949 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4950 return PackageManager.SIGNATURE_NO_MATCH; 4951 } 4952 4953 String msg = null; 4954 try { 4955 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4956 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4957 + scannedPkg.packageName); 4958 return PackageManager.SIGNATURE_MATCH; 4959 } 4960 } catch (CertificateException e) { 4961 msg = e.getMessage(); 4962 } 4963 4964 logCriticalInfo(Log.INFO, 4965 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4966 return PackageManager.SIGNATURE_NO_MATCH; 4967 } 4968 4969 @Override 4970 public List<String> getAllPackages() { 4971 synchronized (mPackages) { 4972 return new ArrayList<String>(mPackages.keySet()); 4973 } 4974 } 4975 4976 @Override 4977 public String[] getPackagesForUid(int uid) { 4978 final int userId = UserHandle.getUserId(uid); 4979 uid = UserHandle.getAppId(uid); 4980 // reader 4981 synchronized (mPackages) { 4982 Object obj = mSettings.getUserIdLPr(uid); 4983 if (obj instanceof SharedUserSetting) { 4984 final SharedUserSetting sus = (SharedUserSetting) obj; 4985 final int N = sus.packages.size(); 4986 String[] res = new String[N]; 4987 final Iterator<PackageSetting> it = sus.packages.iterator(); 4988 int i = 0; 4989 while (it.hasNext()) { 4990 PackageSetting ps = it.next(); 4991 if (ps.getInstalled(userId)) { 4992 res[i++] = ps.name; 4993 } else { 4994 res = ArrayUtils.removeElement(String.class, res, res[i]); 4995 } 4996 } 4997 return res; 4998 } else if (obj instanceof PackageSetting) { 4999 final PackageSetting ps = (PackageSetting) obj; 5000 return new String[] { ps.name }; 5001 } 5002 } 5003 return null; 5004 } 5005 5006 @Override 5007 public String getNameForUid(int uid) { 5008 // reader 5009 synchronized (mPackages) { 5010 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5011 if (obj instanceof SharedUserSetting) { 5012 final SharedUserSetting sus = (SharedUserSetting) obj; 5013 return sus.name + ":" + sus.userId; 5014 } else if (obj instanceof PackageSetting) { 5015 final PackageSetting ps = (PackageSetting) obj; 5016 return ps.name; 5017 } 5018 } 5019 return null; 5020 } 5021 5022 @Override 5023 public int getUidForSharedUser(String sharedUserName) { 5024 if(sharedUserName == null) { 5025 return -1; 5026 } 5027 // reader 5028 synchronized (mPackages) { 5029 SharedUserSetting suid; 5030 try { 5031 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5032 if (suid != null) { 5033 return suid.userId; 5034 } 5035 } catch (PackageManagerException ignore) { 5036 // can't happen, but, still need to catch it 5037 } 5038 return -1; 5039 } 5040 } 5041 5042 @Override 5043 public int getFlagsForUid(int uid) { 5044 synchronized (mPackages) { 5045 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5046 if (obj instanceof SharedUserSetting) { 5047 final SharedUserSetting sus = (SharedUserSetting) obj; 5048 return sus.pkgFlags; 5049 } else if (obj instanceof PackageSetting) { 5050 final PackageSetting ps = (PackageSetting) obj; 5051 return ps.pkgFlags; 5052 } 5053 } 5054 return 0; 5055 } 5056 5057 @Override 5058 public int getPrivateFlagsForUid(int uid) { 5059 synchronized (mPackages) { 5060 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5061 if (obj instanceof SharedUserSetting) { 5062 final SharedUserSetting sus = (SharedUserSetting) obj; 5063 return sus.pkgPrivateFlags; 5064 } else if (obj instanceof PackageSetting) { 5065 final PackageSetting ps = (PackageSetting) obj; 5066 return ps.pkgPrivateFlags; 5067 } 5068 } 5069 return 0; 5070 } 5071 5072 @Override 5073 public boolean isUidPrivileged(int uid) { 5074 uid = UserHandle.getAppId(uid); 5075 // reader 5076 synchronized (mPackages) { 5077 Object obj = mSettings.getUserIdLPr(uid); 5078 if (obj instanceof SharedUserSetting) { 5079 final SharedUserSetting sus = (SharedUserSetting) obj; 5080 final Iterator<PackageSetting> it = sus.packages.iterator(); 5081 while (it.hasNext()) { 5082 if (it.next().isPrivileged()) { 5083 return true; 5084 } 5085 } 5086 } else if (obj instanceof PackageSetting) { 5087 final PackageSetting ps = (PackageSetting) obj; 5088 return ps.isPrivileged(); 5089 } 5090 } 5091 return false; 5092 } 5093 5094 @Override 5095 public String[] getAppOpPermissionPackages(String permissionName) { 5096 synchronized (mPackages) { 5097 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5098 if (pkgs == null) { 5099 return null; 5100 } 5101 return pkgs.toArray(new String[pkgs.size()]); 5102 } 5103 } 5104 5105 @Override 5106 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5107 int flags, int userId) { 5108 try { 5109 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5110 5111 if (!sUserManager.exists(userId)) return null; 5112 flags = updateFlagsForResolve(flags, userId, intent); 5113 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5114 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5115 5116 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5117 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5118 flags, userId); 5119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5120 5121 final ResolveInfo bestChoice = 5122 chooseBestActivity(intent, resolvedType, flags, query, userId); 5123 return bestChoice; 5124 } finally { 5125 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5126 } 5127 } 5128 5129 @Override 5130 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5131 IntentFilter filter, int match, ComponentName activity) { 5132 final int userId = UserHandle.getCallingUserId(); 5133 if (DEBUG_PREFERRED) { 5134 Log.v(TAG, "setLastChosenActivity intent=" + intent 5135 + " resolvedType=" + resolvedType 5136 + " flags=" + flags 5137 + " filter=" + filter 5138 + " match=" + match 5139 + " activity=" + activity); 5140 filter.dump(new PrintStreamPrinter(System.out), " "); 5141 } 5142 intent.setComponent(null); 5143 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5144 userId); 5145 // Find any earlier preferred or last chosen entries and nuke them 5146 findPreferredActivity(intent, resolvedType, 5147 flags, query, 0, false, true, false, userId); 5148 // Add the new activity as the last chosen for this filter 5149 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5150 "Setting last chosen"); 5151 } 5152 5153 @Override 5154 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5155 final int userId = UserHandle.getCallingUserId(); 5156 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5157 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5158 userId); 5159 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5160 false, false, false, userId); 5161 } 5162 5163 private boolean isEphemeralDisabled() { 5164 // ephemeral apps have been disabled across the board 5165 if (DISABLE_EPHEMERAL_APPS) { 5166 return true; 5167 } 5168 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5169 if (!mSystemReady) { 5170 return true; 5171 } 5172 // we can't get a content resolver until the system is ready; these checks must happen last 5173 final ContentResolver resolver = mContext.getContentResolver(); 5174 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5175 return true; 5176 } 5177 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5178 } 5179 5180 private boolean isEphemeralAllowed( 5181 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5182 boolean skipPackageCheck) { 5183 // Short circuit and return early if possible. 5184 if (isEphemeralDisabled()) { 5185 return false; 5186 } 5187 final int callingUser = UserHandle.getCallingUserId(); 5188 if (callingUser != UserHandle.USER_SYSTEM) { 5189 return false; 5190 } 5191 if (mEphemeralResolverConnection == null) { 5192 return false; 5193 } 5194 if (mEphemeralInstallerComponent == null) { 5195 return false; 5196 } 5197 if (intent.getComponent() != null) { 5198 return false; 5199 } 5200 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5201 return false; 5202 } 5203 if (!skipPackageCheck && intent.getPackage() != null) { 5204 return false; 5205 } 5206 final boolean isWebUri = hasWebURI(intent); 5207 if (!isWebUri || intent.getData().getHost() == null) { 5208 return false; 5209 } 5210 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5211 synchronized (mPackages) { 5212 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5213 for (int n = 0; n < count; n++) { 5214 ResolveInfo info = resolvedActivities.get(n); 5215 String packageName = info.activityInfo.packageName; 5216 PackageSetting ps = mSettings.mPackages.get(packageName); 5217 if (ps != null) { 5218 // Try to get the status from User settings first 5219 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5220 int status = (int) (packedStatus >> 32); 5221 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5222 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5223 if (DEBUG_EPHEMERAL) { 5224 Slog.v(TAG, "DENY ephemeral apps;" 5225 + " pkg: " + packageName + ", status: " + status); 5226 } 5227 return false; 5228 } 5229 } 5230 } 5231 } 5232 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5233 return true; 5234 } 5235 5236 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5237 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5238 int userId) { 5239 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5240 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5241 callingPackage, userId)); 5242 mHandler.sendMessage(msg); 5243 } 5244 5245 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5246 int flags, List<ResolveInfo> query, int userId) { 5247 if (query != null) { 5248 final int N = query.size(); 5249 if (N == 1) { 5250 return query.get(0); 5251 } else if (N > 1) { 5252 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5253 // If there is more than one activity with the same priority, 5254 // then let the user decide between them. 5255 ResolveInfo r0 = query.get(0); 5256 ResolveInfo r1 = query.get(1); 5257 if (DEBUG_INTENT_MATCHING || debug) { 5258 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5259 + r1.activityInfo.name + "=" + r1.priority); 5260 } 5261 // If the first activity has a higher priority, or a different 5262 // default, then it is always desirable to pick it. 5263 if (r0.priority != r1.priority 5264 || r0.preferredOrder != r1.preferredOrder 5265 || r0.isDefault != r1.isDefault) { 5266 return query.get(0); 5267 } 5268 // If we have saved a preference for a preferred activity for 5269 // this Intent, use that. 5270 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5271 flags, query, r0.priority, true, false, debug, userId); 5272 if (ri != null) { 5273 return ri; 5274 } 5275 ri = new ResolveInfo(mResolveInfo); 5276 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5277 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5278 // If all of the options come from the same package, show the application's 5279 // label and icon instead of the generic resolver's. 5280 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5281 // and then throw away the ResolveInfo itself, meaning that the caller loses 5282 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5283 // a fallback for this case; we only set the target package's resources on 5284 // the ResolveInfo, not the ActivityInfo. 5285 final String intentPackage = intent.getPackage(); 5286 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5287 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5288 ri.resolvePackageName = intentPackage; 5289 if (userNeedsBadging(userId)) { 5290 ri.noResourceId = true; 5291 } else { 5292 ri.icon = appi.icon; 5293 } 5294 ri.iconResourceId = appi.icon; 5295 ri.labelRes = appi.labelRes; 5296 } 5297 ri.activityInfo.applicationInfo = new ApplicationInfo( 5298 ri.activityInfo.applicationInfo); 5299 if (userId != 0) { 5300 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5301 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5302 } 5303 // Make sure that the resolver is displayable in car mode 5304 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5305 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5306 return ri; 5307 } 5308 } 5309 return null; 5310 } 5311 5312 /** 5313 * Return true if the given list is not empty and all of its contents have 5314 * an activityInfo with the given package name. 5315 */ 5316 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5317 if (ArrayUtils.isEmpty(list)) { 5318 return false; 5319 } 5320 for (int i = 0, N = list.size(); i < N; i++) { 5321 final ResolveInfo ri = list.get(i); 5322 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5323 if (ai == null || !packageName.equals(ai.packageName)) { 5324 return false; 5325 } 5326 } 5327 return true; 5328 } 5329 5330 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5331 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5332 final int N = query.size(); 5333 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5334 .get(userId); 5335 // Get the list of persistent preferred activities that handle the intent 5336 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5337 List<PersistentPreferredActivity> pprefs = ppir != null 5338 ? ppir.queryIntent(intent, resolvedType, 5339 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5340 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5341 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5342 : null; 5343 if (pprefs != null && pprefs.size() > 0) { 5344 final int M = pprefs.size(); 5345 for (int i=0; i<M; i++) { 5346 final PersistentPreferredActivity ppa = pprefs.get(i); 5347 if (DEBUG_PREFERRED || debug) { 5348 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5349 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5350 + "\n component=" + ppa.mComponent); 5351 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5352 } 5353 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5354 flags | MATCH_DISABLED_COMPONENTS, userId); 5355 if (DEBUG_PREFERRED || debug) { 5356 Slog.v(TAG, "Found persistent preferred activity:"); 5357 if (ai != null) { 5358 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5359 } else { 5360 Slog.v(TAG, " null"); 5361 } 5362 } 5363 if (ai == null) { 5364 // This previously registered persistent preferred activity 5365 // component is no longer known. Ignore it and do NOT remove it. 5366 continue; 5367 } 5368 for (int j=0; j<N; j++) { 5369 final ResolveInfo ri = query.get(j); 5370 if (!ri.activityInfo.applicationInfo.packageName 5371 .equals(ai.applicationInfo.packageName)) { 5372 continue; 5373 } 5374 if (!ri.activityInfo.name.equals(ai.name)) { 5375 continue; 5376 } 5377 // Found a persistent preference that can handle the intent. 5378 if (DEBUG_PREFERRED || debug) { 5379 Slog.v(TAG, "Returning persistent preferred activity: " + 5380 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5381 } 5382 return ri; 5383 } 5384 } 5385 } 5386 return null; 5387 } 5388 5389 // TODO: handle preferred activities missing while user has amnesia 5390 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5391 List<ResolveInfo> query, int priority, boolean always, 5392 boolean removeMatches, boolean debug, int userId) { 5393 if (!sUserManager.exists(userId)) return null; 5394 flags = updateFlagsForResolve(flags, userId, intent); 5395 // writer 5396 synchronized (mPackages) { 5397 if (intent.getSelector() != null) { 5398 intent = intent.getSelector(); 5399 } 5400 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5401 5402 // Try to find a matching persistent preferred activity. 5403 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5404 debug, userId); 5405 5406 // If a persistent preferred activity matched, use it. 5407 if (pri != null) { 5408 return pri; 5409 } 5410 5411 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5412 // Get the list of preferred activities that handle the intent 5413 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5414 List<PreferredActivity> prefs = pir != null 5415 ? pir.queryIntent(intent, resolvedType, 5416 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5417 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5418 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5419 : null; 5420 if (prefs != null && prefs.size() > 0) { 5421 boolean changed = false; 5422 try { 5423 // First figure out how good the original match set is. 5424 // We will only allow preferred activities that came 5425 // from the same match quality. 5426 int match = 0; 5427 5428 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5429 5430 final int N = query.size(); 5431 for (int j=0; j<N; j++) { 5432 final ResolveInfo ri = query.get(j); 5433 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5434 + ": 0x" + Integer.toHexString(match)); 5435 if (ri.match > match) { 5436 match = ri.match; 5437 } 5438 } 5439 5440 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5441 + Integer.toHexString(match)); 5442 5443 match &= IntentFilter.MATCH_CATEGORY_MASK; 5444 final int M = prefs.size(); 5445 for (int i=0; i<M; i++) { 5446 final PreferredActivity pa = prefs.get(i); 5447 if (DEBUG_PREFERRED || debug) { 5448 Slog.v(TAG, "Checking PreferredActivity ds=" 5449 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5450 + "\n component=" + pa.mPref.mComponent); 5451 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5452 } 5453 if (pa.mPref.mMatch != match) { 5454 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5455 + Integer.toHexString(pa.mPref.mMatch)); 5456 continue; 5457 } 5458 // If it's not an "always" type preferred activity and that's what we're 5459 // looking for, skip it. 5460 if (always && !pa.mPref.mAlways) { 5461 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5462 continue; 5463 } 5464 final ActivityInfo ai = getActivityInfo( 5465 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5466 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5467 userId); 5468 if (DEBUG_PREFERRED || debug) { 5469 Slog.v(TAG, "Found preferred activity:"); 5470 if (ai != null) { 5471 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5472 } else { 5473 Slog.v(TAG, " null"); 5474 } 5475 } 5476 if (ai == null) { 5477 // This previously registered preferred activity 5478 // component is no longer known. Most likely an update 5479 // to the app was installed and in the new version this 5480 // component no longer exists. Clean it up by removing 5481 // it from the preferred activities list, and skip it. 5482 Slog.w(TAG, "Removing dangling preferred activity: " 5483 + pa.mPref.mComponent); 5484 pir.removeFilter(pa); 5485 changed = true; 5486 continue; 5487 } 5488 for (int j=0; j<N; j++) { 5489 final ResolveInfo ri = query.get(j); 5490 if (!ri.activityInfo.applicationInfo.packageName 5491 .equals(ai.applicationInfo.packageName)) { 5492 continue; 5493 } 5494 if (!ri.activityInfo.name.equals(ai.name)) { 5495 continue; 5496 } 5497 5498 if (removeMatches) { 5499 pir.removeFilter(pa); 5500 changed = true; 5501 if (DEBUG_PREFERRED) { 5502 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5503 } 5504 break; 5505 } 5506 5507 // Okay we found a previously set preferred or last chosen app. 5508 // If the result set is different from when this 5509 // was created, we need to clear it and re-ask the 5510 // user their preference, if we're looking for an "always" type entry. 5511 if (always && !pa.mPref.sameSet(query)) { 5512 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5513 + intent + " type " + resolvedType); 5514 if (DEBUG_PREFERRED) { 5515 Slog.v(TAG, "Removing preferred activity since set changed " 5516 + pa.mPref.mComponent); 5517 } 5518 pir.removeFilter(pa); 5519 // Re-add the filter as a "last chosen" entry (!always) 5520 PreferredActivity lastChosen = new PreferredActivity( 5521 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5522 pir.addFilter(lastChosen); 5523 changed = true; 5524 return null; 5525 } 5526 5527 // Yay! Either the set matched or we're looking for the last chosen 5528 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5529 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5530 return ri; 5531 } 5532 } 5533 } finally { 5534 if (changed) { 5535 if (DEBUG_PREFERRED) { 5536 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5537 } 5538 scheduleWritePackageRestrictionsLocked(userId); 5539 } 5540 } 5541 } 5542 } 5543 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5544 return null; 5545 } 5546 5547 /* 5548 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5549 */ 5550 @Override 5551 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5552 int targetUserId) { 5553 mContext.enforceCallingOrSelfPermission( 5554 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5555 List<CrossProfileIntentFilter> matches = 5556 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5557 if (matches != null) { 5558 int size = matches.size(); 5559 for (int i = 0; i < size; i++) { 5560 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5561 } 5562 } 5563 if (hasWebURI(intent)) { 5564 // cross-profile app linking works only towards the parent. 5565 final UserInfo parent = getProfileParent(sourceUserId); 5566 synchronized(mPackages) { 5567 int flags = updateFlagsForResolve(0, parent.id, intent); 5568 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5569 intent, resolvedType, flags, sourceUserId, parent.id); 5570 return xpDomainInfo != null; 5571 } 5572 } 5573 return false; 5574 } 5575 5576 private UserInfo getProfileParent(int userId) { 5577 final long identity = Binder.clearCallingIdentity(); 5578 try { 5579 return sUserManager.getProfileParent(userId); 5580 } finally { 5581 Binder.restoreCallingIdentity(identity); 5582 } 5583 } 5584 5585 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5586 String resolvedType, int userId) { 5587 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5588 if (resolver != null) { 5589 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5590 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5591 } 5592 return null; 5593 } 5594 5595 @Override 5596 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5597 String resolvedType, int flags, int userId) { 5598 try { 5599 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5600 5601 return new ParceledListSlice<>( 5602 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5603 } finally { 5604 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5605 } 5606 } 5607 5608 /** 5609 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5610 * ephemeral, returns {@code null}. 5611 */ 5612 private String getEphemeralPackageName(int callingUid) { 5613 final int appId = UserHandle.getAppId(callingUid); 5614 synchronized (mPackages) { 5615 final Object obj = mSettings.getUserIdLPr(appId); 5616 if (obj instanceof PackageSetting) { 5617 final PackageSetting ps = (PackageSetting) obj; 5618 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5619 } 5620 } 5621 return null; 5622 } 5623 5624 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5625 String resolvedType, int flags, int userId) { 5626 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5627 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5628 flags = updateFlagsForResolve(flags, userId, intent); 5629 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5630 false /* requireFullPermission */, false /* checkShell */, 5631 "query intent activities"); 5632 ComponentName comp = intent.getComponent(); 5633 if (comp == null) { 5634 if (intent.getSelector() != null) { 5635 intent = intent.getSelector(); 5636 comp = intent.getComponent(); 5637 } 5638 } 5639 5640 if (comp != null) { 5641 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5642 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5643 if (ai != null) { 5644 // When specifying an explicit component, we prevent the activity from being 5645 // used when either 1) the calling package is normal and the activity is within 5646 // an ephemeral application or 2) the calling package is ephemeral and the 5647 // activity is not visible to ephemeral applications. 5648 boolean matchEphemeral = 5649 (flags & PackageManager.MATCH_EPHEMERAL) != 0; 5650 boolean ephemeralVisibleOnly = 5651 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 5652 boolean blockResolution = 5653 (!matchEphemeral && ephemeralPkgName == null 5654 && (ai.applicationInfo.privateFlags 5655 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5656 || (ephemeralVisibleOnly && ephemeralPkgName != null 5657 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5658 if (!blockResolution) { 5659 final ResolveInfo ri = new ResolveInfo(); 5660 ri.activityInfo = ai; 5661 list.add(ri); 5662 } 5663 } 5664 return list; 5665 } 5666 5667 // reader 5668 boolean sortResult = false; 5669 boolean addEphemeral = false; 5670 List<ResolveInfo> result; 5671 final String pkgName = intent.getPackage(); 5672 synchronized (mPackages) { 5673 if (pkgName == null) { 5674 List<CrossProfileIntentFilter> matchingFilters = 5675 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5676 // Check for results that need to skip the current profile. 5677 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5678 resolvedType, flags, userId); 5679 if (xpResolveInfo != null) { 5680 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5681 xpResult.add(xpResolveInfo); 5682 return filterForEphemeral( 5683 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5684 } 5685 5686 // Check for results in the current profile. 5687 result = filterIfNotSystemUser(mActivities.queryIntent( 5688 intent, resolvedType, flags, userId), userId); 5689 addEphemeral = 5690 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5691 5692 // Check for cross profile results. 5693 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5694 xpResolveInfo = queryCrossProfileIntents( 5695 matchingFilters, intent, resolvedType, flags, userId, 5696 hasNonNegativePriorityResult); 5697 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5698 boolean isVisibleToUser = filterIfNotSystemUser( 5699 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5700 if (isVisibleToUser) { 5701 result.add(xpResolveInfo); 5702 sortResult = true; 5703 } 5704 } 5705 if (hasWebURI(intent)) { 5706 CrossProfileDomainInfo xpDomainInfo = null; 5707 final UserInfo parent = getProfileParent(userId); 5708 if (parent != null) { 5709 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5710 flags, userId, parent.id); 5711 } 5712 if (xpDomainInfo != null) { 5713 if (xpResolveInfo != null) { 5714 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5715 // in the result. 5716 result.remove(xpResolveInfo); 5717 } 5718 if (result.size() == 0 && !addEphemeral) { 5719 // No result in current profile, but found candidate in parent user. 5720 // And we are not going to add emphemeral app, so we can return the 5721 // result straight away. 5722 result.add(xpDomainInfo.resolveInfo); 5723 return filterForEphemeral(result, ephemeralPkgName); 5724 } 5725 } else if (result.size() <= 1 && !addEphemeral) { 5726 // No result in parent user and <= 1 result in current profile, and we 5727 // are not going to add emphemeral app, so we can return the result without 5728 // further processing. 5729 return filterForEphemeral(result, ephemeralPkgName); 5730 } 5731 // We have more than one candidate (combining results from current and parent 5732 // profile), so we need filtering and sorting. 5733 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5734 intent, flags, result, xpDomainInfo, userId); 5735 sortResult = true; 5736 } 5737 } else { 5738 final PackageParser.Package pkg = mPackages.get(pkgName); 5739 if (pkg != null) { 5740 result = filterForEphemeral(filterIfNotSystemUser( 5741 mActivities.queryIntentForPackage( 5742 intent, resolvedType, flags, pkg.activities, userId), 5743 userId), ephemeralPkgName); 5744 } else { 5745 // the caller wants to resolve for a particular package; however, there 5746 // were no installed results, so, try to find an ephemeral result 5747 addEphemeral = isEphemeralAllowed( 5748 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5749 result = new ArrayList<ResolveInfo>(); 5750 } 5751 } 5752 } 5753 if (addEphemeral) { 5754 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5755 final EphemeralRequest requestObject = new EphemeralRequest( 5756 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5757 null /*launchIntent*/, null /*callingPackage*/, userId); 5758 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5759 mContext, mEphemeralResolverConnection, requestObject); 5760 if (intentInfo != null) { 5761 if (DEBUG_EPHEMERAL) { 5762 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5763 } 5764 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5765 ephemeralInstaller.ephemeralResponse = intentInfo; 5766 // make sure this resolver is the default 5767 ephemeralInstaller.isDefault = true; 5768 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5769 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5770 // add a non-generic filter 5771 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5772 ephemeralInstaller.filter.addDataPath( 5773 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5774 result.add(ephemeralInstaller); 5775 } 5776 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5777 } 5778 if (sortResult) { 5779 Collections.sort(result, mResolvePrioritySorter); 5780 } 5781 return filterForEphemeral(result, ephemeralPkgName); 5782 } 5783 5784 private static class CrossProfileDomainInfo { 5785 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5786 ResolveInfo resolveInfo; 5787 /* Best domain verification status of the activities found in the other profile */ 5788 int bestDomainVerificationStatus; 5789 } 5790 5791 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5792 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5793 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5794 sourceUserId)) { 5795 return null; 5796 } 5797 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5798 resolvedType, flags, parentUserId); 5799 5800 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5801 return null; 5802 } 5803 CrossProfileDomainInfo result = null; 5804 int size = resultTargetUser.size(); 5805 for (int i = 0; i < size; i++) { 5806 ResolveInfo riTargetUser = resultTargetUser.get(i); 5807 // Intent filter verification is only for filters that specify a host. So don't return 5808 // those that handle all web uris. 5809 if (riTargetUser.handleAllWebDataURI) { 5810 continue; 5811 } 5812 String packageName = riTargetUser.activityInfo.packageName; 5813 PackageSetting ps = mSettings.mPackages.get(packageName); 5814 if (ps == null) { 5815 continue; 5816 } 5817 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5818 int status = (int)(verificationState >> 32); 5819 if (result == null) { 5820 result = new CrossProfileDomainInfo(); 5821 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5822 sourceUserId, parentUserId); 5823 result.bestDomainVerificationStatus = status; 5824 } else { 5825 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5826 result.bestDomainVerificationStatus); 5827 } 5828 } 5829 // Don't consider matches with status NEVER across profiles. 5830 if (result != null && result.bestDomainVerificationStatus 5831 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5832 return null; 5833 } 5834 return result; 5835 } 5836 5837 /** 5838 * Verification statuses are ordered from the worse to the best, except for 5839 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5840 */ 5841 private int bestDomainVerificationStatus(int status1, int status2) { 5842 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5843 return status2; 5844 } 5845 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5846 return status1; 5847 } 5848 return (int) MathUtils.max(status1, status2); 5849 } 5850 5851 private boolean isUserEnabled(int userId) { 5852 long callingId = Binder.clearCallingIdentity(); 5853 try { 5854 UserInfo userInfo = sUserManager.getUserInfo(userId); 5855 return userInfo != null && userInfo.isEnabled(); 5856 } finally { 5857 Binder.restoreCallingIdentity(callingId); 5858 } 5859 } 5860 5861 /** 5862 * Filter out activities with systemUserOnly flag set, when current user is not System. 5863 * 5864 * @return filtered list 5865 */ 5866 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5867 if (userId == UserHandle.USER_SYSTEM) { 5868 return resolveInfos; 5869 } 5870 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5871 ResolveInfo info = resolveInfos.get(i); 5872 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5873 resolveInfos.remove(i); 5874 } 5875 } 5876 return resolveInfos; 5877 } 5878 5879 /** 5880 * Filters out ephemeral activities. 5881 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 5882 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 5883 * 5884 * @param resolveInfos The pre-filtered list of resolved activities 5885 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 5886 * is performed. 5887 * @return A filtered list of resolved activities. 5888 */ 5889 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 5890 String ephemeralPkgName) { 5891 if (ephemeralPkgName == null) { 5892 return resolveInfos; 5893 } 5894 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5895 ResolveInfo info = resolveInfos.get(i); 5896 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 5897 // allow activities that are defined in the provided package 5898 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 5899 continue; 5900 } 5901 // allow activities that have been explicitly exposed to ephemeral apps 5902 if (!isEphemeralApp 5903 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 5904 continue; 5905 } 5906 resolveInfos.remove(i); 5907 } 5908 return resolveInfos; 5909 } 5910 5911 /** 5912 * @param resolveInfos list of resolve infos in descending priority order 5913 * @return if the list contains a resolve info with non-negative priority 5914 */ 5915 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5916 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5917 } 5918 5919 private static boolean hasWebURI(Intent intent) { 5920 if (intent.getData() == null) { 5921 return false; 5922 } 5923 final String scheme = intent.getScheme(); 5924 if (TextUtils.isEmpty(scheme)) { 5925 return false; 5926 } 5927 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5928 } 5929 5930 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5931 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5932 int userId) { 5933 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5934 5935 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5936 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5937 candidates.size()); 5938 } 5939 5940 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5941 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5942 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5943 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5944 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5945 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5946 5947 synchronized (mPackages) { 5948 final int count = candidates.size(); 5949 // First, try to use linked apps. Partition the candidates into four lists: 5950 // one for the final results, one for the "do not use ever", one for "undefined status" 5951 // and finally one for "browser app type". 5952 for (int n=0; n<count; n++) { 5953 ResolveInfo info = candidates.get(n); 5954 String packageName = info.activityInfo.packageName; 5955 PackageSetting ps = mSettings.mPackages.get(packageName); 5956 if (ps != null) { 5957 // Add to the special match all list (Browser use case) 5958 if (info.handleAllWebDataURI) { 5959 matchAllList.add(info); 5960 continue; 5961 } 5962 // Try to get the status from User settings first 5963 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5964 int status = (int)(packedStatus >> 32); 5965 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5966 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5967 if (DEBUG_DOMAIN_VERIFICATION || debug) { 5968 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5969 + " : linkgen=" + linkGeneration); 5970 } 5971 // Use link-enabled generation as preferredOrder, i.e. 5972 // prefer newly-enabled over earlier-enabled. 5973 info.preferredOrder = linkGeneration; 5974 alwaysList.add(info); 5975 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5976 if (DEBUG_DOMAIN_VERIFICATION || debug) { 5977 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5978 } 5979 neverList.add(info); 5980 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5981 if (DEBUG_DOMAIN_VERIFICATION || debug) { 5982 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5983 } 5984 alwaysAskList.add(info); 5985 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5986 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5987 if (DEBUG_DOMAIN_VERIFICATION || debug) { 5988 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5989 } 5990 undefinedList.add(info); 5991 } 5992 } 5993 } 5994 5995 // We'll want to include browser possibilities in a few cases 5996 boolean includeBrowser = false; 5997 5998 // First try to add the "always" resolution(s) for the current user, if any 5999 if (alwaysList.size() > 0) { 6000 result.addAll(alwaysList); 6001 } else { 6002 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6003 result.addAll(undefinedList); 6004 // Maybe add one for the other profile. 6005 if (xpDomainInfo != null && ( 6006 xpDomainInfo.bestDomainVerificationStatus 6007 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6008 result.add(xpDomainInfo.resolveInfo); 6009 } 6010 includeBrowser = true; 6011 } 6012 6013 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6014 // If there were 'always' entries their preferred order has been set, so we also 6015 // back that off to make the alternatives equivalent 6016 if (alwaysAskList.size() > 0) { 6017 for (ResolveInfo i : result) { 6018 i.preferredOrder = 0; 6019 } 6020 result.addAll(alwaysAskList); 6021 includeBrowser = true; 6022 } 6023 6024 if (includeBrowser) { 6025 // Also add browsers (all of them or only the default one) 6026 if (DEBUG_DOMAIN_VERIFICATION) { 6027 Slog.v(TAG, " ...including browsers in candidate set"); 6028 } 6029 if ((matchFlags & MATCH_ALL) != 0) { 6030 result.addAll(matchAllList); 6031 } else { 6032 // Browser/generic handling case. If there's a default browser, go straight 6033 // to that (but only if there is no other higher-priority match). 6034 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6035 int maxMatchPrio = 0; 6036 ResolveInfo defaultBrowserMatch = null; 6037 final int numCandidates = matchAllList.size(); 6038 for (int n = 0; n < numCandidates; n++) { 6039 ResolveInfo info = matchAllList.get(n); 6040 // track the highest overall match priority... 6041 if (info.priority > maxMatchPrio) { 6042 maxMatchPrio = info.priority; 6043 } 6044 // ...and the highest-priority default browser match 6045 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6046 if (defaultBrowserMatch == null 6047 || (defaultBrowserMatch.priority < info.priority)) { 6048 if (debug) { 6049 Slog.v(TAG, "Considering default browser match " + info); 6050 } 6051 defaultBrowserMatch = info; 6052 } 6053 } 6054 } 6055 if (defaultBrowserMatch != null 6056 && defaultBrowserMatch.priority >= maxMatchPrio 6057 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6058 { 6059 if (debug) { 6060 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6061 } 6062 result.add(defaultBrowserMatch); 6063 } else { 6064 result.addAll(matchAllList); 6065 } 6066 } 6067 6068 // If there is nothing selected, add all candidates and remove the ones that the user 6069 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6070 if (result.size() == 0) { 6071 result.addAll(candidates); 6072 result.removeAll(neverList); 6073 } 6074 } 6075 } 6076 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6077 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6078 result.size()); 6079 for (ResolveInfo info : result) { 6080 Slog.v(TAG, " + " + info.activityInfo); 6081 } 6082 } 6083 return result; 6084 } 6085 6086 // Returns a packed value as a long: 6087 // 6088 // high 'int'-sized word: link status: undefined/ask/never/always. 6089 // low 'int'-sized word: relative priority among 'always' results. 6090 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6091 long result = ps.getDomainVerificationStatusForUser(userId); 6092 // if none available, get the master status 6093 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6094 if (ps.getIntentFilterVerificationInfo() != null) { 6095 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6096 } 6097 } 6098 return result; 6099 } 6100 6101 private ResolveInfo querySkipCurrentProfileIntents( 6102 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6103 int flags, int sourceUserId) { 6104 if (matchingFilters != null) { 6105 int size = matchingFilters.size(); 6106 for (int i = 0; i < size; i ++) { 6107 CrossProfileIntentFilter filter = matchingFilters.get(i); 6108 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6109 // Checking if there are activities in the target user that can handle the 6110 // intent. 6111 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6112 resolvedType, flags, sourceUserId); 6113 if (resolveInfo != null) { 6114 return resolveInfo; 6115 } 6116 } 6117 } 6118 } 6119 return null; 6120 } 6121 6122 // Return matching ResolveInfo in target user if any. 6123 private ResolveInfo queryCrossProfileIntents( 6124 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6125 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6126 if (matchingFilters != null) { 6127 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6128 // match the same intent. For performance reasons, it is better not to 6129 // run queryIntent twice for the same userId 6130 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6131 int size = matchingFilters.size(); 6132 for (int i = 0; i < size; i++) { 6133 CrossProfileIntentFilter filter = matchingFilters.get(i); 6134 int targetUserId = filter.getTargetUserId(); 6135 boolean skipCurrentProfile = 6136 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6137 boolean skipCurrentProfileIfNoMatchFound = 6138 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6139 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6140 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6141 // Checking if there are activities in the target user that can handle the 6142 // intent. 6143 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6144 resolvedType, flags, sourceUserId); 6145 if (resolveInfo != null) return resolveInfo; 6146 alreadyTriedUserIds.put(targetUserId, true); 6147 } 6148 } 6149 } 6150 return null; 6151 } 6152 6153 /** 6154 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6155 * will forward the intent to the filter's target user. 6156 * Otherwise, returns null. 6157 */ 6158 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6159 String resolvedType, int flags, int sourceUserId) { 6160 int targetUserId = filter.getTargetUserId(); 6161 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6162 resolvedType, flags, targetUserId); 6163 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6164 // If all the matches in the target profile are suspended, return null. 6165 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6166 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6167 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6168 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6169 targetUserId); 6170 } 6171 } 6172 } 6173 return null; 6174 } 6175 6176 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6177 int sourceUserId, int targetUserId) { 6178 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6179 long ident = Binder.clearCallingIdentity(); 6180 boolean targetIsProfile; 6181 try { 6182 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6183 } finally { 6184 Binder.restoreCallingIdentity(ident); 6185 } 6186 String className; 6187 if (targetIsProfile) { 6188 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6189 } else { 6190 className = FORWARD_INTENT_TO_PARENT; 6191 } 6192 ComponentName forwardingActivityComponentName = new ComponentName( 6193 mAndroidApplication.packageName, className); 6194 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6195 sourceUserId); 6196 if (!targetIsProfile) { 6197 forwardingActivityInfo.showUserIcon = targetUserId; 6198 forwardingResolveInfo.noResourceId = true; 6199 } 6200 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6201 forwardingResolveInfo.priority = 0; 6202 forwardingResolveInfo.preferredOrder = 0; 6203 forwardingResolveInfo.match = 0; 6204 forwardingResolveInfo.isDefault = true; 6205 forwardingResolveInfo.filter = filter; 6206 forwardingResolveInfo.targetUserId = targetUserId; 6207 return forwardingResolveInfo; 6208 } 6209 6210 @Override 6211 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6212 Intent[] specifics, String[] specificTypes, Intent intent, 6213 String resolvedType, int flags, int userId) { 6214 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6215 specificTypes, intent, resolvedType, flags, userId)); 6216 } 6217 6218 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6219 Intent[] specifics, String[] specificTypes, Intent intent, 6220 String resolvedType, int flags, int userId) { 6221 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6222 flags = updateFlagsForResolve(flags, userId, intent); 6223 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6224 false /* requireFullPermission */, false /* checkShell */, 6225 "query intent activity options"); 6226 final String resultsAction = intent.getAction(); 6227 6228 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6229 | PackageManager.GET_RESOLVED_FILTER, userId); 6230 6231 if (DEBUG_INTENT_MATCHING) { 6232 Log.v(TAG, "Query " + intent + ": " + results); 6233 } 6234 6235 int specificsPos = 0; 6236 int N; 6237 6238 // todo: note that the algorithm used here is O(N^2). This 6239 // isn't a problem in our current environment, but if we start running 6240 // into situations where we have more than 5 or 10 matches then this 6241 // should probably be changed to something smarter... 6242 6243 // First we go through and resolve each of the specific items 6244 // that were supplied, taking care of removing any corresponding 6245 // duplicate items in the generic resolve list. 6246 if (specifics != null) { 6247 for (int i=0; i<specifics.length; i++) { 6248 final Intent sintent = specifics[i]; 6249 if (sintent == null) { 6250 continue; 6251 } 6252 6253 if (DEBUG_INTENT_MATCHING) { 6254 Log.v(TAG, "Specific #" + i + ": " + sintent); 6255 } 6256 6257 String action = sintent.getAction(); 6258 if (resultsAction != null && resultsAction.equals(action)) { 6259 // If this action was explicitly requested, then don't 6260 // remove things that have it. 6261 action = null; 6262 } 6263 6264 ResolveInfo ri = null; 6265 ActivityInfo ai = null; 6266 6267 ComponentName comp = sintent.getComponent(); 6268 if (comp == null) { 6269 ri = resolveIntent( 6270 sintent, 6271 specificTypes != null ? specificTypes[i] : null, 6272 flags, userId); 6273 if (ri == null) { 6274 continue; 6275 } 6276 if (ri == mResolveInfo) { 6277 // ACK! Must do something better with this. 6278 } 6279 ai = ri.activityInfo; 6280 comp = new ComponentName(ai.applicationInfo.packageName, 6281 ai.name); 6282 } else { 6283 ai = getActivityInfo(comp, flags, userId); 6284 if (ai == null) { 6285 continue; 6286 } 6287 } 6288 6289 // Look for any generic query activities that are duplicates 6290 // of this specific one, and remove them from the results. 6291 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6292 N = results.size(); 6293 int j; 6294 for (j=specificsPos; j<N; j++) { 6295 ResolveInfo sri = results.get(j); 6296 if ((sri.activityInfo.name.equals(comp.getClassName()) 6297 && sri.activityInfo.applicationInfo.packageName.equals( 6298 comp.getPackageName())) 6299 || (action != null && sri.filter.matchAction(action))) { 6300 results.remove(j); 6301 if (DEBUG_INTENT_MATCHING) Log.v( 6302 TAG, "Removing duplicate item from " + j 6303 + " due to specific " + specificsPos); 6304 if (ri == null) { 6305 ri = sri; 6306 } 6307 j--; 6308 N--; 6309 } 6310 } 6311 6312 // Add this specific item to its proper place. 6313 if (ri == null) { 6314 ri = new ResolveInfo(); 6315 ri.activityInfo = ai; 6316 } 6317 results.add(specificsPos, ri); 6318 ri.specificIndex = i; 6319 specificsPos++; 6320 } 6321 } 6322 6323 // Now we go through the remaining generic results and remove any 6324 // duplicate actions that are found here. 6325 N = results.size(); 6326 for (int i=specificsPos; i<N-1; i++) { 6327 final ResolveInfo rii = results.get(i); 6328 if (rii.filter == null) { 6329 continue; 6330 } 6331 6332 // Iterate over all of the actions of this result's intent 6333 // filter... typically this should be just one. 6334 final Iterator<String> it = rii.filter.actionsIterator(); 6335 if (it == null) { 6336 continue; 6337 } 6338 while (it.hasNext()) { 6339 final String action = it.next(); 6340 if (resultsAction != null && resultsAction.equals(action)) { 6341 // If this action was explicitly requested, then don't 6342 // remove things that have it. 6343 continue; 6344 } 6345 for (int j=i+1; j<N; j++) { 6346 final ResolveInfo rij = results.get(j); 6347 if (rij.filter != null && rij.filter.hasAction(action)) { 6348 results.remove(j); 6349 if (DEBUG_INTENT_MATCHING) Log.v( 6350 TAG, "Removing duplicate item from " + j 6351 + " due to action " + action + " at " + i); 6352 j--; 6353 N--; 6354 } 6355 } 6356 } 6357 6358 // If the caller didn't request filter information, drop it now 6359 // so we don't have to marshall/unmarshall it. 6360 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6361 rii.filter = null; 6362 } 6363 } 6364 6365 // Filter out the caller activity if so requested. 6366 if (caller != null) { 6367 N = results.size(); 6368 for (int i=0; i<N; i++) { 6369 ActivityInfo ainfo = results.get(i).activityInfo; 6370 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6371 && caller.getClassName().equals(ainfo.name)) { 6372 results.remove(i); 6373 break; 6374 } 6375 } 6376 } 6377 6378 // If the caller didn't request filter information, 6379 // drop them now so we don't have to 6380 // marshall/unmarshall it. 6381 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6382 N = results.size(); 6383 for (int i=0; i<N; i++) { 6384 results.get(i).filter = null; 6385 } 6386 } 6387 6388 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6389 return results; 6390 } 6391 6392 @Override 6393 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6394 String resolvedType, int flags, int userId) { 6395 return new ParceledListSlice<>( 6396 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6397 } 6398 6399 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6400 String resolvedType, int flags, int userId) { 6401 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6402 flags = updateFlagsForResolve(flags, userId, intent); 6403 ComponentName comp = intent.getComponent(); 6404 if (comp == null) { 6405 if (intent.getSelector() != null) { 6406 intent = intent.getSelector(); 6407 comp = intent.getComponent(); 6408 } 6409 } 6410 if (comp != null) { 6411 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6412 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6413 if (ai != null) { 6414 ResolveInfo ri = new ResolveInfo(); 6415 ri.activityInfo = ai; 6416 list.add(ri); 6417 } 6418 return list; 6419 } 6420 6421 // reader 6422 synchronized (mPackages) { 6423 String pkgName = intent.getPackage(); 6424 if (pkgName == null) { 6425 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6426 } 6427 final PackageParser.Package pkg = mPackages.get(pkgName); 6428 if (pkg != null) { 6429 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6430 userId); 6431 } 6432 return Collections.emptyList(); 6433 } 6434 } 6435 6436 @Override 6437 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6438 if (!sUserManager.exists(userId)) return null; 6439 flags = updateFlagsForResolve(flags, userId, intent); 6440 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6441 if (query != null) { 6442 if (query.size() >= 1) { 6443 // If there is more than one service with the same priority, 6444 // just arbitrarily pick the first one. 6445 return query.get(0); 6446 } 6447 } 6448 return null; 6449 } 6450 6451 @Override 6452 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6453 String resolvedType, int flags, int userId) { 6454 return new ParceledListSlice<>( 6455 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6456 } 6457 6458 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6459 String resolvedType, int flags, int userId) { 6460 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6461 flags = updateFlagsForResolve(flags, userId, intent); 6462 ComponentName comp = intent.getComponent(); 6463 if (comp == null) { 6464 if (intent.getSelector() != null) { 6465 intent = intent.getSelector(); 6466 comp = intent.getComponent(); 6467 } 6468 } 6469 if (comp != null) { 6470 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6471 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6472 if (si != null) { 6473 final ResolveInfo ri = new ResolveInfo(); 6474 ri.serviceInfo = si; 6475 list.add(ri); 6476 } 6477 return list; 6478 } 6479 6480 // reader 6481 synchronized (mPackages) { 6482 String pkgName = intent.getPackage(); 6483 if (pkgName == null) { 6484 return mServices.queryIntent(intent, resolvedType, flags, userId); 6485 } 6486 final PackageParser.Package pkg = mPackages.get(pkgName); 6487 if (pkg != null) { 6488 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6489 userId); 6490 } 6491 return Collections.emptyList(); 6492 } 6493 } 6494 6495 @Override 6496 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6497 String resolvedType, int flags, int userId) { 6498 return new ParceledListSlice<>( 6499 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6500 } 6501 6502 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6503 Intent intent, String resolvedType, int flags, int userId) { 6504 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6505 flags = updateFlagsForResolve(flags, userId, intent); 6506 ComponentName comp = intent.getComponent(); 6507 if (comp == null) { 6508 if (intent.getSelector() != null) { 6509 intent = intent.getSelector(); 6510 comp = intent.getComponent(); 6511 } 6512 } 6513 if (comp != null) { 6514 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6515 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6516 if (pi != null) { 6517 final ResolveInfo ri = new ResolveInfo(); 6518 ri.providerInfo = pi; 6519 list.add(ri); 6520 } 6521 return list; 6522 } 6523 6524 // reader 6525 synchronized (mPackages) { 6526 String pkgName = intent.getPackage(); 6527 if (pkgName == null) { 6528 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6529 } 6530 final PackageParser.Package pkg = mPackages.get(pkgName); 6531 if (pkg != null) { 6532 return mProviders.queryIntentForPackage( 6533 intent, resolvedType, flags, pkg.providers, userId); 6534 } 6535 return Collections.emptyList(); 6536 } 6537 } 6538 6539 @Override 6540 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6541 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6542 flags = updateFlagsForPackage(flags, userId, null); 6543 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6544 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6545 true /* requireFullPermission */, false /* checkShell */, 6546 "get installed packages"); 6547 6548 // writer 6549 synchronized (mPackages) { 6550 ArrayList<PackageInfo> list; 6551 if (listUninstalled) { 6552 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6553 for (PackageSetting ps : mSettings.mPackages.values()) { 6554 final PackageInfo pi; 6555 if (ps.pkg != null) { 6556 pi = generatePackageInfo(ps, flags, userId); 6557 } else { 6558 pi = generatePackageInfo(ps, flags, userId); 6559 } 6560 if (pi != null) { 6561 list.add(pi); 6562 } 6563 } 6564 } else { 6565 list = new ArrayList<PackageInfo>(mPackages.size()); 6566 for (PackageParser.Package p : mPackages.values()) { 6567 final PackageInfo pi = 6568 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6569 if (pi != null) { 6570 list.add(pi); 6571 } 6572 } 6573 } 6574 6575 return new ParceledListSlice<PackageInfo>(list); 6576 } 6577 } 6578 6579 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6580 String[] permissions, boolean[] tmp, int flags, int userId) { 6581 int numMatch = 0; 6582 final PermissionsState permissionsState = ps.getPermissionsState(); 6583 for (int i=0; i<permissions.length; i++) { 6584 final String permission = permissions[i]; 6585 if (permissionsState.hasPermission(permission, userId)) { 6586 tmp[i] = true; 6587 numMatch++; 6588 } else { 6589 tmp[i] = false; 6590 } 6591 } 6592 if (numMatch == 0) { 6593 return; 6594 } 6595 final PackageInfo pi; 6596 if (ps.pkg != null) { 6597 pi = generatePackageInfo(ps, flags, userId); 6598 } else { 6599 pi = generatePackageInfo(ps, flags, userId); 6600 } 6601 // The above might return null in cases of uninstalled apps or install-state 6602 // skew across users/profiles. 6603 if (pi != null) { 6604 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6605 if (numMatch == permissions.length) { 6606 pi.requestedPermissions = permissions; 6607 } else { 6608 pi.requestedPermissions = new String[numMatch]; 6609 numMatch = 0; 6610 for (int i=0; i<permissions.length; i++) { 6611 if (tmp[i]) { 6612 pi.requestedPermissions[numMatch] = permissions[i]; 6613 numMatch++; 6614 } 6615 } 6616 } 6617 } 6618 list.add(pi); 6619 } 6620 } 6621 6622 @Override 6623 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6624 String[] permissions, int flags, int userId) { 6625 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6626 flags = updateFlagsForPackage(flags, userId, permissions); 6627 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6628 true /* requireFullPermission */, false /* checkShell */, 6629 "get packages holding permissions"); 6630 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6631 6632 // writer 6633 synchronized (mPackages) { 6634 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6635 boolean[] tmpBools = new boolean[permissions.length]; 6636 if (listUninstalled) { 6637 for (PackageSetting ps : mSettings.mPackages.values()) { 6638 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6639 userId); 6640 } 6641 } else { 6642 for (PackageParser.Package pkg : mPackages.values()) { 6643 PackageSetting ps = (PackageSetting)pkg.mExtras; 6644 if (ps != null) { 6645 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6646 userId); 6647 } 6648 } 6649 } 6650 6651 return new ParceledListSlice<PackageInfo>(list); 6652 } 6653 } 6654 6655 @Override 6656 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6657 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6658 flags = updateFlagsForApplication(flags, userId, null); 6659 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6660 6661 // writer 6662 synchronized (mPackages) { 6663 ArrayList<ApplicationInfo> list; 6664 if (listUninstalled) { 6665 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6666 for (PackageSetting ps : mSettings.mPackages.values()) { 6667 ApplicationInfo ai; 6668 int effectiveFlags = flags; 6669 if (ps.isSystem()) { 6670 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6671 } 6672 if (ps.pkg != null) { 6673 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6674 ps.readUserState(userId), userId); 6675 } else { 6676 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6677 userId); 6678 } 6679 if (ai != null) { 6680 list.add(ai); 6681 } 6682 } 6683 } else { 6684 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6685 for (PackageParser.Package p : mPackages.values()) { 6686 if (p.mExtras != null) { 6687 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6688 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6689 if (ai != null) { 6690 list.add(ai); 6691 } 6692 } 6693 } 6694 } 6695 6696 return new ParceledListSlice<ApplicationInfo>(list); 6697 } 6698 } 6699 6700 @Override 6701 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6702 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6703 return null; 6704 } 6705 6706 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6707 "getEphemeralApplications"); 6708 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6709 true /* requireFullPermission */, false /* checkShell */, 6710 "getEphemeralApplications"); 6711 synchronized (mPackages) { 6712 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6713 .getEphemeralApplicationsLPw(userId); 6714 if (ephemeralApps != null) { 6715 return new ParceledListSlice<>(ephemeralApps); 6716 } 6717 } 6718 return null; 6719 } 6720 6721 @Override 6722 public boolean isEphemeralApplication(String packageName, int userId) { 6723 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6724 true /* requireFullPermission */, false /* checkShell */, 6725 "isEphemeral"); 6726 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6727 return false; 6728 } 6729 6730 if (!isCallerSameApp(packageName)) { 6731 return false; 6732 } 6733 synchronized (mPackages) { 6734 PackageParser.Package pkg = mPackages.get(packageName); 6735 if (pkg != null) { 6736 return pkg.applicationInfo.isEphemeralApp(); 6737 } 6738 } 6739 return false; 6740 } 6741 6742 @Override 6743 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6744 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6745 return null; 6746 } 6747 6748 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6749 true /* requireFullPermission */, false /* checkShell */, 6750 "getCookie"); 6751 if (!isCallerSameApp(packageName)) { 6752 return null; 6753 } 6754 synchronized (mPackages) { 6755 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6756 packageName, userId); 6757 } 6758 } 6759 6760 @Override 6761 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6762 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6763 return true; 6764 } 6765 6766 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6767 true /* requireFullPermission */, true /* checkShell */, 6768 "setCookie"); 6769 if (!isCallerSameApp(packageName)) { 6770 return false; 6771 } 6772 synchronized (mPackages) { 6773 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6774 packageName, cookie, userId); 6775 } 6776 } 6777 6778 @Override 6779 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6780 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6781 return null; 6782 } 6783 6784 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6785 "getEphemeralApplicationIcon"); 6786 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6787 true /* requireFullPermission */, false /* checkShell */, 6788 "getEphemeralApplicationIcon"); 6789 synchronized (mPackages) { 6790 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6791 packageName, userId); 6792 } 6793 } 6794 6795 private boolean isCallerSameApp(String packageName) { 6796 PackageParser.Package pkg = mPackages.get(packageName); 6797 return pkg != null 6798 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6799 } 6800 6801 @Override 6802 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6803 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6804 } 6805 6806 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6807 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6808 6809 // reader 6810 synchronized (mPackages) { 6811 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6812 final int userId = UserHandle.getCallingUserId(); 6813 while (i.hasNext()) { 6814 final PackageParser.Package p = i.next(); 6815 if (p.applicationInfo == null) continue; 6816 6817 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6818 && !p.applicationInfo.isDirectBootAware(); 6819 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6820 && p.applicationInfo.isDirectBootAware(); 6821 6822 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6823 && (!mSafeMode || isSystemApp(p)) 6824 && (matchesUnaware || matchesAware)) { 6825 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6826 if (ps != null) { 6827 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6828 ps.readUserState(userId), userId); 6829 if (ai != null) { 6830 finalList.add(ai); 6831 } 6832 } 6833 } 6834 } 6835 } 6836 6837 return finalList; 6838 } 6839 6840 @Override 6841 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6842 if (!sUserManager.exists(userId)) return null; 6843 flags = updateFlagsForComponent(flags, userId, name); 6844 // reader 6845 synchronized (mPackages) { 6846 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6847 PackageSetting ps = provider != null 6848 ? mSettings.mPackages.get(provider.owner.packageName) 6849 : null; 6850 return ps != null 6851 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6852 ? PackageParser.generateProviderInfo(provider, flags, 6853 ps.readUserState(userId), userId) 6854 : null; 6855 } 6856 } 6857 6858 /** 6859 * @deprecated 6860 */ 6861 @Deprecated 6862 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6863 // reader 6864 synchronized (mPackages) { 6865 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6866 .entrySet().iterator(); 6867 final int userId = UserHandle.getCallingUserId(); 6868 while (i.hasNext()) { 6869 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6870 PackageParser.Provider p = entry.getValue(); 6871 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6872 6873 if (ps != null && p.syncable 6874 && (!mSafeMode || (p.info.applicationInfo.flags 6875 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6876 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6877 ps.readUserState(userId), userId); 6878 if (info != null) { 6879 outNames.add(entry.getKey()); 6880 outInfo.add(info); 6881 } 6882 } 6883 } 6884 } 6885 } 6886 6887 @Override 6888 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6889 int uid, int flags) { 6890 final int userId = processName != null ? UserHandle.getUserId(uid) 6891 : UserHandle.getCallingUserId(); 6892 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6893 flags = updateFlagsForComponent(flags, userId, processName); 6894 6895 ArrayList<ProviderInfo> finalList = null; 6896 // reader 6897 synchronized (mPackages) { 6898 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6899 while (i.hasNext()) { 6900 final PackageParser.Provider p = i.next(); 6901 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6902 if (ps != null && p.info.authority != null 6903 && (processName == null 6904 || (p.info.processName.equals(processName) 6905 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6906 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6907 if (finalList == null) { 6908 finalList = new ArrayList<ProviderInfo>(3); 6909 } 6910 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6911 ps.readUserState(userId), userId); 6912 if (info != null) { 6913 finalList.add(info); 6914 } 6915 } 6916 } 6917 } 6918 6919 if (finalList != null) { 6920 Collections.sort(finalList, mProviderInitOrderSorter); 6921 return new ParceledListSlice<ProviderInfo>(finalList); 6922 } 6923 6924 return ParceledListSlice.emptyList(); 6925 } 6926 6927 @Override 6928 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6929 // reader 6930 synchronized (mPackages) { 6931 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6932 return PackageParser.generateInstrumentationInfo(i, flags); 6933 } 6934 } 6935 6936 @Override 6937 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6938 String targetPackage, int flags) { 6939 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6940 } 6941 6942 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6943 int flags) { 6944 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6945 6946 // reader 6947 synchronized (mPackages) { 6948 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6949 while (i.hasNext()) { 6950 final PackageParser.Instrumentation p = i.next(); 6951 if (targetPackage == null 6952 || targetPackage.equals(p.info.targetPackage)) { 6953 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6954 flags); 6955 if (ii != null) { 6956 finalList.add(ii); 6957 } 6958 } 6959 } 6960 } 6961 6962 return finalList; 6963 } 6964 6965 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6966 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6967 if (overlays == null) { 6968 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6969 return; 6970 } 6971 for (PackageParser.Package opkg : overlays.values()) { 6972 // Not much to do if idmap fails: we already logged the error 6973 // and we certainly don't want to abort installation of pkg simply 6974 // because an overlay didn't fit properly. For these reasons, 6975 // ignore the return value of createIdmapForPackagePairLI. 6976 createIdmapForPackagePairLI(pkg, opkg); 6977 } 6978 } 6979 6980 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6981 PackageParser.Package opkg) { 6982 if (!opkg.mTrustedOverlay) { 6983 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6984 opkg.baseCodePath + ": overlay not trusted"); 6985 return false; 6986 } 6987 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6988 if (overlaySet == null) { 6989 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6990 opkg.baseCodePath + " but target package has no known overlays"); 6991 return false; 6992 } 6993 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6994 // TODO: generate idmap for split APKs 6995 try { 6996 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6997 } catch (InstallerException e) { 6998 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6999 + opkg.baseCodePath); 7000 return false; 7001 } 7002 PackageParser.Package[] overlayArray = 7003 overlaySet.values().toArray(new PackageParser.Package[0]); 7004 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7005 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7006 return p1.mOverlayPriority - p2.mOverlayPriority; 7007 } 7008 }; 7009 Arrays.sort(overlayArray, cmp); 7010 7011 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7012 int i = 0; 7013 for (PackageParser.Package p : overlayArray) { 7014 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7015 } 7016 return true; 7017 } 7018 7019 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7020 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7021 try { 7022 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7023 } finally { 7024 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7025 } 7026 } 7027 7028 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7029 final File[] files = dir.listFiles(); 7030 if (ArrayUtils.isEmpty(files)) { 7031 Log.d(TAG, "No files in app dir " + dir); 7032 return; 7033 } 7034 7035 if (DEBUG_PACKAGE_SCANNING) { 7036 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7037 + " flags=0x" + Integer.toHexString(parseFlags)); 7038 } 7039 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7040 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7041 7042 // Submit files for parsing in parallel 7043 int fileCount = 0; 7044 for (File file : files) { 7045 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7046 && !PackageInstallerService.isStageName(file.getName()); 7047 if (!isPackage) { 7048 // Ignore entries which are not packages 7049 continue; 7050 } 7051 parallelPackageParser.submit(file, parseFlags); 7052 fileCount++; 7053 } 7054 7055 // Process results one by one 7056 for (; fileCount > 0; fileCount--) { 7057 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7058 Throwable throwable = parseResult.throwable; 7059 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7060 7061 if (throwable == null) { 7062 try { 7063 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7064 currentTime, null); 7065 } catch (PackageManagerException e) { 7066 errorCode = e.error; 7067 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7068 } 7069 } else if (throwable instanceof PackageParser.PackageParserException) { 7070 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7071 throwable; 7072 errorCode = e.error; 7073 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7074 } else { 7075 throw new IllegalStateException("Unexpected exception occurred while parsing " 7076 + parseResult.scanFile, throwable); 7077 } 7078 7079 // Delete invalid userdata apps 7080 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7081 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7082 logCriticalInfo(Log.WARN, 7083 "Deleting invalid package at " + parseResult.scanFile); 7084 removeCodePathLI(parseResult.scanFile); 7085 } 7086 } 7087 parallelPackageParser.close(); 7088 } 7089 7090 private static File getSettingsProblemFile() { 7091 File dataDir = Environment.getDataDirectory(); 7092 File systemDir = new File(dataDir, "system"); 7093 File fname = new File(systemDir, "uiderrors.txt"); 7094 return fname; 7095 } 7096 7097 static void reportSettingsProblem(int priority, String msg) { 7098 logCriticalInfo(priority, msg); 7099 } 7100 7101 static void logCriticalInfo(int priority, String msg) { 7102 Slog.println(priority, TAG, msg); 7103 EventLogTags.writePmCriticalInfo(msg); 7104 try { 7105 File fname = getSettingsProblemFile(); 7106 FileOutputStream out = new FileOutputStream(fname, true); 7107 PrintWriter pw = new FastPrintWriter(out); 7108 SimpleDateFormat formatter = new SimpleDateFormat(); 7109 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7110 pw.println(dateString + ": " + msg); 7111 pw.close(); 7112 FileUtils.setPermissions( 7113 fname.toString(), 7114 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7115 -1, -1); 7116 } catch (java.io.IOException e) { 7117 } 7118 } 7119 7120 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7121 if (srcFile.isDirectory()) { 7122 final File baseFile = new File(pkg.baseCodePath); 7123 long maxModifiedTime = baseFile.lastModified(); 7124 if (pkg.splitCodePaths != null) { 7125 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7126 final File splitFile = new File(pkg.splitCodePaths[i]); 7127 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7128 } 7129 } 7130 return maxModifiedTime; 7131 } 7132 return srcFile.lastModified(); 7133 } 7134 7135 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7136 final int policyFlags) throws PackageManagerException { 7137 // When upgrading from pre-N MR1, verify the package time stamp using the package 7138 // directory and not the APK file. 7139 final long lastModifiedTime = mIsPreNMR1Upgrade 7140 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7141 if (ps != null 7142 && ps.codePath.equals(srcFile) 7143 && ps.timeStamp == lastModifiedTime 7144 && !isCompatSignatureUpdateNeeded(pkg) 7145 && !isRecoverSignatureUpdateNeeded(pkg)) { 7146 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7147 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7148 ArraySet<PublicKey> signingKs; 7149 synchronized (mPackages) { 7150 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7151 } 7152 if (ps.signatures.mSignatures != null 7153 && ps.signatures.mSignatures.length != 0 7154 && signingKs != null) { 7155 // Optimization: reuse the existing cached certificates 7156 // if the package appears to be unchanged. 7157 pkg.mSignatures = ps.signatures.mSignatures; 7158 pkg.mSigningKeys = signingKs; 7159 return; 7160 } 7161 7162 Slog.w(TAG, "PackageSetting for " + ps.name 7163 + " is missing signatures. Collecting certs again to recover them."); 7164 } else { 7165 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7166 } 7167 7168 try { 7169 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7170 PackageParser.collectCertificates(pkg, policyFlags); 7171 } catch (PackageParserException e) { 7172 throw PackageManagerException.from(e); 7173 } finally { 7174 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7175 } 7176 } 7177 7178 /** 7179 * Traces a package scan. 7180 * @see #scanPackageLI(File, int, int, long, UserHandle) 7181 */ 7182 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7183 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7184 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7185 try { 7186 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7187 } finally { 7188 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7189 } 7190 } 7191 7192 /** 7193 * Scans a package and returns the newly parsed package. 7194 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7195 */ 7196 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7197 long currentTime, UserHandle user) throws PackageManagerException { 7198 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7199 PackageParser pp = new PackageParser(); 7200 pp.setSeparateProcesses(mSeparateProcesses); 7201 pp.setOnlyCoreApps(mOnlyCore); 7202 pp.setDisplayMetrics(mMetrics); 7203 7204 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7205 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7206 } 7207 7208 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7209 final PackageParser.Package pkg; 7210 try { 7211 pkg = pp.parsePackage(scanFile, parseFlags); 7212 } catch (PackageParserException e) { 7213 throw PackageManagerException.from(e); 7214 } finally { 7215 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7216 } 7217 7218 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7219 } 7220 7221 /** 7222 * Scans a package and returns the newly parsed package. 7223 * @throws PackageManagerException on a parse error. 7224 */ 7225 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7226 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7227 throws PackageManagerException { 7228 // If the package has children and this is the first dive in the function 7229 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7230 // packages (parent and children) would be successfully scanned before the 7231 // actual scan since scanning mutates internal state and we want to atomically 7232 // install the package and its children. 7233 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7234 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7235 scanFlags |= SCAN_CHECK_ONLY; 7236 } 7237 } else { 7238 scanFlags &= ~SCAN_CHECK_ONLY; 7239 } 7240 7241 // Scan the parent 7242 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7243 scanFlags, currentTime, user); 7244 7245 // Scan the children 7246 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7247 for (int i = 0; i < childCount; i++) { 7248 PackageParser.Package childPackage = pkg.childPackages.get(i); 7249 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7250 currentTime, user); 7251 } 7252 7253 7254 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7255 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7256 } 7257 7258 return scannedPkg; 7259 } 7260 7261 /** 7262 * Scans a package and returns the newly parsed package. 7263 * @throws PackageManagerException on a parse error. 7264 */ 7265 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7266 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7267 throws PackageManagerException { 7268 PackageSetting ps = null; 7269 PackageSetting updatedPkg; 7270 // reader 7271 synchronized (mPackages) { 7272 // Look to see if we already know about this package. 7273 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7274 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7275 // This package has been renamed to its original name. Let's 7276 // use that. 7277 ps = mSettings.getPackageLPr(oldName); 7278 } 7279 // If there was no original package, see one for the real package name. 7280 if (ps == null) { 7281 ps = mSettings.getPackageLPr(pkg.packageName); 7282 } 7283 // Check to see if this package could be hiding/updating a system 7284 // package. Must look for it either under the original or real 7285 // package name depending on our state. 7286 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7287 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7288 7289 // If this is a package we don't know about on the system partition, we 7290 // may need to remove disabled child packages on the system partition 7291 // or may need to not add child packages if the parent apk is updated 7292 // on the data partition and no longer defines this child package. 7293 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7294 // If this is a parent package for an updated system app and this system 7295 // app got an OTA update which no longer defines some of the child packages 7296 // we have to prune them from the disabled system packages. 7297 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7298 if (disabledPs != null) { 7299 final int scannedChildCount = (pkg.childPackages != null) 7300 ? pkg.childPackages.size() : 0; 7301 final int disabledChildCount = disabledPs.childPackageNames != null 7302 ? disabledPs.childPackageNames.size() : 0; 7303 for (int i = 0; i < disabledChildCount; i++) { 7304 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7305 boolean disabledPackageAvailable = false; 7306 for (int j = 0; j < scannedChildCount; j++) { 7307 PackageParser.Package childPkg = pkg.childPackages.get(j); 7308 if (childPkg.packageName.equals(disabledChildPackageName)) { 7309 disabledPackageAvailable = true; 7310 break; 7311 } 7312 } 7313 if (!disabledPackageAvailable) { 7314 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7315 } 7316 } 7317 } 7318 } 7319 } 7320 7321 boolean updatedPkgBetter = false; 7322 // First check if this is a system package that may involve an update 7323 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7324 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7325 // it needs to drop FLAG_PRIVILEGED. 7326 if (locationIsPrivileged(scanFile)) { 7327 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7328 } else { 7329 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7330 } 7331 7332 if (ps != null && !ps.codePath.equals(scanFile)) { 7333 // The path has changed from what was last scanned... check the 7334 // version of the new path against what we have stored to determine 7335 // what to do. 7336 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7337 if (pkg.mVersionCode <= ps.versionCode) { 7338 // The system package has been updated and the code path does not match 7339 // Ignore entry. Skip it. 7340 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7341 + " ignored: updated version " + ps.versionCode 7342 + " better than this " + pkg.mVersionCode); 7343 if (!updatedPkg.codePath.equals(scanFile)) { 7344 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7345 + ps.name + " changing from " + updatedPkg.codePathString 7346 + " to " + scanFile); 7347 updatedPkg.codePath = scanFile; 7348 updatedPkg.codePathString = scanFile.toString(); 7349 updatedPkg.resourcePath = scanFile; 7350 updatedPkg.resourcePathString = scanFile.toString(); 7351 } 7352 updatedPkg.pkg = pkg; 7353 updatedPkg.versionCode = pkg.mVersionCode; 7354 7355 // Update the disabled system child packages to point to the package too. 7356 final int childCount = updatedPkg.childPackageNames != null 7357 ? updatedPkg.childPackageNames.size() : 0; 7358 for (int i = 0; i < childCount; i++) { 7359 String childPackageName = updatedPkg.childPackageNames.get(i); 7360 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7361 childPackageName); 7362 if (updatedChildPkg != null) { 7363 updatedChildPkg.pkg = pkg; 7364 updatedChildPkg.versionCode = pkg.mVersionCode; 7365 } 7366 } 7367 7368 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7369 + scanFile + " ignored: updated version " + ps.versionCode 7370 + " better than this " + pkg.mVersionCode); 7371 } else { 7372 // The current app on the system partition is better than 7373 // what we have updated to on the data partition; switch 7374 // back to the system partition version. 7375 // At this point, its safely assumed that package installation for 7376 // apps in system partition will go through. If not there won't be a working 7377 // version of the app 7378 // writer 7379 synchronized (mPackages) { 7380 // Just remove the loaded entries from package lists. 7381 mPackages.remove(ps.name); 7382 } 7383 7384 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7385 + " reverting from " + ps.codePathString 7386 + ": new version " + pkg.mVersionCode 7387 + " better than installed " + ps.versionCode); 7388 7389 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7390 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7391 synchronized (mInstallLock) { 7392 args.cleanUpResourcesLI(); 7393 } 7394 synchronized (mPackages) { 7395 mSettings.enableSystemPackageLPw(ps.name); 7396 } 7397 updatedPkgBetter = true; 7398 } 7399 } 7400 } 7401 7402 if (updatedPkg != null) { 7403 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7404 // initially 7405 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7406 7407 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7408 // flag set initially 7409 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7410 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7411 } 7412 } 7413 7414 // Verify certificates against what was last scanned 7415 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7416 7417 /* 7418 * A new system app appeared, but we already had a non-system one of the 7419 * same name installed earlier. 7420 */ 7421 boolean shouldHideSystemApp = false; 7422 if (updatedPkg == null && ps != null 7423 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7424 /* 7425 * Check to make sure the signatures match first. If they don't, 7426 * wipe the installed application and its data. 7427 */ 7428 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7429 != PackageManager.SIGNATURE_MATCH) { 7430 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7431 + " signatures don't match existing userdata copy; removing"); 7432 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7433 "scanPackageInternalLI")) { 7434 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7435 } 7436 ps = null; 7437 } else { 7438 /* 7439 * If the newly-added system app is an older version than the 7440 * already installed version, hide it. It will be scanned later 7441 * and re-added like an update. 7442 */ 7443 if (pkg.mVersionCode <= ps.versionCode) { 7444 shouldHideSystemApp = true; 7445 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7446 + " but new version " + pkg.mVersionCode + " better than installed " 7447 + ps.versionCode + "; hiding system"); 7448 } else { 7449 /* 7450 * The newly found system app is a newer version that the 7451 * one previously installed. Simply remove the 7452 * already-installed application and replace it with our own 7453 * while keeping the application data. 7454 */ 7455 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7456 + " reverting from " + ps.codePathString + ": new version " 7457 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7458 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7459 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7460 synchronized (mInstallLock) { 7461 args.cleanUpResourcesLI(); 7462 } 7463 } 7464 } 7465 } 7466 7467 // The apk is forward locked (not public) if its code and resources 7468 // are kept in different files. (except for app in either system or 7469 // vendor path). 7470 // TODO grab this value from PackageSettings 7471 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7472 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7473 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7474 } 7475 } 7476 7477 // TODO: extend to support forward-locked splits 7478 String resourcePath = null; 7479 String baseResourcePath = null; 7480 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7481 if (ps != null && ps.resourcePathString != null) { 7482 resourcePath = ps.resourcePathString; 7483 baseResourcePath = ps.resourcePathString; 7484 } else { 7485 // Should not happen at all. Just log an error. 7486 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7487 } 7488 } else { 7489 resourcePath = pkg.codePath; 7490 baseResourcePath = pkg.baseCodePath; 7491 } 7492 7493 // Set application objects path explicitly. 7494 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7495 pkg.setApplicationInfoCodePath(pkg.codePath); 7496 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7497 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7498 pkg.setApplicationInfoResourcePath(resourcePath); 7499 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7500 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7501 7502 // Note that we invoke the following method only if we are about to unpack an application 7503 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7504 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7505 7506 /* 7507 * If the system app should be overridden by a previously installed 7508 * data, hide the system app now and let the /data/app scan pick it up 7509 * again. 7510 */ 7511 if (shouldHideSystemApp) { 7512 synchronized (mPackages) { 7513 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7514 } 7515 } 7516 7517 return scannedPkg; 7518 } 7519 7520 private static String fixProcessName(String defProcessName, 7521 String processName) { 7522 if (processName == null) { 7523 return defProcessName; 7524 } 7525 return processName; 7526 } 7527 7528 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7529 throws PackageManagerException { 7530 if (pkgSetting.signatures.mSignatures != null) { 7531 // Already existing package. Make sure signatures match 7532 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7533 == PackageManager.SIGNATURE_MATCH; 7534 if (!match) { 7535 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7536 == PackageManager.SIGNATURE_MATCH; 7537 } 7538 if (!match) { 7539 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7540 == PackageManager.SIGNATURE_MATCH; 7541 } 7542 if (!match) { 7543 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7544 + pkg.packageName + " signatures do not match the " 7545 + "previously installed version; ignoring!"); 7546 } 7547 } 7548 7549 // Check for shared user signatures 7550 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7551 // Already existing package. Make sure signatures match 7552 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7553 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7554 if (!match) { 7555 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7556 == PackageManager.SIGNATURE_MATCH; 7557 } 7558 if (!match) { 7559 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7560 == PackageManager.SIGNATURE_MATCH; 7561 } 7562 if (!match) { 7563 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7564 "Package " + pkg.packageName 7565 + " has no signatures that match those in shared user " 7566 + pkgSetting.sharedUser.name + "; ignoring!"); 7567 } 7568 } 7569 } 7570 7571 /** 7572 * Enforces that only the system UID or root's UID can call a method exposed 7573 * via Binder. 7574 * 7575 * @param message used as message if SecurityException is thrown 7576 * @throws SecurityException if the caller is not system or root 7577 */ 7578 private static final void enforceSystemOrRoot(String message) { 7579 final int uid = Binder.getCallingUid(); 7580 if (uid != Process.SYSTEM_UID && uid != 0) { 7581 throw new SecurityException(message); 7582 } 7583 } 7584 7585 @Override 7586 public void performFstrimIfNeeded() { 7587 enforceSystemOrRoot("Only the system can request fstrim"); 7588 7589 // Before everything else, see whether we need to fstrim. 7590 try { 7591 IStorageManager sm = PackageHelper.getStorageManager(); 7592 if (sm != null) { 7593 boolean doTrim = false; 7594 final long interval = android.provider.Settings.Global.getLong( 7595 mContext.getContentResolver(), 7596 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7597 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7598 if (interval > 0) { 7599 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7600 if (timeSinceLast > interval) { 7601 doTrim = true; 7602 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7603 + "; running immediately"); 7604 } 7605 } 7606 if (doTrim) { 7607 final boolean dexOptDialogShown; 7608 synchronized (mPackages) { 7609 dexOptDialogShown = mDexOptDialogShown; 7610 } 7611 if (!isFirstBoot() && dexOptDialogShown) { 7612 try { 7613 ActivityManager.getService().showBootMessage( 7614 mContext.getResources().getString( 7615 R.string.android_upgrading_fstrim), true); 7616 } catch (RemoteException e) { 7617 } 7618 } 7619 sm.runMaintenance(); 7620 } 7621 } else { 7622 Slog.e(TAG, "storageManager service unavailable!"); 7623 } 7624 } catch (RemoteException e) { 7625 // Can't happen; StorageManagerService is local 7626 } 7627 } 7628 7629 @Override 7630 public void updatePackagesIfNeeded() { 7631 enforceSystemOrRoot("Only the system can request package update"); 7632 7633 // We need to re-extract after an OTA. 7634 boolean causeUpgrade = isUpgrade(); 7635 7636 // First boot or factory reset. 7637 // Note: we also handle devices that are upgrading to N right now as if it is their 7638 // first boot, as they do not have profile data. 7639 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7640 7641 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7642 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7643 7644 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7645 return; 7646 } 7647 7648 List<PackageParser.Package> pkgs; 7649 synchronized (mPackages) { 7650 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7651 } 7652 7653 final long startTime = System.nanoTime(); 7654 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7655 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7656 7657 final int elapsedTimeSeconds = 7658 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7659 7660 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7661 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7662 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7663 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7664 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7665 } 7666 7667 /** 7668 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7669 * containing statistics about the invocation. The array consists of three elements, 7670 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7671 * and {@code numberOfPackagesFailed}. 7672 */ 7673 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7674 String compilerFilter) { 7675 7676 int numberOfPackagesVisited = 0; 7677 int numberOfPackagesOptimized = 0; 7678 int numberOfPackagesSkipped = 0; 7679 int numberOfPackagesFailed = 0; 7680 final int numberOfPackagesToDexopt = pkgs.size(); 7681 7682 for (PackageParser.Package pkg : pkgs) { 7683 numberOfPackagesVisited++; 7684 7685 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7686 if (DEBUG_DEXOPT) { 7687 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7688 } 7689 numberOfPackagesSkipped++; 7690 continue; 7691 } 7692 7693 if (DEBUG_DEXOPT) { 7694 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7695 numberOfPackagesToDexopt + ": " + pkg.packageName); 7696 } 7697 7698 if (showDialog) { 7699 try { 7700 ActivityManager.getService().showBootMessage( 7701 mContext.getResources().getString(R.string.android_upgrading_apk, 7702 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7703 } catch (RemoteException e) { 7704 } 7705 synchronized (mPackages) { 7706 mDexOptDialogShown = true; 7707 } 7708 } 7709 7710 // If the OTA updates a system app which was previously preopted to a non-preopted state 7711 // the app might end up being verified at runtime. That's because by default the apps 7712 // are verify-profile but for preopted apps there's no profile. 7713 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7714 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7715 // filter (by default interpret-only). 7716 // Note that at this stage unused apps are already filtered. 7717 if (isSystemApp(pkg) && 7718 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7719 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7720 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7721 } 7722 7723 // checkProfiles is false to avoid merging profiles during boot which 7724 // might interfere with background compilation (b/28612421). 7725 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7726 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7727 // trade-off worth doing to save boot time work. 7728 int dexOptStatus = performDexOptTraced(pkg.packageName, 7729 false /* checkProfiles */, 7730 compilerFilter, 7731 false /* force */); 7732 switch (dexOptStatus) { 7733 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7734 numberOfPackagesOptimized++; 7735 break; 7736 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7737 numberOfPackagesSkipped++; 7738 break; 7739 case PackageDexOptimizer.DEX_OPT_FAILED: 7740 numberOfPackagesFailed++; 7741 break; 7742 default: 7743 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7744 break; 7745 } 7746 } 7747 7748 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7749 numberOfPackagesFailed }; 7750 } 7751 7752 @Override 7753 public void notifyPackageUse(String packageName, int reason) { 7754 synchronized (mPackages) { 7755 PackageParser.Package p = mPackages.get(packageName); 7756 if (p == null) { 7757 return; 7758 } 7759 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7760 } 7761 } 7762 7763 @Override 7764 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7765 int userId = UserHandle.getCallingUserId(); 7766 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7767 if (ai == null) { 7768 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7769 + loadingPackageName + ", user=" + userId); 7770 return; 7771 } 7772 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7773 } 7774 7775 // TODO: this is not used nor needed. Delete it. 7776 @Override 7777 public boolean performDexOptIfNeeded(String packageName) { 7778 int dexOptStatus = performDexOptTraced(packageName, 7779 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7780 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7781 } 7782 7783 @Override 7784 public boolean performDexOpt(String packageName, 7785 boolean checkProfiles, int compileReason, boolean force) { 7786 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7787 getCompilerFilterForReason(compileReason), force); 7788 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7789 } 7790 7791 @Override 7792 public boolean performDexOptMode(String packageName, 7793 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7794 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7795 targetCompilerFilter, force); 7796 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7797 } 7798 7799 private int performDexOptTraced(String packageName, 7800 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7801 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7802 try { 7803 return performDexOptInternal(packageName, checkProfiles, 7804 targetCompilerFilter, force); 7805 } finally { 7806 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7807 } 7808 } 7809 7810 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7811 // if the package can now be considered up to date for the given filter. 7812 private int performDexOptInternal(String packageName, 7813 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7814 PackageParser.Package p; 7815 synchronized (mPackages) { 7816 p = mPackages.get(packageName); 7817 if (p == null) { 7818 // Package could not be found. Report failure. 7819 return PackageDexOptimizer.DEX_OPT_FAILED; 7820 } 7821 mPackageUsage.maybeWriteAsync(mPackages); 7822 mCompilerStats.maybeWriteAsync(); 7823 } 7824 long callingId = Binder.clearCallingIdentity(); 7825 try { 7826 synchronized (mInstallLock) { 7827 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7828 targetCompilerFilter, force); 7829 } 7830 } finally { 7831 Binder.restoreCallingIdentity(callingId); 7832 } 7833 } 7834 7835 public ArraySet<String> getOptimizablePackages() { 7836 ArraySet<String> pkgs = new ArraySet<String>(); 7837 synchronized (mPackages) { 7838 for (PackageParser.Package p : mPackages.values()) { 7839 if (PackageDexOptimizer.canOptimizePackage(p)) { 7840 pkgs.add(p.packageName); 7841 } 7842 } 7843 } 7844 return pkgs; 7845 } 7846 7847 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7848 boolean checkProfiles, String targetCompilerFilter, 7849 boolean force) { 7850 // Select the dex optimizer based on the force parameter. 7851 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7852 // allocate an object here. 7853 PackageDexOptimizer pdo = force 7854 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7855 : mPackageDexOptimizer; 7856 7857 // Optimize all dependencies first. Note: we ignore the return value and march on 7858 // on errors. 7859 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7860 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7861 if (!deps.isEmpty()) { 7862 for (PackageParser.Package depPackage : deps) { 7863 // TODO: Analyze and investigate if we (should) profile libraries. 7864 // Currently this will do a full compilation of the library by default. 7865 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7866 false /* checkProfiles */, 7867 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7868 getOrCreateCompilerPackageStats(depPackage)); 7869 } 7870 } 7871 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7872 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7873 } 7874 7875 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7876 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7877 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7878 Set<String> collectedNames = new HashSet<>(); 7879 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7880 7881 retValue.remove(p); 7882 7883 return retValue; 7884 } else { 7885 return Collections.emptyList(); 7886 } 7887 } 7888 7889 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7890 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7891 if (!collectedNames.contains(p.packageName)) { 7892 collectedNames.add(p.packageName); 7893 collected.add(p); 7894 7895 if (p.usesLibraries != null) { 7896 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7897 } 7898 if (p.usesOptionalLibraries != null) { 7899 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7900 collectedNames); 7901 } 7902 } 7903 } 7904 7905 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7906 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7907 for (String libName : libs) { 7908 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7909 if (libPkg != null) { 7910 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7911 } 7912 } 7913 } 7914 7915 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7916 synchronized (mPackages) { 7917 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7918 if (lib != null && lib.apk != null) { 7919 return mPackages.get(lib.apk); 7920 } 7921 } 7922 return null; 7923 } 7924 7925 public void shutdown() { 7926 mPackageUsage.writeNow(mPackages); 7927 mCompilerStats.writeNow(); 7928 } 7929 7930 @Override 7931 public void dumpProfiles(String packageName) { 7932 PackageParser.Package pkg; 7933 synchronized (mPackages) { 7934 pkg = mPackages.get(packageName); 7935 if (pkg == null) { 7936 throw new IllegalArgumentException("Unknown package: " + packageName); 7937 } 7938 } 7939 /* Only the shell, root, or the app user should be able to dump profiles. */ 7940 int callingUid = Binder.getCallingUid(); 7941 if (callingUid != Process.SHELL_UID && 7942 callingUid != Process.ROOT_UID && 7943 callingUid != pkg.applicationInfo.uid) { 7944 throw new SecurityException("dumpProfiles"); 7945 } 7946 7947 synchronized (mInstallLock) { 7948 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7949 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7950 try { 7951 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7952 String codePaths = TextUtils.join(";", allCodePaths); 7953 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7954 } catch (InstallerException e) { 7955 Slog.w(TAG, "Failed to dump profiles", e); 7956 } 7957 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7958 } 7959 } 7960 7961 @Override 7962 public void forceDexOpt(String packageName) { 7963 enforceSystemOrRoot("forceDexOpt"); 7964 7965 PackageParser.Package pkg; 7966 synchronized (mPackages) { 7967 pkg = mPackages.get(packageName); 7968 if (pkg == null) { 7969 throw new IllegalArgumentException("Unknown package: " + packageName); 7970 } 7971 } 7972 7973 synchronized (mInstallLock) { 7974 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7975 7976 // Whoever is calling forceDexOpt wants a fully compiled package. 7977 // Don't use profiles since that may cause compilation to be skipped. 7978 final int res = performDexOptInternalWithDependenciesLI(pkg, 7979 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7980 true /* force */); 7981 7982 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7983 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7984 throw new IllegalStateException("Failed to dexopt: " + res); 7985 } 7986 } 7987 } 7988 7989 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7990 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7991 Slog.w(TAG, "Unable to update from " + oldPkg.name 7992 + " to " + newPkg.packageName 7993 + ": old package not in system partition"); 7994 return false; 7995 } else if (mPackages.get(oldPkg.name) != null) { 7996 Slog.w(TAG, "Unable to update from " + oldPkg.name 7997 + " to " + newPkg.packageName 7998 + ": old package still exists"); 7999 return false; 8000 } 8001 return true; 8002 } 8003 8004 void removeCodePathLI(File codePath) { 8005 if (codePath.isDirectory()) { 8006 try { 8007 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8008 } catch (InstallerException e) { 8009 Slog.w(TAG, "Failed to remove code path", e); 8010 } 8011 } else { 8012 codePath.delete(); 8013 } 8014 } 8015 8016 private int[] resolveUserIds(int userId) { 8017 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8018 } 8019 8020 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8021 if (pkg == null) { 8022 Slog.wtf(TAG, "Package was null!", new Throwable()); 8023 return; 8024 } 8025 clearAppDataLeafLIF(pkg, userId, flags); 8026 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8027 for (int i = 0; i < childCount; i++) { 8028 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8029 } 8030 } 8031 8032 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8033 final PackageSetting ps; 8034 synchronized (mPackages) { 8035 ps = mSettings.mPackages.get(pkg.packageName); 8036 } 8037 for (int realUserId : resolveUserIds(userId)) { 8038 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8039 try { 8040 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8041 ceDataInode); 8042 } catch (InstallerException e) { 8043 Slog.w(TAG, String.valueOf(e)); 8044 } 8045 } 8046 } 8047 8048 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8049 if (pkg == null) { 8050 Slog.wtf(TAG, "Package was null!", new Throwable()); 8051 return; 8052 } 8053 destroyAppDataLeafLIF(pkg, userId, flags); 8054 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8055 for (int i = 0; i < childCount; i++) { 8056 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8057 } 8058 } 8059 8060 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8061 final PackageSetting ps; 8062 synchronized (mPackages) { 8063 ps = mSettings.mPackages.get(pkg.packageName); 8064 } 8065 for (int realUserId : resolveUserIds(userId)) { 8066 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8067 try { 8068 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8069 ceDataInode); 8070 } catch (InstallerException e) { 8071 Slog.w(TAG, String.valueOf(e)); 8072 } 8073 } 8074 } 8075 8076 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8077 if (pkg == null) { 8078 Slog.wtf(TAG, "Package was null!", new Throwable()); 8079 return; 8080 } 8081 destroyAppProfilesLeafLIF(pkg); 8082 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8083 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8084 for (int i = 0; i < childCount; i++) { 8085 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8086 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8087 true /* removeBaseMarker */); 8088 } 8089 } 8090 8091 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8092 boolean removeBaseMarker) { 8093 if (pkg.isForwardLocked()) { 8094 return; 8095 } 8096 8097 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8098 try { 8099 path = PackageManagerServiceUtils.realpath(new File(path)); 8100 } catch (IOException e) { 8101 // TODO: Should we return early here ? 8102 Slog.w(TAG, "Failed to get canonical path", e); 8103 continue; 8104 } 8105 8106 final String useMarker = path.replace('/', '@'); 8107 for (int realUserId : resolveUserIds(userId)) { 8108 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8109 if (removeBaseMarker) { 8110 File foreignUseMark = new File(profileDir, useMarker); 8111 if (foreignUseMark.exists()) { 8112 if (!foreignUseMark.delete()) { 8113 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8114 + pkg.packageName); 8115 } 8116 } 8117 } 8118 8119 File[] markers = profileDir.listFiles(); 8120 if (markers != null) { 8121 final String searchString = "@" + pkg.packageName + "@"; 8122 // We also delete all markers that contain the package name we're 8123 // uninstalling. These are associated with secondary dex-files belonging 8124 // to the package. Reconstructing the path of these dex files is messy 8125 // in general. 8126 for (File marker : markers) { 8127 if (marker.getName().indexOf(searchString) > 0) { 8128 if (!marker.delete()) { 8129 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8130 + pkg.packageName); 8131 } 8132 } 8133 } 8134 } 8135 } 8136 } 8137 } 8138 8139 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8140 try { 8141 mInstaller.destroyAppProfiles(pkg.packageName); 8142 } catch (InstallerException e) { 8143 Slog.w(TAG, String.valueOf(e)); 8144 } 8145 } 8146 8147 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8148 if (pkg == null) { 8149 Slog.wtf(TAG, "Package was null!", new Throwable()); 8150 return; 8151 } 8152 clearAppProfilesLeafLIF(pkg); 8153 // We don't remove the base foreign use marker when clearing profiles because 8154 // we will rename it when the app is updated. Unlike the actual profile contents, 8155 // the foreign use marker is good across installs. 8156 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8157 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8158 for (int i = 0; i < childCount; i++) { 8159 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8160 } 8161 } 8162 8163 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8164 try { 8165 mInstaller.clearAppProfiles(pkg.packageName); 8166 } catch (InstallerException e) { 8167 Slog.w(TAG, String.valueOf(e)); 8168 } 8169 } 8170 8171 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8172 long lastUpdateTime) { 8173 // Set parent install/update time 8174 PackageSetting ps = (PackageSetting) pkg.mExtras; 8175 if (ps != null) { 8176 ps.firstInstallTime = firstInstallTime; 8177 ps.lastUpdateTime = lastUpdateTime; 8178 } 8179 // Set children install/update time 8180 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8181 for (int i = 0; i < childCount; i++) { 8182 PackageParser.Package childPkg = pkg.childPackages.get(i); 8183 ps = (PackageSetting) childPkg.mExtras; 8184 if (ps != null) { 8185 ps.firstInstallTime = firstInstallTime; 8186 ps.lastUpdateTime = lastUpdateTime; 8187 } 8188 } 8189 } 8190 8191 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8192 PackageParser.Package changingLib) { 8193 if (file.path != null) { 8194 usesLibraryFiles.add(file.path); 8195 return; 8196 } 8197 PackageParser.Package p = mPackages.get(file.apk); 8198 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8199 // If we are doing this while in the middle of updating a library apk, 8200 // then we need to make sure to use that new apk for determining the 8201 // dependencies here. (We haven't yet finished committing the new apk 8202 // to the package manager state.) 8203 if (p == null || p.packageName.equals(changingLib.packageName)) { 8204 p = changingLib; 8205 } 8206 } 8207 if (p != null) { 8208 usesLibraryFiles.addAll(p.getAllCodePaths()); 8209 } 8210 } 8211 8212 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8213 PackageParser.Package changingLib) throws PackageManagerException { 8214 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8215 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8216 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8217 for (int i=0; i<N; i++) { 8218 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8219 if (file == null) { 8220 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8221 "Package " + pkg.packageName + " requires unavailable shared library " 8222 + pkg.usesLibraries.get(i) + "; failing!"); 8223 } 8224 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8225 } 8226 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8227 for (int i=0; i<N; i++) { 8228 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8229 if (file == null) { 8230 Slog.w(TAG, "Package " + pkg.packageName 8231 + " desires unavailable shared library " 8232 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8233 } else { 8234 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8235 } 8236 } 8237 N = usesLibraryFiles.size(); 8238 if (N > 0) { 8239 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8240 } else { 8241 pkg.usesLibraryFiles = null; 8242 } 8243 } 8244 } 8245 8246 private static boolean hasString(List<String> list, List<String> which) { 8247 if (list == null) { 8248 return false; 8249 } 8250 for (int i=list.size()-1; i>=0; i--) { 8251 for (int j=which.size()-1; j>=0; j--) { 8252 if (which.get(j).equals(list.get(i))) { 8253 return true; 8254 } 8255 } 8256 } 8257 return false; 8258 } 8259 8260 private void updateAllSharedLibrariesLPw() { 8261 for (PackageParser.Package pkg : mPackages.values()) { 8262 try { 8263 updateSharedLibrariesLPr(pkg, null); 8264 } catch (PackageManagerException e) { 8265 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8266 } 8267 } 8268 } 8269 8270 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8271 PackageParser.Package changingPkg) { 8272 ArrayList<PackageParser.Package> res = null; 8273 for (PackageParser.Package pkg : mPackages.values()) { 8274 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8275 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8276 if (res == null) { 8277 res = new ArrayList<PackageParser.Package>(); 8278 } 8279 res.add(pkg); 8280 try { 8281 updateSharedLibrariesLPr(pkg, changingPkg); 8282 } catch (PackageManagerException e) { 8283 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8284 } 8285 } 8286 } 8287 return res; 8288 } 8289 8290 /** 8291 * Derive the value of the {@code cpuAbiOverride} based on the provided 8292 * value and an optional stored value from the package settings. 8293 */ 8294 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8295 String cpuAbiOverride = null; 8296 8297 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8298 cpuAbiOverride = null; 8299 } else if (abiOverride != null) { 8300 cpuAbiOverride = abiOverride; 8301 } else if (settings != null) { 8302 cpuAbiOverride = settings.cpuAbiOverrideString; 8303 } 8304 8305 return cpuAbiOverride; 8306 } 8307 8308 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8309 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8310 throws PackageManagerException { 8311 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8312 // If the package has children and this is the first dive in the function 8313 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8314 // whether all packages (parent and children) would be successfully scanned 8315 // before the actual scan since scanning mutates internal state and we want 8316 // to atomically install the package and its children. 8317 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8318 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8319 scanFlags |= SCAN_CHECK_ONLY; 8320 } 8321 } else { 8322 scanFlags &= ~SCAN_CHECK_ONLY; 8323 } 8324 8325 final PackageParser.Package scannedPkg; 8326 try { 8327 // Scan the parent 8328 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8329 // Scan the children 8330 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8331 for (int i = 0; i < childCount; i++) { 8332 PackageParser.Package childPkg = pkg.childPackages.get(i); 8333 scanPackageLI(childPkg, policyFlags, 8334 scanFlags, currentTime, user); 8335 } 8336 } finally { 8337 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8338 } 8339 8340 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8341 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8342 } 8343 8344 return scannedPkg; 8345 } 8346 8347 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8348 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8349 boolean success = false; 8350 try { 8351 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8352 currentTime, user); 8353 success = true; 8354 return res; 8355 } finally { 8356 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8357 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8358 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8359 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8360 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8361 } 8362 } 8363 } 8364 8365 /** 8366 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8367 */ 8368 private static boolean apkHasCode(String fileName) { 8369 StrictJarFile jarFile = null; 8370 try { 8371 jarFile = new StrictJarFile(fileName, 8372 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8373 return jarFile.findEntry("classes.dex") != null; 8374 } catch (IOException ignore) { 8375 } finally { 8376 try { 8377 if (jarFile != null) { 8378 jarFile.close(); 8379 } 8380 } catch (IOException ignore) {} 8381 } 8382 return false; 8383 } 8384 8385 /** 8386 * Enforces code policy for the package. This ensures that if an APK has 8387 * declared hasCode="true" in its manifest that the APK actually contains 8388 * code. 8389 * 8390 * @throws PackageManagerException If bytecode could not be found when it should exist 8391 */ 8392 private static void assertCodePolicy(PackageParser.Package pkg) 8393 throws PackageManagerException { 8394 final boolean shouldHaveCode = 8395 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8396 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8397 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8398 "Package " + pkg.baseCodePath + " code is missing"); 8399 } 8400 8401 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8402 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8403 final boolean splitShouldHaveCode = 8404 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8405 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8406 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8407 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8408 } 8409 } 8410 } 8411 } 8412 8413 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8414 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8415 throws PackageManagerException { 8416 if (DEBUG_PACKAGE_SCANNING) { 8417 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8418 Log.d(TAG, "Scanning package " + pkg.packageName); 8419 } 8420 8421 applyPolicy(pkg, policyFlags); 8422 8423 assertPackageIsValid(pkg, policyFlags, scanFlags); 8424 8425 // Initialize package source and resource directories 8426 final File scanFile = new File(pkg.codePath); 8427 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8428 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8429 8430 SharedUserSetting suid = null; 8431 PackageSetting pkgSetting = null; 8432 8433 // Getting the package setting may have a side-effect, so if we 8434 // are only checking if scan would succeed, stash a copy of the 8435 // old setting to restore at the end. 8436 PackageSetting nonMutatedPs = null; 8437 8438 // We keep references to the derived CPU Abis from settings in oder to reuse 8439 // them in the case where we're not upgrading or booting for the first time. 8440 String primaryCpuAbiFromSettings = null; 8441 String secondaryCpuAbiFromSettings = null; 8442 8443 // writer 8444 synchronized (mPackages) { 8445 if (pkg.mSharedUserId != null) { 8446 // SIDE EFFECTS; may potentially allocate a new shared user 8447 suid = mSettings.getSharedUserLPw( 8448 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8449 if (DEBUG_PACKAGE_SCANNING) { 8450 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8451 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8452 + "): packages=" + suid.packages); 8453 } 8454 } 8455 8456 // Check if we are renaming from an original package name. 8457 PackageSetting origPackage = null; 8458 String realName = null; 8459 if (pkg.mOriginalPackages != null) { 8460 // This package may need to be renamed to a previously 8461 // installed name. Let's check on that... 8462 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8463 if (pkg.mOriginalPackages.contains(renamed)) { 8464 // This package had originally been installed as the 8465 // original name, and we have already taken care of 8466 // transitioning to the new one. Just update the new 8467 // one to continue using the old name. 8468 realName = pkg.mRealPackage; 8469 if (!pkg.packageName.equals(renamed)) { 8470 // Callers into this function may have already taken 8471 // care of renaming the package; only do it here if 8472 // it is not already done. 8473 pkg.setPackageName(renamed); 8474 } 8475 } else { 8476 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8477 if ((origPackage = mSettings.getPackageLPr( 8478 pkg.mOriginalPackages.get(i))) != null) { 8479 // We do have the package already installed under its 8480 // original name... should we use it? 8481 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8482 // New package is not compatible with original. 8483 origPackage = null; 8484 continue; 8485 } else if (origPackage.sharedUser != null) { 8486 // Make sure uid is compatible between packages. 8487 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8488 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8489 + " to " + pkg.packageName + ": old uid " 8490 + origPackage.sharedUser.name 8491 + " differs from " + pkg.mSharedUserId); 8492 origPackage = null; 8493 continue; 8494 } 8495 // TODO: Add case when shared user id is added [b/28144775] 8496 } else { 8497 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8498 + pkg.packageName + " to old name " + origPackage.name); 8499 } 8500 break; 8501 } 8502 } 8503 } 8504 } 8505 8506 if (mTransferedPackages.contains(pkg.packageName)) { 8507 Slog.w(TAG, "Package " + pkg.packageName 8508 + " was transferred to another, but its .apk remains"); 8509 } 8510 8511 // See comments in nonMutatedPs declaration 8512 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8513 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8514 if (foundPs != null) { 8515 nonMutatedPs = new PackageSetting(foundPs); 8516 } 8517 } 8518 8519 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8520 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8521 if (foundPs != null) { 8522 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8523 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8524 } 8525 } 8526 8527 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8528 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8529 PackageManagerService.reportSettingsProblem(Log.WARN, 8530 "Package " + pkg.packageName + " shared user changed from " 8531 + (pkgSetting.sharedUser != null 8532 ? pkgSetting.sharedUser.name : "<nothing>") 8533 + " to " 8534 + (suid != null ? suid.name : "<nothing>") 8535 + "; replacing with new"); 8536 pkgSetting = null; 8537 } 8538 final PackageSetting oldPkgSetting = 8539 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8540 final PackageSetting disabledPkgSetting = 8541 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8542 if (pkgSetting == null) { 8543 final String parentPackageName = (pkg.parentPackage != null) 8544 ? pkg.parentPackage.packageName : null; 8545 // REMOVE SharedUserSetting from method; update in a separate call 8546 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8547 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8548 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8549 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8550 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8551 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8552 UserManagerService.getInstance()); 8553 // SIDE EFFECTS; updates system state; move elsewhere 8554 if (origPackage != null) { 8555 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8556 } 8557 mSettings.addUserToSettingLPw(pkgSetting); 8558 } else { 8559 // REMOVE SharedUserSetting from method; update in a separate call. 8560 // 8561 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8562 // secondaryCpuAbi are not known at this point so we always update them 8563 // to null here, only to reset them at a later point. 8564 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8565 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8566 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8567 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8568 UserManagerService.getInstance()); 8569 } 8570 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8571 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8572 8573 // SIDE EFFECTS; modifies system state; move elsewhere 8574 if (pkgSetting.origPackage != null) { 8575 // If we are first transitioning from an original package, 8576 // fix up the new package's name now. We need to do this after 8577 // looking up the package under its new name, so getPackageLP 8578 // can take care of fiddling things correctly. 8579 pkg.setPackageName(origPackage.name); 8580 8581 // File a report about this. 8582 String msg = "New package " + pkgSetting.realName 8583 + " renamed to replace old package " + pkgSetting.name; 8584 reportSettingsProblem(Log.WARN, msg); 8585 8586 // Make a note of it. 8587 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8588 mTransferedPackages.add(origPackage.name); 8589 } 8590 8591 // No longer need to retain this. 8592 pkgSetting.origPackage = null; 8593 } 8594 8595 // SIDE EFFECTS; modifies system state; move elsewhere 8596 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8597 // Make a note of it. 8598 mTransferedPackages.add(pkg.packageName); 8599 } 8600 8601 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8602 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8603 } 8604 8605 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8606 // Check all shared libraries and map to their actual file path. 8607 // We only do this here for apps not on a system dir, because those 8608 // are the only ones that can fail an install due to this. We 8609 // will take care of the system apps by updating all of their 8610 // library paths after the scan is done. 8611 updateSharedLibrariesLPr(pkg, null); 8612 } 8613 8614 if (mFoundPolicyFile) { 8615 SELinuxMMAC.assignSeinfoValue(pkg); 8616 } 8617 8618 pkg.applicationInfo.uid = pkgSetting.appId; 8619 pkg.mExtras = pkgSetting; 8620 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8621 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8622 // We just determined the app is signed correctly, so bring 8623 // over the latest parsed certs. 8624 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8625 } else { 8626 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8627 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8628 "Package " + pkg.packageName + " upgrade keys do not match the " 8629 + "previously installed version"); 8630 } else { 8631 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8632 String msg = "System package " + pkg.packageName 8633 + " signature changed; retaining data."; 8634 reportSettingsProblem(Log.WARN, msg); 8635 } 8636 } 8637 } else { 8638 try { 8639 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8640 verifySignaturesLP(pkgSetting, pkg); 8641 // We just determined the app is signed correctly, so bring 8642 // over the latest parsed certs. 8643 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8644 } catch (PackageManagerException e) { 8645 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8646 throw e; 8647 } 8648 // The signature has changed, but this package is in the system 8649 // image... let's recover! 8650 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8651 // However... if this package is part of a shared user, but it 8652 // doesn't match the signature of the shared user, let's fail. 8653 // What this means is that you can't change the signatures 8654 // associated with an overall shared user, which doesn't seem all 8655 // that unreasonable. 8656 if (pkgSetting.sharedUser != null) { 8657 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8658 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8659 throw new PackageManagerException( 8660 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8661 "Signature mismatch for shared user: " 8662 + pkgSetting.sharedUser); 8663 } 8664 } 8665 // File a report about this. 8666 String msg = "System package " + pkg.packageName 8667 + " signature changed; retaining data."; 8668 reportSettingsProblem(Log.WARN, msg); 8669 } 8670 } 8671 8672 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8673 // This package wants to adopt ownership of permissions from 8674 // another package. 8675 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8676 final String origName = pkg.mAdoptPermissions.get(i); 8677 final PackageSetting orig = mSettings.getPackageLPr(origName); 8678 if (orig != null) { 8679 if (verifyPackageUpdateLPr(orig, pkg)) { 8680 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8681 + pkg.packageName); 8682 // SIDE EFFECTS; updates permissions system state; move elsewhere 8683 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8684 } 8685 } 8686 } 8687 } 8688 } 8689 8690 pkg.applicationInfo.processName = fixProcessName( 8691 pkg.applicationInfo.packageName, 8692 pkg.applicationInfo.processName); 8693 8694 if (pkg != mPlatformPackage) { 8695 // Get all of our default paths setup 8696 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8697 } 8698 8699 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8700 8701 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8702 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8703 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8704 derivePackageAbi( 8705 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8706 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8707 8708 // Some system apps still use directory structure for native libraries 8709 // in which case we might end up not detecting abi solely based on apk 8710 // structure. Try to detect abi based on directory structure. 8711 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8712 pkg.applicationInfo.primaryCpuAbi == null) { 8713 setBundledAppAbisAndRoots(pkg, pkgSetting); 8714 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8715 } 8716 } else { 8717 // This is not a first boot or an upgrade, don't bother deriving the 8718 // ABI during the scan. Instead, trust the value that was stored in the 8719 // package setting. 8720 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8721 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8722 8723 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8724 8725 if (DEBUG_ABI_SELECTION) { 8726 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8727 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8728 pkg.applicationInfo.secondaryCpuAbi); 8729 } 8730 } 8731 } else { 8732 if ((scanFlags & SCAN_MOVE) != 0) { 8733 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8734 // but we already have this packages package info in the PackageSetting. We just 8735 // use that and derive the native library path based on the new codepath. 8736 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8737 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8738 } 8739 8740 // Set native library paths again. For moves, the path will be updated based on the 8741 // ABIs we've determined above. For non-moves, the path will be updated based on the 8742 // ABIs we determined during compilation, but the path will depend on the final 8743 // package path (after the rename away from the stage path). 8744 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8745 } 8746 8747 // This is a special case for the "system" package, where the ABI is 8748 // dictated by the zygote configuration (and init.rc). We should keep track 8749 // of this ABI so that we can deal with "normal" applications that run under 8750 // the same UID correctly. 8751 if (mPlatformPackage == pkg) { 8752 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8753 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8754 } 8755 8756 // If there's a mismatch between the abi-override in the package setting 8757 // and the abiOverride specified for the install. Warn about this because we 8758 // would've already compiled the app without taking the package setting into 8759 // account. 8760 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8761 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8762 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8763 " for package " + pkg.packageName); 8764 } 8765 } 8766 8767 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8768 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8769 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8770 8771 // Copy the derived override back to the parsed package, so that we can 8772 // update the package settings accordingly. 8773 pkg.cpuAbiOverride = cpuAbiOverride; 8774 8775 if (DEBUG_ABI_SELECTION) { 8776 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8777 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8778 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8779 } 8780 8781 // Push the derived path down into PackageSettings so we know what to 8782 // clean up at uninstall time. 8783 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8784 8785 if (DEBUG_ABI_SELECTION) { 8786 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8787 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8788 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8789 } 8790 8791 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8792 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8793 // We don't do this here during boot because we can do it all 8794 // at once after scanning all existing packages. 8795 // 8796 // We also do this *before* we perform dexopt on this package, so that 8797 // we can avoid redundant dexopts, and also to make sure we've got the 8798 // code and package path correct. 8799 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8800 } 8801 8802 if (mFactoryTest && pkg.requestedPermissions.contains( 8803 android.Manifest.permission.FACTORY_TEST)) { 8804 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8805 } 8806 8807 if (isSystemApp(pkg)) { 8808 pkgSetting.isOrphaned = true; 8809 } 8810 8811 // Take care of first install / last update times. 8812 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8813 if (currentTime != 0) { 8814 if (pkgSetting.firstInstallTime == 0) { 8815 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8816 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8817 pkgSetting.lastUpdateTime = currentTime; 8818 } 8819 } else if (pkgSetting.firstInstallTime == 0) { 8820 // We need *something*. Take time time stamp of the file. 8821 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8822 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8823 if (scanFileTime != pkgSetting.timeStamp) { 8824 // A package on the system image has changed; consider this 8825 // to be an update. 8826 pkgSetting.lastUpdateTime = scanFileTime; 8827 } 8828 } 8829 pkgSetting.setTimeStamp(scanFileTime); 8830 8831 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8832 if (nonMutatedPs != null) { 8833 synchronized (mPackages) { 8834 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8835 } 8836 } 8837 } else { 8838 // Modify state for the given package setting 8839 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8840 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8841 } 8842 return pkg; 8843 } 8844 8845 /** 8846 * Applies policy to the parsed package based upon the given policy flags. 8847 * Ensures the package is in a good state. 8848 * <p> 8849 * Implementation detail: This method must NOT have any side effect. It would 8850 * ideally be static, but, it requires locks to read system state. 8851 */ 8852 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8853 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8854 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8855 if (pkg.applicationInfo.isDirectBootAware()) { 8856 // we're direct boot aware; set for all components 8857 for (PackageParser.Service s : pkg.services) { 8858 s.info.encryptionAware = s.info.directBootAware = true; 8859 } 8860 for (PackageParser.Provider p : pkg.providers) { 8861 p.info.encryptionAware = p.info.directBootAware = true; 8862 } 8863 for (PackageParser.Activity a : pkg.activities) { 8864 a.info.encryptionAware = a.info.directBootAware = true; 8865 } 8866 for (PackageParser.Activity r : pkg.receivers) { 8867 r.info.encryptionAware = r.info.directBootAware = true; 8868 } 8869 } 8870 } else { 8871 // Only allow system apps to be flagged as core apps. 8872 pkg.coreApp = false; 8873 // clear flags not applicable to regular apps 8874 pkg.applicationInfo.privateFlags &= 8875 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8876 pkg.applicationInfo.privateFlags &= 8877 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8878 } 8879 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8880 8881 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8882 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8883 } 8884 8885 if (!isSystemApp(pkg)) { 8886 // Only system apps can use these features. 8887 pkg.mOriginalPackages = null; 8888 pkg.mRealPackage = null; 8889 pkg.mAdoptPermissions = null; 8890 } 8891 } 8892 8893 /** 8894 * Asserts the parsed package is valid according to teh given policy. If the 8895 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8896 * <p> 8897 * Implementation detail: This method must NOT have any side effects. It would 8898 * ideally be static, but, it requires locks to read system state. 8899 * 8900 * @throws PackageManagerException If the package fails any of the validation checks 8901 */ 8902 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8903 throws PackageManagerException { 8904 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8905 assertCodePolicy(pkg); 8906 } 8907 8908 if (pkg.applicationInfo.getCodePath() == null || 8909 pkg.applicationInfo.getResourcePath() == null) { 8910 // Bail out. The resource and code paths haven't been set. 8911 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8912 "Code and resource paths haven't been set correctly"); 8913 } 8914 8915 // Make sure we're not adding any bogus keyset info 8916 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8917 ksms.assertScannedPackageValid(pkg); 8918 8919 synchronized (mPackages) { 8920 // The special "android" package can only be defined once 8921 if (pkg.packageName.equals("android")) { 8922 if (mAndroidApplication != null) { 8923 Slog.w(TAG, "*************************************************"); 8924 Slog.w(TAG, "Core android package being redefined. Skipping."); 8925 Slog.w(TAG, " codePath=" + pkg.codePath); 8926 Slog.w(TAG, "*************************************************"); 8927 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8928 "Core android package being redefined. Skipping."); 8929 } 8930 } 8931 8932 // A package name must be unique; don't allow duplicates 8933 if (mPackages.containsKey(pkg.packageName) 8934 || mSharedLibraries.containsKey(pkg.packageName)) { 8935 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8936 "Application package " + pkg.packageName 8937 + " already installed. Skipping duplicate."); 8938 } 8939 8940 // Only privileged apps and updated privileged apps can add child packages. 8941 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8942 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8943 throw new PackageManagerException("Only privileged apps can add child " 8944 + "packages. Ignoring package " + pkg.packageName); 8945 } 8946 final int childCount = pkg.childPackages.size(); 8947 for (int i = 0; i < childCount; i++) { 8948 PackageParser.Package childPkg = pkg.childPackages.get(i); 8949 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8950 childPkg.packageName)) { 8951 throw new PackageManagerException("Can't override child of " 8952 + "another disabled app. Ignoring package " + pkg.packageName); 8953 } 8954 } 8955 } 8956 8957 // If we're only installing presumed-existing packages, require that the 8958 // scanned APK is both already known and at the path previously established 8959 // for it. Previously unknown packages we pick up normally, but if we have an 8960 // a priori expectation about this package's install presence, enforce it. 8961 // With a singular exception for new system packages. When an OTA contains 8962 // a new system package, we allow the codepath to change from a system location 8963 // to the user-installed location. If we don't allow this change, any newer, 8964 // user-installed version of the application will be ignored. 8965 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8966 if (mExpectingBetter.containsKey(pkg.packageName)) { 8967 logCriticalInfo(Log.WARN, 8968 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8969 } else { 8970 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8971 if (known != null) { 8972 if (DEBUG_PACKAGE_SCANNING) { 8973 Log.d(TAG, "Examining " + pkg.codePath 8974 + " and requiring known paths " + known.codePathString 8975 + " & " + known.resourcePathString); 8976 } 8977 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8978 || !pkg.applicationInfo.getResourcePath().equals( 8979 known.resourcePathString)) { 8980 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8981 "Application package " + pkg.packageName 8982 + " found at " + pkg.applicationInfo.getCodePath() 8983 + " but expected at " + known.codePathString 8984 + "; ignoring."); 8985 } 8986 } 8987 } 8988 } 8989 8990 // Verify that this new package doesn't have any content providers 8991 // that conflict with existing packages. Only do this if the 8992 // package isn't already installed, since we don't want to break 8993 // things that are installed. 8994 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8995 final int N = pkg.providers.size(); 8996 int i; 8997 for (i=0; i<N; i++) { 8998 PackageParser.Provider p = pkg.providers.get(i); 8999 if (p.info.authority != null) { 9000 String names[] = p.info.authority.split(";"); 9001 for (int j = 0; j < names.length; j++) { 9002 if (mProvidersByAuthority.containsKey(names[j])) { 9003 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9004 final String otherPackageName = 9005 ((other != null && other.getComponentName() != null) ? 9006 other.getComponentName().getPackageName() : "?"); 9007 throw new PackageManagerException( 9008 INSTALL_FAILED_CONFLICTING_PROVIDER, 9009 "Can't install because provider name " + names[j] 9010 + " (in package " + pkg.applicationInfo.packageName 9011 + ") is already used by " + otherPackageName); 9012 } 9013 } 9014 } 9015 } 9016 } 9017 } 9018 } 9019 9020 /** 9021 * Adds a scanned package to the system. When this method is finished, the package will 9022 * be available for query, resolution, etc... 9023 */ 9024 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9025 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9026 final String pkgName = pkg.packageName; 9027 if (mCustomResolverComponentName != null && 9028 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9029 setUpCustomResolverActivity(pkg); 9030 } 9031 9032 if (pkg.packageName.equals("android")) { 9033 synchronized (mPackages) { 9034 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9035 // Set up information for our fall-back user intent resolution activity. 9036 mPlatformPackage = pkg; 9037 pkg.mVersionCode = mSdkVersion; 9038 mAndroidApplication = pkg.applicationInfo; 9039 9040 if (!mResolverReplaced) { 9041 mResolveActivity.applicationInfo = mAndroidApplication; 9042 mResolveActivity.name = ResolverActivity.class.getName(); 9043 mResolveActivity.packageName = mAndroidApplication.packageName; 9044 mResolveActivity.processName = "system:ui"; 9045 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9046 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9047 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9048 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9049 mResolveActivity.exported = true; 9050 mResolveActivity.enabled = true; 9051 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9052 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9053 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9054 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9055 | ActivityInfo.CONFIG_ORIENTATION 9056 | ActivityInfo.CONFIG_KEYBOARD 9057 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9058 mResolveInfo.activityInfo = mResolveActivity; 9059 mResolveInfo.priority = 0; 9060 mResolveInfo.preferredOrder = 0; 9061 mResolveInfo.match = 0; 9062 mResolveComponentName = new ComponentName( 9063 mAndroidApplication.packageName, mResolveActivity.name); 9064 } 9065 } 9066 } 9067 } 9068 9069 ArrayList<PackageParser.Package> clientLibPkgs = null; 9070 // writer 9071 synchronized (mPackages) { 9072 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9073 // Only system apps can add new shared libraries. 9074 if (pkg.libraryNames != null) { 9075 for (int i=0; i<pkg.libraryNames.size(); i++) { 9076 String name = pkg.libraryNames.get(i); 9077 boolean allowed = false; 9078 if (pkg.isUpdatedSystemApp()) { 9079 // New library entries can only be added through the 9080 // system image. This is important to get rid of a lot 9081 // of nasty edge cases: for example if we allowed a non- 9082 // system update of the app to add a library, then uninstalling 9083 // the update would make the library go away, and assumptions 9084 // we made such as through app install filtering would now 9085 // have allowed apps on the device which aren't compatible 9086 // with it. Better to just have the restriction here, be 9087 // conservative, and create many fewer cases that can negatively 9088 // impact the user experience. 9089 final PackageSetting sysPs = mSettings 9090 .getDisabledSystemPkgLPr(pkg.packageName); 9091 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9092 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 9093 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9094 allowed = true; 9095 break; 9096 } 9097 } 9098 } 9099 } else { 9100 allowed = true; 9101 } 9102 if (allowed) { 9103 if (!mSharedLibraries.containsKey(name)) { 9104 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 9105 } else if (!name.equals(pkg.packageName)) { 9106 Slog.w(TAG, "Package " + pkg.packageName + " library " 9107 + name + " already exists; skipping"); 9108 } 9109 } else { 9110 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9111 + name + " that is not declared on system image; skipping"); 9112 } 9113 } 9114 if ((scanFlags & SCAN_BOOTING) == 0) { 9115 // If we are not booting, we need to update any applications 9116 // that are clients of our shared library. If we are booting, 9117 // this will all be done once the scan is complete. 9118 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9119 } 9120 } 9121 } 9122 } 9123 9124 if ((scanFlags & SCAN_BOOTING) != 0) { 9125 // No apps can run during boot scan, so they don't need to be frozen 9126 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9127 // Caller asked to not kill app, so it's probably not frozen 9128 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9129 // Caller asked us to ignore frozen check for some reason; they 9130 // probably didn't know the package name 9131 } else { 9132 // We're doing major surgery on this package, so it better be frozen 9133 // right now to keep it from launching 9134 checkPackageFrozen(pkgName); 9135 } 9136 9137 // Also need to kill any apps that are dependent on the library. 9138 if (clientLibPkgs != null) { 9139 for (int i=0; i<clientLibPkgs.size(); i++) { 9140 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9141 killApplication(clientPkg.applicationInfo.packageName, 9142 clientPkg.applicationInfo.uid, "update lib"); 9143 } 9144 } 9145 9146 // writer 9147 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9148 9149 boolean createIdmapFailed = false; 9150 synchronized (mPackages) { 9151 // We don't expect installation to fail beyond this point 9152 9153 if (pkgSetting.pkg != null) { 9154 // Note that |user| might be null during the initial boot scan. If a codePath 9155 // for an app has changed during a boot scan, it's due to an app update that's 9156 // part of the system partition and marker changes must be applied to all users. 9157 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9158 final int[] userIds = resolveUserIds(userId); 9159 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9160 } 9161 9162 // Add the new setting to mSettings 9163 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9164 // Add the new setting to mPackages 9165 mPackages.put(pkg.applicationInfo.packageName, pkg); 9166 // Make sure we don't accidentally delete its data. 9167 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9168 while (iter.hasNext()) { 9169 PackageCleanItem item = iter.next(); 9170 if (pkgName.equals(item.packageName)) { 9171 iter.remove(); 9172 } 9173 } 9174 9175 // Add the package's KeySets to the global KeySetManagerService 9176 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9177 ksms.addScannedPackageLPw(pkg); 9178 9179 int N = pkg.providers.size(); 9180 StringBuilder r = null; 9181 int i; 9182 for (i=0; i<N; i++) { 9183 PackageParser.Provider p = pkg.providers.get(i); 9184 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9185 p.info.processName); 9186 mProviders.addProvider(p); 9187 p.syncable = p.info.isSyncable; 9188 if (p.info.authority != null) { 9189 String names[] = p.info.authority.split(";"); 9190 p.info.authority = null; 9191 for (int j = 0; j < names.length; j++) { 9192 if (j == 1 && p.syncable) { 9193 // We only want the first authority for a provider to possibly be 9194 // syncable, so if we already added this provider using a different 9195 // authority clear the syncable flag. We copy the provider before 9196 // changing it because the mProviders object contains a reference 9197 // to a provider that we don't want to change. 9198 // Only do this for the second authority since the resulting provider 9199 // object can be the same for all future authorities for this provider. 9200 p = new PackageParser.Provider(p); 9201 p.syncable = false; 9202 } 9203 if (!mProvidersByAuthority.containsKey(names[j])) { 9204 mProvidersByAuthority.put(names[j], p); 9205 if (p.info.authority == null) { 9206 p.info.authority = names[j]; 9207 } else { 9208 p.info.authority = p.info.authority + ";" + names[j]; 9209 } 9210 if (DEBUG_PACKAGE_SCANNING) { 9211 if (chatty) 9212 Log.d(TAG, "Registered content provider: " + names[j] 9213 + ", className = " + p.info.name + ", isSyncable = " 9214 + p.info.isSyncable); 9215 } 9216 } else { 9217 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9218 Slog.w(TAG, "Skipping provider name " + names[j] + 9219 " (in package " + pkg.applicationInfo.packageName + 9220 "): name already used by " 9221 + ((other != null && other.getComponentName() != null) 9222 ? other.getComponentName().getPackageName() : "?")); 9223 } 9224 } 9225 } 9226 if (chatty) { 9227 if (r == null) { 9228 r = new StringBuilder(256); 9229 } else { 9230 r.append(' '); 9231 } 9232 r.append(p.info.name); 9233 } 9234 } 9235 if (r != null) { 9236 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9237 } 9238 9239 N = pkg.services.size(); 9240 r = null; 9241 for (i=0; i<N; i++) { 9242 PackageParser.Service s = pkg.services.get(i); 9243 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9244 s.info.processName); 9245 mServices.addService(s); 9246 if (chatty) { 9247 if (r == null) { 9248 r = new StringBuilder(256); 9249 } else { 9250 r.append(' '); 9251 } 9252 r.append(s.info.name); 9253 } 9254 } 9255 if (r != null) { 9256 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9257 } 9258 9259 N = pkg.receivers.size(); 9260 r = null; 9261 for (i=0; i<N; i++) { 9262 PackageParser.Activity a = pkg.receivers.get(i); 9263 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9264 a.info.processName); 9265 mReceivers.addActivity(a, "receiver"); 9266 if (chatty) { 9267 if (r == null) { 9268 r = new StringBuilder(256); 9269 } else { 9270 r.append(' '); 9271 } 9272 r.append(a.info.name); 9273 } 9274 } 9275 if (r != null) { 9276 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9277 } 9278 9279 N = pkg.activities.size(); 9280 r = null; 9281 for (i=0; i<N; i++) { 9282 PackageParser.Activity a = pkg.activities.get(i); 9283 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9284 a.info.processName); 9285 mActivities.addActivity(a, "activity"); 9286 if (chatty) { 9287 if (r == null) { 9288 r = new StringBuilder(256); 9289 } else { 9290 r.append(' '); 9291 } 9292 r.append(a.info.name); 9293 } 9294 } 9295 if (r != null) { 9296 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9297 } 9298 9299 N = pkg.permissionGroups.size(); 9300 r = null; 9301 for (i=0; i<N; i++) { 9302 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9303 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9304 final String curPackageName = cur == null ? null : cur.info.packageName; 9305 // Dont allow ephemeral apps to define new permission groups. 9306 if (pkg.applicationInfo.isEphemeralApp()) { 9307 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9308 + pg.info.packageName 9309 + " ignored: ephemeral apps cannot define new permission groups."); 9310 continue; 9311 } 9312 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9313 if (cur == null || isPackageUpdate) { 9314 mPermissionGroups.put(pg.info.name, pg); 9315 if (chatty) { 9316 if (r == null) { 9317 r = new StringBuilder(256); 9318 } else { 9319 r.append(' '); 9320 } 9321 if (isPackageUpdate) { 9322 r.append("UPD:"); 9323 } 9324 r.append(pg.info.name); 9325 } 9326 } else { 9327 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9328 + pg.info.packageName + " ignored: original from " 9329 + cur.info.packageName); 9330 if (chatty) { 9331 if (r == null) { 9332 r = new StringBuilder(256); 9333 } else { 9334 r.append(' '); 9335 } 9336 r.append("DUP:"); 9337 r.append(pg.info.name); 9338 } 9339 } 9340 } 9341 if (r != null) { 9342 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9343 } 9344 9345 N = pkg.permissions.size(); 9346 r = null; 9347 for (i=0; i<N; i++) { 9348 PackageParser.Permission p = pkg.permissions.get(i); 9349 9350 // Dont allow ephemeral apps to define new permissions. 9351 if (pkg.applicationInfo.isEphemeralApp()) { 9352 Slog.w(TAG, "Permission " + p.info.name + " from package " 9353 + p.info.packageName 9354 + " ignored: ephemeral apps cannot define new permissions."); 9355 continue; 9356 } 9357 9358 // Assume by default that we did not install this permission into the system. 9359 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9360 9361 // Now that permission groups have a special meaning, we ignore permission 9362 // groups for legacy apps to prevent unexpected behavior. In particular, 9363 // permissions for one app being granted to someone just becase they happen 9364 // to be in a group defined by another app (before this had no implications). 9365 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9366 p.group = mPermissionGroups.get(p.info.group); 9367 // Warn for a permission in an unknown group. 9368 if (p.info.group != null && p.group == null) { 9369 Slog.w(TAG, "Permission " + p.info.name + " from package " 9370 + p.info.packageName + " in an unknown group " + p.info.group); 9371 } 9372 } 9373 9374 ArrayMap<String, BasePermission> permissionMap = 9375 p.tree ? mSettings.mPermissionTrees 9376 : mSettings.mPermissions; 9377 BasePermission bp = permissionMap.get(p.info.name); 9378 9379 // Allow system apps to redefine non-system permissions 9380 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9381 final boolean currentOwnerIsSystem = (bp.perm != null 9382 && isSystemApp(bp.perm.owner)); 9383 if (isSystemApp(p.owner)) { 9384 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9385 // It's a built-in permission and no owner, take ownership now 9386 bp.packageSetting = pkgSetting; 9387 bp.perm = p; 9388 bp.uid = pkg.applicationInfo.uid; 9389 bp.sourcePackage = p.info.packageName; 9390 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9391 } else if (!currentOwnerIsSystem) { 9392 String msg = "New decl " + p.owner + " of permission " 9393 + p.info.name + " is system; overriding " + bp.sourcePackage; 9394 reportSettingsProblem(Log.WARN, msg); 9395 bp = null; 9396 } 9397 } 9398 } 9399 9400 if (bp == null) { 9401 bp = new BasePermission(p.info.name, p.info.packageName, 9402 BasePermission.TYPE_NORMAL); 9403 permissionMap.put(p.info.name, bp); 9404 } 9405 9406 if (bp.perm == null) { 9407 if (bp.sourcePackage == null 9408 || bp.sourcePackage.equals(p.info.packageName)) { 9409 BasePermission tree = findPermissionTreeLP(p.info.name); 9410 if (tree == null 9411 || tree.sourcePackage.equals(p.info.packageName)) { 9412 bp.packageSetting = pkgSetting; 9413 bp.perm = p; 9414 bp.uid = pkg.applicationInfo.uid; 9415 bp.sourcePackage = p.info.packageName; 9416 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9417 if (chatty) { 9418 if (r == null) { 9419 r = new StringBuilder(256); 9420 } else { 9421 r.append(' '); 9422 } 9423 r.append(p.info.name); 9424 } 9425 } else { 9426 Slog.w(TAG, "Permission " + p.info.name + " from package " 9427 + p.info.packageName + " ignored: base tree " 9428 + tree.name + " is from package " 9429 + tree.sourcePackage); 9430 } 9431 } else { 9432 Slog.w(TAG, "Permission " + p.info.name + " from package " 9433 + p.info.packageName + " ignored: original from " 9434 + bp.sourcePackage); 9435 } 9436 } else if (chatty) { 9437 if (r == null) { 9438 r = new StringBuilder(256); 9439 } else { 9440 r.append(' '); 9441 } 9442 r.append("DUP:"); 9443 r.append(p.info.name); 9444 } 9445 if (bp.perm == p) { 9446 bp.protectionLevel = p.info.protectionLevel; 9447 } 9448 } 9449 9450 if (r != null) { 9451 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9452 } 9453 9454 N = pkg.instrumentation.size(); 9455 r = null; 9456 for (i=0; i<N; i++) { 9457 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9458 a.info.packageName = pkg.applicationInfo.packageName; 9459 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9460 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9461 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9462 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9463 a.info.dataDir = pkg.applicationInfo.dataDir; 9464 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9465 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9466 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9467 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9468 mInstrumentation.put(a.getComponentName(), a); 9469 if (chatty) { 9470 if (r == null) { 9471 r = new StringBuilder(256); 9472 } else { 9473 r.append(' '); 9474 } 9475 r.append(a.info.name); 9476 } 9477 } 9478 if (r != null) { 9479 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9480 } 9481 9482 if (pkg.protectedBroadcasts != null) { 9483 N = pkg.protectedBroadcasts.size(); 9484 for (i=0; i<N; i++) { 9485 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9486 } 9487 } 9488 9489 // Create idmap files for pairs of (packages, overlay packages). 9490 // Note: "android", ie framework-res.apk, is handled by native layers. 9491 if (pkg.mOverlayTarget != null) { 9492 // This is an overlay package. 9493 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9494 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9495 mOverlays.put(pkg.mOverlayTarget, 9496 new ArrayMap<String, PackageParser.Package>()); 9497 } 9498 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9499 map.put(pkg.packageName, pkg); 9500 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9501 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9502 createIdmapFailed = true; 9503 } 9504 } 9505 } else if (mOverlays.containsKey(pkg.packageName) && 9506 !pkg.packageName.equals("android")) { 9507 // This is a regular package, with one or more known overlay packages. 9508 createIdmapsForPackageLI(pkg); 9509 } 9510 } 9511 9512 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9513 9514 if (createIdmapFailed) { 9515 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9516 "scanPackageLI failed to createIdmap"); 9517 } 9518 } 9519 9520 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9521 PackageParser.Package update, int[] userIds) { 9522 if (existing.applicationInfo == null || update.applicationInfo == null) { 9523 // This isn't due to an app installation. 9524 return; 9525 } 9526 9527 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9528 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9529 9530 // The codePath hasn't changed, so there's nothing for us to do. 9531 if (Objects.equals(oldCodePath, newCodePath)) { 9532 return; 9533 } 9534 9535 File canonicalNewCodePath; 9536 try { 9537 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9538 } catch (IOException e) { 9539 Slog.w(TAG, "Failed to get canonical path.", e); 9540 return; 9541 } 9542 9543 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9544 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9545 // that the last component of the path (i.e, the name) doesn't need canonicalization 9546 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9547 // but may change in the future. Hopefully this function won't exist at that point. 9548 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9549 oldCodePath.getName()); 9550 9551 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9552 // with "@". 9553 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9554 if (!oldMarkerPrefix.endsWith("@")) { 9555 oldMarkerPrefix += "@"; 9556 } 9557 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9558 if (!newMarkerPrefix.endsWith("@")) { 9559 newMarkerPrefix += "@"; 9560 } 9561 9562 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9563 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9564 for (String updatedPath : updatedPaths) { 9565 String updatedPathName = new File(updatedPath).getName(); 9566 markerSuffixes.add(updatedPathName.replace('/', '@')); 9567 } 9568 9569 for (int userId : userIds) { 9570 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9571 9572 for (String markerSuffix : markerSuffixes) { 9573 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9574 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9575 if (oldForeignUseMark.exists()) { 9576 try { 9577 Os.rename(oldForeignUseMark.getAbsolutePath(), 9578 newForeignUseMark.getAbsolutePath()); 9579 } catch (ErrnoException e) { 9580 Slog.w(TAG, "Failed to rename foreign use marker", e); 9581 oldForeignUseMark.delete(); 9582 } 9583 } 9584 } 9585 } 9586 } 9587 9588 /** 9589 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9590 * is derived purely on the basis of the contents of {@code scanFile} and 9591 * {@code cpuAbiOverride}. 9592 * 9593 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9594 */ 9595 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9596 String cpuAbiOverride, boolean extractLibs, 9597 File appLib32InstallDir) 9598 throws PackageManagerException { 9599 // Give ourselves some initial paths; we'll come back for another 9600 // pass once we've determined ABI below. 9601 setNativeLibraryPaths(pkg, appLib32InstallDir); 9602 9603 // We would never need to extract libs for forward-locked and external packages, 9604 // since the container service will do it for us. We shouldn't attempt to 9605 // extract libs from system app when it was not updated. 9606 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9607 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9608 extractLibs = false; 9609 } 9610 9611 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9612 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9613 9614 NativeLibraryHelper.Handle handle = null; 9615 try { 9616 handle = NativeLibraryHelper.Handle.create(pkg); 9617 // TODO(multiArch): This can be null for apps that didn't go through the 9618 // usual installation process. We can calculate it again, like we 9619 // do during install time. 9620 // 9621 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9622 // unnecessary. 9623 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9624 9625 // Null out the abis so that they can be recalculated. 9626 pkg.applicationInfo.primaryCpuAbi = null; 9627 pkg.applicationInfo.secondaryCpuAbi = null; 9628 if (isMultiArch(pkg.applicationInfo)) { 9629 // Warn if we've set an abiOverride for multi-lib packages.. 9630 // By definition, we need to copy both 32 and 64 bit libraries for 9631 // such packages. 9632 if (pkg.cpuAbiOverride != null 9633 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9634 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9635 } 9636 9637 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9638 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9639 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9640 if (extractLibs) { 9641 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9642 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9643 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9644 useIsaSpecificSubdirs); 9645 } else { 9646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9647 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9648 } 9649 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9650 } 9651 9652 maybeThrowExceptionForMultiArchCopy( 9653 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9654 9655 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9656 if (extractLibs) { 9657 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9658 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9659 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9660 useIsaSpecificSubdirs); 9661 } else { 9662 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9663 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9664 } 9665 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9666 } 9667 9668 maybeThrowExceptionForMultiArchCopy( 9669 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9670 9671 if (abi64 >= 0) { 9672 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9673 } 9674 9675 if (abi32 >= 0) { 9676 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9677 if (abi64 >= 0) { 9678 if (pkg.use32bitAbi) { 9679 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9680 pkg.applicationInfo.primaryCpuAbi = abi; 9681 } else { 9682 pkg.applicationInfo.secondaryCpuAbi = abi; 9683 } 9684 } else { 9685 pkg.applicationInfo.primaryCpuAbi = abi; 9686 } 9687 } 9688 9689 } else { 9690 String[] abiList = (cpuAbiOverride != null) ? 9691 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9692 9693 // Enable gross and lame hacks for apps that are built with old 9694 // SDK tools. We must scan their APKs for renderscript bitcode and 9695 // not launch them if it's present. Don't bother checking on devices 9696 // that don't have 64 bit support. 9697 boolean needsRenderScriptOverride = false; 9698 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9699 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9700 abiList = Build.SUPPORTED_32_BIT_ABIS; 9701 needsRenderScriptOverride = true; 9702 } 9703 9704 final int copyRet; 9705 if (extractLibs) { 9706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9707 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9708 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9709 } else { 9710 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9711 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9712 } 9713 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9714 9715 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9716 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9717 "Error unpackaging native libs for app, errorCode=" + copyRet); 9718 } 9719 9720 if (copyRet >= 0) { 9721 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9722 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9723 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9724 } else if (needsRenderScriptOverride) { 9725 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9726 } 9727 } 9728 } catch (IOException ioe) { 9729 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9730 } finally { 9731 IoUtils.closeQuietly(handle); 9732 } 9733 9734 // Now that we've calculated the ABIs and determined if it's an internal app, 9735 // we will go ahead and populate the nativeLibraryPath. 9736 setNativeLibraryPaths(pkg, appLib32InstallDir); 9737 } 9738 9739 /** 9740 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9741 * i.e, so that all packages can be run inside a single process if required. 9742 * 9743 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9744 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9745 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9746 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9747 * updating a package that belongs to a shared user. 9748 * 9749 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9750 * adds unnecessary complexity. 9751 */ 9752 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9753 PackageParser.Package scannedPackage) { 9754 String requiredInstructionSet = null; 9755 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9756 requiredInstructionSet = VMRuntime.getInstructionSet( 9757 scannedPackage.applicationInfo.primaryCpuAbi); 9758 } 9759 9760 PackageSetting requirer = null; 9761 for (PackageSetting ps : packagesForUser) { 9762 // If packagesForUser contains scannedPackage, we skip it. This will happen 9763 // when scannedPackage is an update of an existing package. Without this check, 9764 // we will never be able to change the ABI of any package belonging to a shared 9765 // user, even if it's compatible with other packages. 9766 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9767 if (ps.primaryCpuAbiString == null) { 9768 continue; 9769 } 9770 9771 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9772 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9773 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9774 // this but there's not much we can do. 9775 String errorMessage = "Instruction set mismatch, " 9776 + ((requirer == null) ? "[caller]" : requirer) 9777 + " requires " + requiredInstructionSet + " whereas " + ps 9778 + " requires " + instructionSet; 9779 Slog.w(TAG, errorMessage); 9780 } 9781 9782 if (requiredInstructionSet == null) { 9783 requiredInstructionSet = instructionSet; 9784 requirer = ps; 9785 } 9786 } 9787 } 9788 9789 if (requiredInstructionSet != null) { 9790 String adjustedAbi; 9791 if (requirer != null) { 9792 // requirer != null implies that either scannedPackage was null or that scannedPackage 9793 // did not require an ABI, in which case we have to adjust scannedPackage to match 9794 // the ABI of the set (which is the same as requirer's ABI) 9795 adjustedAbi = requirer.primaryCpuAbiString; 9796 if (scannedPackage != null) { 9797 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9798 } 9799 } else { 9800 // requirer == null implies that we're updating all ABIs in the set to 9801 // match scannedPackage. 9802 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9803 } 9804 9805 for (PackageSetting ps : packagesForUser) { 9806 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9807 if (ps.primaryCpuAbiString != null) { 9808 continue; 9809 } 9810 9811 ps.primaryCpuAbiString = adjustedAbi; 9812 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9813 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9814 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9815 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9816 + " (requirer=" 9817 + (requirer == null ? "null" : requirer.pkg.packageName) 9818 + ", scannedPackage=" 9819 + (scannedPackage != null ? scannedPackage.packageName : "null") 9820 + ")"); 9821 try { 9822 mInstaller.rmdex(ps.codePathString, 9823 getDexCodeInstructionSet(getPreferredInstructionSet())); 9824 } catch (InstallerException ignored) { 9825 } 9826 } 9827 } 9828 } 9829 } 9830 } 9831 9832 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9833 synchronized (mPackages) { 9834 mResolverReplaced = true; 9835 // Set up information for custom user intent resolution activity. 9836 mResolveActivity.applicationInfo = pkg.applicationInfo; 9837 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9838 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9839 mResolveActivity.processName = pkg.applicationInfo.packageName; 9840 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9841 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9842 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9843 mResolveActivity.theme = 0; 9844 mResolveActivity.exported = true; 9845 mResolveActivity.enabled = true; 9846 mResolveInfo.activityInfo = mResolveActivity; 9847 mResolveInfo.priority = 0; 9848 mResolveInfo.preferredOrder = 0; 9849 mResolveInfo.match = 0; 9850 mResolveComponentName = mCustomResolverComponentName; 9851 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9852 mResolveComponentName); 9853 } 9854 } 9855 9856 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9857 if (installerComponent == null) { 9858 if (DEBUG_EPHEMERAL) { 9859 Slog.d(TAG, "Clear ephemeral installer activity"); 9860 } 9861 mEphemeralInstallerActivity.applicationInfo = null; 9862 return; 9863 } 9864 9865 if (DEBUG_EPHEMERAL) { 9866 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9867 } 9868 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9869 // Set up information for ephemeral installer activity 9870 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9871 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9872 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9873 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9874 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9875 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9876 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9877 mEphemeralInstallerActivity.theme = 0; 9878 mEphemeralInstallerActivity.exported = true; 9879 mEphemeralInstallerActivity.enabled = true; 9880 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9881 mEphemeralInstallerInfo.priority = 0; 9882 mEphemeralInstallerInfo.preferredOrder = 1; 9883 mEphemeralInstallerInfo.isDefault = true; 9884 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9885 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9886 } 9887 9888 private static String calculateBundledApkRoot(final String codePathString) { 9889 final File codePath = new File(codePathString); 9890 final File codeRoot; 9891 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9892 codeRoot = Environment.getRootDirectory(); 9893 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9894 codeRoot = Environment.getOemDirectory(); 9895 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9896 codeRoot = Environment.getVendorDirectory(); 9897 } else { 9898 // Unrecognized code path; take its top real segment as the apk root: 9899 // e.g. /something/app/blah.apk => /something 9900 try { 9901 File f = codePath.getCanonicalFile(); 9902 File parent = f.getParentFile(); // non-null because codePath is a file 9903 File tmp; 9904 while ((tmp = parent.getParentFile()) != null) { 9905 f = parent; 9906 parent = tmp; 9907 } 9908 codeRoot = f; 9909 Slog.w(TAG, "Unrecognized code path " 9910 + codePath + " - using " + codeRoot); 9911 } catch (IOException e) { 9912 // Can't canonicalize the code path -- shenanigans? 9913 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9914 return Environment.getRootDirectory().getPath(); 9915 } 9916 } 9917 return codeRoot.getPath(); 9918 } 9919 9920 /** 9921 * Derive and set the location of native libraries for the given package, 9922 * which varies depending on where and how the package was installed. 9923 */ 9924 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9925 final ApplicationInfo info = pkg.applicationInfo; 9926 final String codePath = pkg.codePath; 9927 final File codeFile = new File(codePath); 9928 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9929 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9930 9931 info.nativeLibraryRootDir = null; 9932 info.nativeLibraryRootRequiresIsa = false; 9933 info.nativeLibraryDir = null; 9934 info.secondaryNativeLibraryDir = null; 9935 9936 if (isApkFile(codeFile)) { 9937 // Monolithic install 9938 if (bundledApp) { 9939 // If "/system/lib64/apkname" exists, assume that is the per-package 9940 // native library directory to use; otherwise use "/system/lib/apkname". 9941 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9942 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9943 getPrimaryInstructionSet(info)); 9944 9945 // This is a bundled system app so choose the path based on the ABI. 9946 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9947 // is just the default path. 9948 final String apkName = deriveCodePathName(codePath); 9949 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9950 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9951 apkName).getAbsolutePath(); 9952 9953 if (info.secondaryCpuAbi != null) { 9954 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9955 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9956 secondaryLibDir, apkName).getAbsolutePath(); 9957 } 9958 } else if (asecApp) { 9959 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9960 .getAbsolutePath(); 9961 } else { 9962 final String apkName = deriveCodePathName(codePath); 9963 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9964 .getAbsolutePath(); 9965 } 9966 9967 info.nativeLibraryRootRequiresIsa = false; 9968 info.nativeLibraryDir = info.nativeLibraryRootDir; 9969 } else { 9970 // Cluster install 9971 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9972 info.nativeLibraryRootRequiresIsa = true; 9973 9974 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9975 getPrimaryInstructionSet(info)).getAbsolutePath(); 9976 9977 if (info.secondaryCpuAbi != null) { 9978 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9979 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9980 } 9981 } 9982 } 9983 9984 /** 9985 * Calculate the abis and roots for a bundled app. These can uniquely 9986 * be determined from the contents of the system partition, i.e whether 9987 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9988 * of this information, and instead assume that the system was built 9989 * sensibly. 9990 */ 9991 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9992 PackageSetting pkgSetting) { 9993 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9994 9995 // If "/system/lib64/apkname" exists, assume that is the per-package 9996 // native library directory to use; otherwise use "/system/lib/apkname". 9997 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9998 setBundledAppAbi(pkg, apkRoot, apkName); 9999 // pkgSetting might be null during rescan following uninstall of updates 10000 // to a bundled app, so accommodate that possibility. The settings in 10001 // that case will be established later from the parsed package. 10002 // 10003 // If the settings aren't null, sync them up with what we've just derived. 10004 // note that apkRoot isn't stored in the package settings. 10005 if (pkgSetting != null) { 10006 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10007 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10008 } 10009 } 10010 10011 /** 10012 * Deduces the ABI of a bundled app and sets the relevant fields on the 10013 * parsed pkg object. 10014 * 10015 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10016 * under which system libraries are installed. 10017 * @param apkName the name of the installed package. 10018 */ 10019 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10020 final File codeFile = new File(pkg.codePath); 10021 10022 final boolean has64BitLibs; 10023 final boolean has32BitLibs; 10024 if (isApkFile(codeFile)) { 10025 // Monolithic install 10026 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10027 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10028 } else { 10029 // Cluster install 10030 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10031 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10032 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10033 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10034 has64BitLibs = (new File(rootDir, isa)).exists(); 10035 } else { 10036 has64BitLibs = false; 10037 } 10038 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10039 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10040 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10041 has32BitLibs = (new File(rootDir, isa)).exists(); 10042 } else { 10043 has32BitLibs = false; 10044 } 10045 } 10046 10047 if (has64BitLibs && !has32BitLibs) { 10048 // The package has 64 bit libs, but not 32 bit libs. Its primary 10049 // ABI should be 64 bit. We can safely assume here that the bundled 10050 // native libraries correspond to the most preferred ABI in the list. 10051 10052 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10053 pkg.applicationInfo.secondaryCpuAbi = null; 10054 } else if (has32BitLibs && !has64BitLibs) { 10055 // The package has 32 bit libs but not 64 bit libs. Its primary 10056 // ABI should be 32 bit. 10057 10058 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10059 pkg.applicationInfo.secondaryCpuAbi = null; 10060 } else if (has32BitLibs && has64BitLibs) { 10061 // The application has both 64 and 32 bit bundled libraries. We check 10062 // here that the app declares multiArch support, and warn if it doesn't. 10063 // 10064 // We will be lenient here and record both ABIs. The primary will be the 10065 // ABI that's higher on the list, i.e, a device that's configured to prefer 10066 // 64 bit apps will see a 64 bit primary ABI, 10067 10068 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10069 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10070 } 10071 10072 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10073 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10074 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10075 } else { 10076 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10077 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10078 } 10079 } else { 10080 pkg.applicationInfo.primaryCpuAbi = null; 10081 pkg.applicationInfo.secondaryCpuAbi = null; 10082 } 10083 } 10084 10085 private void killApplication(String pkgName, int appId, String reason) { 10086 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10087 } 10088 10089 private void killApplication(String pkgName, int appId, int userId, String reason) { 10090 // Request the ActivityManager to kill the process(only for existing packages) 10091 // so that we do not end up in a confused state while the user is still using the older 10092 // version of the application while the new one gets installed. 10093 final long token = Binder.clearCallingIdentity(); 10094 try { 10095 IActivityManager am = ActivityManager.getService(); 10096 if (am != null) { 10097 try { 10098 am.killApplication(pkgName, appId, userId, reason); 10099 } catch (RemoteException e) { 10100 } 10101 } 10102 } finally { 10103 Binder.restoreCallingIdentity(token); 10104 } 10105 } 10106 10107 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10108 // Remove the parent package setting 10109 PackageSetting ps = (PackageSetting) pkg.mExtras; 10110 if (ps != null) { 10111 removePackageLI(ps, chatty); 10112 } 10113 // Remove the child package setting 10114 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10115 for (int i = 0; i < childCount; i++) { 10116 PackageParser.Package childPkg = pkg.childPackages.get(i); 10117 ps = (PackageSetting) childPkg.mExtras; 10118 if (ps != null) { 10119 removePackageLI(ps, chatty); 10120 } 10121 } 10122 } 10123 10124 void removePackageLI(PackageSetting ps, boolean chatty) { 10125 if (DEBUG_INSTALL) { 10126 if (chatty) 10127 Log.d(TAG, "Removing package " + ps.name); 10128 } 10129 10130 // writer 10131 synchronized (mPackages) { 10132 mPackages.remove(ps.name); 10133 final PackageParser.Package pkg = ps.pkg; 10134 if (pkg != null) { 10135 cleanPackageDataStructuresLILPw(pkg, chatty); 10136 } 10137 } 10138 } 10139 10140 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10141 if (DEBUG_INSTALL) { 10142 if (chatty) 10143 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10144 } 10145 10146 // writer 10147 synchronized (mPackages) { 10148 // Remove the parent package 10149 mPackages.remove(pkg.applicationInfo.packageName); 10150 cleanPackageDataStructuresLILPw(pkg, chatty); 10151 10152 // Remove the child packages 10153 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10154 for (int i = 0; i < childCount; i++) { 10155 PackageParser.Package childPkg = pkg.childPackages.get(i); 10156 mPackages.remove(childPkg.applicationInfo.packageName); 10157 cleanPackageDataStructuresLILPw(childPkg, chatty); 10158 } 10159 } 10160 } 10161 10162 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10163 int N = pkg.providers.size(); 10164 StringBuilder r = null; 10165 int i; 10166 for (i=0; i<N; i++) { 10167 PackageParser.Provider p = pkg.providers.get(i); 10168 mProviders.removeProvider(p); 10169 if (p.info.authority == null) { 10170 10171 /* There was another ContentProvider with this authority when 10172 * this app was installed so this authority is null, 10173 * Ignore it as we don't have to unregister the provider. 10174 */ 10175 continue; 10176 } 10177 String names[] = p.info.authority.split(";"); 10178 for (int j = 0; j < names.length; j++) { 10179 if (mProvidersByAuthority.get(names[j]) == p) { 10180 mProvidersByAuthority.remove(names[j]); 10181 if (DEBUG_REMOVE) { 10182 if (chatty) 10183 Log.d(TAG, "Unregistered content provider: " + names[j] 10184 + ", className = " + p.info.name + ", isSyncable = " 10185 + p.info.isSyncable); 10186 } 10187 } 10188 } 10189 if (DEBUG_REMOVE && chatty) { 10190 if (r == null) { 10191 r = new StringBuilder(256); 10192 } else { 10193 r.append(' '); 10194 } 10195 r.append(p.info.name); 10196 } 10197 } 10198 if (r != null) { 10199 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10200 } 10201 10202 N = pkg.services.size(); 10203 r = null; 10204 for (i=0; i<N; i++) { 10205 PackageParser.Service s = pkg.services.get(i); 10206 mServices.removeService(s); 10207 if (chatty) { 10208 if (r == null) { 10209 r = new StringBuilder(256); 10210 } else { 10211 r.append(' '); 10212 } 10213 r.append(s.info.name); 10214 } 10215 } 10216 if (r != null) { 10217 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10218 } 10219 10220 N = pkg.receivers.size(); 10221 r = null; 10222 for (i=0; i<N; i++) { 10223 PackageParser.Activity a = pkg.receivers.get(i); 10224 mReceivers.removeActivity(a, "receiver"); 10225 if (DEBUG_REMOVE && chatty) { 10226 if (r == null) { 10227 r = new StringBuilder(256); 10228 } else { 10229 r.append(' '); 10230 } 10231 r.append(a.info.name); 10232 } 10233 } 10234 if (r != null) { 10235 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10236 } 10237 10238 N = pkg.activities.size(); 10239 r = null; 10240 for (i=0; i<N; i++) { 10241 PackageParser.Activity a = pkg.activities.get(i); 10242 mActivities.removeActivity(a, "activity"); 10243 if (DEBUG_REMOVE && chatty) { 10244 if (r == null) { 10245 r = new StringBuilder(256); 10246 } else { 10247 r.append(' '); 10248 } 10249 r.append(a.info.name); 10250 } 10251 } 10252 if (r != null) { 10253 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10254 } 10255 10256 N = pkg.permissions.size(); 10257 r = null; 10258 for (i=0; i<N; i++) { 10259 PackageParser.Permission p = pkg.permissions.get(i); 10260 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10261 if (bp == null) { 10262 bp = mSettings.mPermissionTrees.get(p.info.name); 10263 } 10264 if (bp != null && bp.perm == p) { 10265 bp.perm = null; 10266 if (DEBUG_REMOVE && chatty) { 10267 if (r == null) { 10268 r = new StringBuilder(256); 10269 } else { 10270 r.append(' '); 10271 } 10272 r.append(p.info.name); 10273 } 10274 } 10275 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10276 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10277 if (appOpPkgs != null) { 10278 appOpPkgs.remove(pkg.packageName); 10279 } 10280 } 10281 } 10282 if (r != null) { 10283 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10284 } 10285 10286 N = pkg.requestedPermissions.size(); 10287 r = null; 10288 for (i=0; i<N; i++) { 10289 String perm = pkg.requestedPermissions.get(i); 10290 BasePermission bp = mSettings.mPermissions.get(perm); 10291 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10292 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10293 if (appOpPkgs != null) { 10294 appOpPkgs.remove(pkg.packageName); 10295 if (appOpPkgs.isEmpty()) { 10296 mAppOpPermissionPackages.remove(perm); 10297 } 10298 } 10299 } 10300 } 10301 if (r != null) { 10302 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10303 } 10304 10305 N = pkg.instrumentation.size(); 10306 r = null; 10307 for (i=0; i<N; i++) { 10308 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10309 mInstrumentation.remove(a.getComponentName()); 10310 if (DEBUG_REMOVE && chatty) { 10311 if (r == null) { 10312 r = new StringBuilder(256); 10313 } else { 10314 r.append(' '); 10315 } 10316 r.append(a.info.name); 10317 } 10318 } 10319 if (r != null) { 10320 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10321 } 10322 10323 r = null; 10324 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10325 // Only system apps can hold shared libraries. 10326 if (pkg.libraryNames != null) { 10327 for (i=0; i<pkg.libraryNames.size(); i++) { 10328 String name = pkg.libraryNames.get(i); 10329 SharedLibraryEntry cur = mSharedLibraries.get(name); 10330 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10331 mSharedLibraries.remove(name); 10332 if (DEBUG_REMOVE && chatty) { 10333 if (r == null) { 10334 r = new StringBuilder(256); 10335 } else { 10336 r.append(' '); 10337 } 10338 r.append(name); 10339 } 10340 } 10341 } 10342 } 10343 } 10344 if (r != null) { 10345 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10346 } 10347 } 10348 10349 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10350 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10351 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10352 return true; 10353 } 10354 } 10355 return false; 10356 } 10357 10358 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10359 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10360 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10361 10362 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10363 // Update the parent permissions 10364 updatePermissionsLPw(pkg.packageName, pkg, flags); 10365 // Update the child permissions 10366 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10367 for (int i = 0; i < childCount; i++) { 10368 PackageParser.Package childPkg = pkg.childPackages.get(i); 10369 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10370 } 10371 } 10372 10373 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10374 int flags) { 10375 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10376 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10377 } 10378 10379 private void updatePermissionsLPw(String changingPkg, 10380 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10381 // Make sure there are no dangling permission trees. 10382 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10383 while (it.hasNext()) { 10384 final BasePermission bp = it.next(); 10385 if (bp.packageSetting == null) { 10386 // We may not yet have parsed the package, so just see if 10387 // we still know about its settings. 10388 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10389 } 10390 if (bp.packageSetting == null) { 10391 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10392 + " from package " + bp.sourcePackage); 10393 it.remove(); 10394 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10395 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10396 Slog.i(TAG, "Removing old permission tree: " + bp.name 10397 + " from package " + bp.sourcePackage); 10398 flags |= UPDATE_PERMISSIONS_ALL; 10399 it.remove(); 10400 } 10401 } 10402 } 10403 10404 // Make sure all dynamic permissions have been assigned to a package, 10405 // and make sure there are no dangling permissions. 10406 it = mSettings.mPermissions.values().iterator(); 10407 while (it.hasNext()) { 10408 final BasePermission bp = it.next(); 10409 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10410 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10411 + bp.name + " pkg=" + bp.sourcePackage 10412 + " info=" + bp.pendingInfo); 10413 if (bp.packageSetting == null && bp.pendingInfo != null) { 10414 final BasePermission tree = findPermissionTreeLP(bp.name); 10415 if (tree != null && tree.perm != null) { 10416 bp.packageSetting = tree.packageSetting; 10417 bp.perm = new PackageParser.Permission(tree.perm.owner, 10418 new PermissionInfo(bp.pendingInfo)); 10419 bp.perm.info.packageName = tree.perm.info.packageName; 10420 bp.perm.info.name = bp.name; 10421 bp.uid = tree.uid; 10422 } 10423 } 10424 } 10425 if (bp.packageSetting == null) { 10426 // We may not yet have parsed the package, so just see if 10427 // we still know about its settings. 10428 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10429 } 10430 if (bp.packageSetting == null) { 10431 Slog.w(TAG, "Removing dangling permission: " + bp.name 10432 + " from package " + bp.sourcePackage); 10433 it.remove(); 10434 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10435 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10436 Slog.i(TAG, "Removing old permission: " + bp.name 10437 + " from package " + bp.sourcePackage); 10438 flags |= UPDATE_PERMISSIONS_ALL; 10439 it.remove(); 10440 } 10441 } 10442 } 10443 10444 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10445 // Now update the permissions for all packages, in particular 10446 // replace the granted permissions of the system packages. 10447 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10448 for (PackageParser.Package pkg : mPackages.values()) { 10449 if (pkg != pkgInfo) { 10450 // Only replace for packages on requested volume 10451 final String volumeUuid = getVolumeUuidForPackage(pkg); 10452 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10453 && Objects.equals(replaceVolumeUuid, volumeUuid); 10454 grantPermissionsLPw(pkg, replace, changingPkg); 10455 } 10456 } 10457 } 10458 10459 if (pkgInfo != null) { 10460 // Only replace for packages on requested volume 10461 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10462 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10463 && Objects.equals(replaceVolumeUuid, volumeUuid); 10464 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10465 } 10466 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10467 } 10468 10469 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10470 String packageOfInterest) { 10471 // IMPORTANT: There are two types of permissions: install and runtime. 10472 // Install time permissions are granted when the app is installed to 10473 // all device users and users added in the future. Runtime permissions 10474 // are granted at runtime explicitly to specific users. Normal and signature 10475 // protected permissions are install time permissions. Dangerous permissions 10476 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10477 // otherwise they are runtime permissions. This function does not manage 10478 // runtime permissions except for the case an app targeting Lollipop MR1 10479 // being upgraded to target a newer SDK, in which case dangerous permissions 10480 // are transformed from install time to runtime ones. 10481 10482 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10483 if (ps == null) { 10484 return; 10485 } 10486 10487 PermissionsState permissionsState = ps.getPermissionsState(); 10488 PermissionsState origPermissions = permissionsState; 10489 10490 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10491 10492 boolean runtimePermissionsRevoked = false; 10493 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10494 10495 boolean changedInstallPermission = false; 10496 10497 if (replace) { 10498 ps.installPermissionsFixed = false; 10499 if (!ps.isSharedUser()) { 10500 origPermissions = new PermissionsState(permissionsState); 10501 permissionsState.reset(); 10502 } else { 10503 // We need to know only about runtime permission changes since the 10504 // calling code always writes the install permissions state but 10505 // the runtime ones are written only if changed. The only cases of 10506 // changed runtime permissions here are promotion of an install to 10507 // runtime and revocation of a runtime from a shared user. 10508 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10509 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10510 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10511 runtimePermissionsRevoked = true; 10512 } 10513 } 10514 } 10515 10516 permissionsState.setGlobalGids(mGlobalGids); 10517 10518 final int N = pkg.requestedPermissions.size(); 10519 for (int i=0; i<N; i++) { 10520 final String name = pkg.requestedPermissions.get(i); 10521 final BasePermission bp = mSettings.mPermissions.get(name); 10522 10523 if (DEBUG_INSTALL) { 10524 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10525 } 10526 10527 if (bp == null || bp.packageSetting == null) { 10528 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10529 Slog.w(TAG, "Unknown permission " + name 10530 + " in package " + pkg.packageName); 10531 } 10532 continue; 10533 } 10534 10535 10536 // Limit ephemeral apps to ephemeral allowed permissions. 10537 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10538 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10539 + pkg.packageName); 10540 continue; 10541 } 10542 10543 final String perm = bp.name; 10544 boolean allowedSig = false; 10545 int grant = GRANT_DENIED; 10546 10547 // Keep track of app op permissions. 10548 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10549 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10550 if (pkgs == null) { 10551 pkgs = new ArraySet<>(); 10552 mAppOpPermissionPackages.put(bp.name, pkgs); 10553 } 10554 pkgs.add(pkg.packageName); 10555 } 10556 10557 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10558 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10559 >= Build.VERSION_CODES.M; 10560 switch (level) { 10561 case PermissionInfo.PROTECTION_NORMAL: { 10562 // For all apps normal permissions are install time ones. 10563 grant = GRANT_INSTALL; 10564 } break; 10565 10566 case PermissionInfo.PROTECTION_DANGEROUS: { 10567 // If a permission review is required for legacy apps we represent 10568 // their permissions as always granted runtime ones since we need 10569 // to keep the review required permission flag per user while an 10570 // install permission's state is shared across all users. 10571 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10572 // For legacy apps dangerous permissions are install time ones. 10573 grant = GRANT_INSTALL; 10574 } else if (origPermissions.hasInstallPermission(bp.name)) { 10575 // For legacy apps that became modern, install becomes runtime. 10576 grant = GRANT_UPGRADE; 10577 } else if (mPromoteSystemApps 10578 && isSystemApp(ps) 10579 && mExistingSystemPackages.contains(ps.name)) { 10580 // For legacy system apps, install becomes runtime. 10581 // We cannot check hasInstallPermission() for system apps since those 10582 // permissions were granted implicitly and not persisted pre-M. 10583 grant = GRANT_UPGRADE; 10584 } else { 10585 // For modern apps keep runtime permissions unchanged. 10586 grant = GRANT_RUNTIME; 10587 } 10588 } break; 10589 10590 case PermissionInfo.PROTECTION_SIGNATURE: { 10591 // For all apps signature permissions are install time ones. 10592 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10593 if (allowedSig) { 10594 grant = GRANT_INSTALL; 10595 } 10596 } break; 10597 } 10598 10599 if (DEBUG_INSTALL) { 10600 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10601 } 10602 10603 if (grant != GRANT_DENIED) { 10604 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10605 // If this is an existing, non-system package, then 10606 // we can't add any new permissions to it. 10607 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10608 // Except... if this is a permission that was added 10609 // to the platform (note: need to only do this when 10610 // updating the platform). 10611 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10612 grant = GRANT_DENIED; 10613 } 10614 } 10615 } 10616 10617 switch (grant) { 10618 case GRANT_INSTALL: { 10619 // Revoke this as runtime permission to handle the case of 10620 // a runtime permission being downgraded to an install one. 10621 // Also in permission review mode we keep dangerous permissions 10622 // for legacy apps 10623 for (int userId : UserManagerService.getInstance().getUserIds()) { 10624 if (origPermissions.getRuntimePermissionState( 10625 bp.name, userId) != null) { 10626 // Revoke the runtime permission and clear the flags. 10627 origPermissions.revokeRuntimePermission(bp, userId); 10628 origPermissions.updatePermissionFlags(bp, userId, 10629 PackageManager.MASK_PERMISSION_FLAGS, 0); 10630 // If we revoked a permission permission, we have to write. 10631 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10632 changedRuntimePermissionUserIds, userId); 10633 } 10634 } 10635 // Grant an install permission. 10636 if (permissionsState.grantInstallPermission(bp) != 10637 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10638 changedInstallPermission = true; 10639 } 10640 } break; 10641 10642 case GRANT_RUNTIME: { 10643 // Grant previously granted runtime permissions. 10644 for (int userId : UserManagerService.getInstance().getUserIds()) { 10645 PermissionState permissionState = origPermissions 10646 .getRuntimePermissionState(bp.name, userId); 10647 int flags = permissionState != null 10648 ? permissionState.getFlags() : 0; 10649 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10650 // Don't propagate the permission in a permission review mode if 10651 // the former was revoked, i.e. marked to not propagate on upgrade. 10652 // Note that in a permission review mode install permissions are 10653 // represented as constantly granted runtime ones since we need to 10654 // keep a per user state associated with the permission. Also the 10655 // revoke on upgrade flag is no longer applicable and is reset. 10656 final boolean revokeOnUpgrade = (flags & PackageManager 10657 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 10658 if (revokeOnUpgrade) { 10659 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 10660 // Since we changed the flags, we have to write. 10661 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10662 changedRuntimePermissionUserIds, userId); 10663 } 10664 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 10665 if (permissionsState.grantRuntimePermission(bp, userId) == 10666 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10667 // If we cannot put the permission as it was, 10668 // we have to write. 10669 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10670 changedRuntimePermissionUserIds, userId); 10671 } 10672 } 10673 10674 // If the app supports runtime permissions no need for a review. 10675 if (mPermissionReviewRequired 10676 && appSupportsRuntimePermissions 10677 && (flags & PackageManager 10678 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10679 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10680 // Since we changed the flags, we have to write. 10681 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10682 changedRuntimePermissionUserIds, userId); 10683 } 10684 } else if (mPermissionReviewRequired 10685 && !appSupportsRuntimePermissions) { 10686 // For legacy apps that need a permission review, every new 10687 // runtime permission is granted but it is pending a review. 10688 // We also need to review only platform defined runtime 10689 // permissions as these are the only ones the platform knows 10690 // how to disable the API to simulate revocation as legacy 10691 // apps don't expect to run with revoked permissions. 10692 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10693 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10694 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10695 // We changed the flags, hence have to write. 10696 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10697 changedRuntimePermissionUserIds, userId); 10698 } 10699 } 10700 if (permissionsState.grantRuntimePermission(bp, userId) 10701 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10702 // We changed the permission, hence have to write. 10703 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10704 changedRuntimePermissionUserIds, userId); 10705 } 10706 } 10707 // Propagate the permission flags. 10708 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10709 } 10710 } break; 10711 10712 case GRANT_UPGRADE: { 10713 // Grant runtime permissions for a previously held install permission. 10714 PermissionState permissionState = origPermissions 10715 .getInstallPermissionState(bp.name); 10716 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10717 10718 if (origPermissions.revokeInstallPermission(bp) 10719 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10720 // We will be transferring the permission flags, so clear them. 10721 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10722 PackageManager.MASK_PERMISSION_FLAGS, 0); 10723 changedInstallPermission = true; 10724 } 10725 10726 // If the permission is not to be promoted to runtime we ignore it and 10727 // also its other flags as they are not applicable to install permissions. 10728 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10729 for (int userId : currentUserIds) { 10730 if (permissionsState.grantRuntimePermission(bp, userId) != 10731 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10732 // Transfer the permission flags. 10733 permissionsState.updatePermissionFlags(bp, userId, 10734 flags, flags); 10735 // If we granted the permission, we have to write. 10736 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10737 changedRuntimePermissionUserIds, userId); 10738 } 10739 } 10740 } 10741 } break; 10742 10743 default: { 10744 if (packageOfInterest == null 10745 || packageOfInterest.equals(pkg.packageName)) { 10746 Slog.w(TAG, "Not granting permission " + perm 10747 + " to package " + pkg.packageName 10748 + " because it was previously installed without"); 10749 } 10750 } break; 10751 } 10752 } else { 10753 if (permissionsState.revokeInstallPermission(bp) != 10754 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10755 // Also drop the permission flags. 10756 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10757 PackageManager.MASK_PERMISSION_FLAGS, 0); 10758 changedInstallPermission = true; 10759 Slog.i(TAG, "Un-granting permission " + perm 10760 + " from package " + pkg.packageName 10761 + " (protectionLevel=" + bp.protectionLevel 10762 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10763 + ")"); 10764 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10765 // Don't print warning for app op permissions, since it is fine for them 10766 // not to be granted, there is a UI for the user to decide. 10767 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10768 Slog.w(TAG, "Not granting permission " + perm 10769 + " to package " + pkg.packageName 10770 + " (protectionLevel=" + bp.protectionLevel 10771 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10772 + ")"); 10773 } 10774 } 10775 } 10776 } 10777 10778 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10779 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10780 // This is the first that we have heard about this package, so the 10781 // permissions we have now selected are fixed until explicitly 10782 // changed. 10783 ps.installPermissionsFixed = true; 10784 } 10785 10786 // Persist the runtime permissions state for users with changes. If permissions 10787 // were revoked because no app in the shared user declares them we have to 10788 // write synchronously to avoid losing runtime permissions state. 10789 for (int userId : changedRuntimePermissionUserIds) { 10790 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10791 } 10792 } 10793 10794 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10795 boolean allowed = false; 10796 final int NP = PackageParser.NEW_PERMISSIONS.length; 10797 for (int ip=0; ip<NP; ip++) { 10798 final PackageParser.NewPermissionInfo npi 10799 = PackageParser.NEW_PERMISSIONS[ip]; 10800 if (npi.name.equals(perm) 10801 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10802 allowed = true; 10803 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10804 + pkg.packageName); 10805 break; 10806 } 10807 } 10808 return allowed; 10809 } 10810 10811 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10812 BasePermission bp, PermissionsState origPermissions) { 10813 boolean privilegedPermission = (bp.protectionLevel 10814 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10815 boolean privappPermissionsDisable = 10816 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10817 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10818 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10819 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10820 && !platformPackage && platformPermission) { 10821 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10822 .getPrivAppPermissions(pkg.packageName); 10823 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10824 if (!whitelisted) { 10825 Slog.w(TAG, "Privileged permission " + perm + " for package " 10826 + pkg.packageName + " - not in privapp-permissions whitelist"); 10827 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10828 return false; 10829 } 10830 } 10831 } 10832 boolean allowed = (compareSignatures( 10833 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10834 == PackageManager.SIGNATURE_MATCH) 10835 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10836 == PackageManager.SIGNATURE_MATCH); 10837 if (!allowed && privilegedPermission) { 10838 if (isSystemApp(pkg)) { 10839 // For updated system applications, a system permission 10840 // is granted only if it had been defined by the original application. 10841 if (pkg.isUpdatedSystemApp()) { 10842 final PackageSetting sysPs = mSettings 10843 .getDisabledSystemPkgLPr(pkg.packageName); 10844 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10845 // If the original was granted this permission, we take 10846 // that grant decision as read and propagate it to the 10847 // update. 10848 if (sysPs.isPrivileged()) { 10849 allowed = true; 10850 } 10851 } else { 10852 // The system apk may have been updated with an older 10853 // version of the one on the data partition, but which 10854 // granted a new system permission that it didn't have 10855 // before. In this case we do want to allow the app to 10856 // now get the new permission if the ancestral apk is 10857 // privileged to get it. 10858 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10859 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10860 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10861 allowed = true; 10862 break; 10863 } 10864 } 10865 } 10866 // Also if a privileged parent package on the system image or any of 10867 // its children requested a privileged permission, the updated child 10868 // packages can also get the permission. 10869 if (pkg.parentPackage != null) { 10870 final PackageSetting disabledSysParentPs = mSettings 10871 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10872 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10873 && disabledSysParentPs.isPrivileged()) { 10874 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10875 allowed = true; 10876 } else if (disabledSysParentPs.pkg.childPackages != null) { 10877 final int count = disabledSysParentPs.pkg.childPackages.size(); 10878 for (int i = 0; i < count; i++) { 10879 PackageParser.Package disabledSysChildPkg = 10880 disabledSysParentPs.pkg.childPackages.get(i); 10881 if (isPackageRequestingPermission(disabledSysChildPkg, 10882 perm)) { 10883 allowed = true; 10884 break; 10885 } 10886 } 10887 } 10888 } 10889 } 10890 } 10891 } else { 10892 allowed = isPrivilegedApp(pkg); 10893 } 10894 } 10895 } 10896 if (!allowed) { 10897 if (!allowed && (bp.protectionLevel 10898 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10899 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10900 // If this was a previously normal/dangerous permission that got moved 10901 // to a system permission as part of the runtime permission redesign, then 10902 // we still want to blindly grant it to old apps. 10903 allowed = true; 10904 } 10905 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10906 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10907 // If this permission is to be granted to the system installer and 10908 // this app is an installer, then it gets the permission. 10909 allowed = true; 10910 } 10911 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10912 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10913 // If this permission is to be granted to the system verifier and 10914 // this app is a verifier, then it gets the permission. 10915 allowed = true; 10916 } 10917 if (!allowed && (bp.protectionLevel 10918 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10919 && isSystemApp(pkg)) { 10920 // Any pre-installed system app is allowed to get this permission. 10921 allowed = true; 10922 } 10923 if (!allowed && (bp.protectionLevel 10924 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10925 // For development permissions, a development permission 10926 // is granted only if it was already granted. 10927 allowed = origPermissions.hasInstallPermission(perm); 10928 } 10929 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10930 && pkg.packageName.equals(mSetupWizardPackage)) { 10931 // If this permission is to be granted to the system setup wizard and 10932 // this app is a setup wizard, then it gets the permission. 10933 allowed = true; 10934 } 10935 } 10936 return allowed; 10937 } 10938 10939 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10940 final int permCount = pkg.requestedPermissions.size(); 10941 for (int j = 0; j < permCount; j++) { 10942 String requestedPermission = pkg.requestedPermissions.get(j); 10943 if (permission.equals(requestedPermission)) { 10944 return true; 10945 } 10946 } 10947 return false; 10948 } 10949 10950 final class ActivityIntentResolver 10951 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10952 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10953 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 10954 if (!sUserManager.exists(userId)) return null; 10955 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 10956 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 10957 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 10958 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 10959 isEphemeral, userId); 10960 } 10961 10962 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10963 int userId) { 10964 if (!sUserManager.exists(userId)) return null; 10965 mFlags = flags; 10966 return super.queryIntent(intent, resolvedType, 10967 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 10968 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 10969 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 10970 } 10971 10972 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10973 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10974 if (!sUserManager.exists(userId)) return null; 10975 if (packageActivities == null) { 10976 return null; 10977 } 10978 mFlags = flags; 10979 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10980 final boolean vislbleToEphemeral = 10981 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 10982 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 10983 final int N = packageActivities.size(); 10984 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10985 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10986 10987 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10988 for (int i = 0; i < N; ++i) { 10989 intentFilters = packageActivities.get(i).intents; 10990 if (intentFilters != null && intentFilters.size() > 0) { 10991 PackageParser.ActivityIntentInfo[] array = 10992 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10993 intentFilters.toArray(array); 10994 listCut.add(array); 10995 } 10996 } 10997 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 10998 vislbleToEphemeral, isEphemeral, listCut, userId); 10999 } 11000 11001 /** 11002 * Finds a privileged activity that matches the specified activity names. 11003 */ 11004 private PackageParser.Activity findMatchingActivity( 11005 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11006 for (PackageParser.Activity sysActivity : activityList) { 11007 if (sysActivity.info.name.equals(activityInfo.name)) { 11008 return sysActivity; 11009 } 11010 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11011 return sysActivity; 11012 } 11013 if (sysActivity.info.targetActivity != null) { 11014 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11015 return sysActivity; 11016 } 11017 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11018 return sysActivity; 11019 } 11020 } 11021 } 11022 return null; 11023 } 11024 11025 public class IterGenerator<E> { 11026 public Iterator<E> generate(ActivityIntentInfo info) { 11027 return null; 11028 } 11029 } 11030 11031 public class ActionIterGenerator extends IterGenerator<String> { 11032 @Override 11033 public Iterator<String> generate(ActivityIntentInfo info) { 11034 return info.actionsIterator(); 11035 } 11036 } 11037 11038 public class CategoriesIterGenerator extends IterGenerator<String> { 11039 @Override 11040 public Iterator<String> generate(ActivityIntentInfo info) { 11041 return info.categoriesIterator(); 11042 } 11043 } 11044 11045 public class SchemesIterGenerator extends IterGenerator<String> { 11046 @Override 11047 public Iterator<String> generate(ActivityIntentInfo info) { 11048 return info.schemesIterator(); 11049 } 11050 } 11051 11052 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11053 @Override 11054 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11055 return info.authoritiesIterator(); 11056 } 11057 } 11058 11059 /** 11060 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11061 * MODIFIED. Do not pass in a list that should not be changed. 11062 */ 11063 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11064 IterGenerator<T> generator, Iterator<T> searchIterator) { 11065 // loop through the set of actions; every one must be found in the intent filter 11066 while (searchIterator.hasNext()) { 11067 // we must have at least one filter in the list to consider a match 11068 if (intentList.size() == 0) { 11069 break; 11070 } 11071 11072 final T searchAction = searchIterator.next(); 11073 11074 // loop through the set of intent filters 11075 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11076 while (intentIter.hasNext()) { 11077 final ActivityIntentInfo intentInfo = intentIter.next(); 11078 boolean selectionFound = false; 11079 11080 // loop through the intent filter's selection criteria; at least one 11081 // of them must match the searched criteria 11082 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11083 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11084 final T intentSelection = intentSelectionIter.next(); 11085 if (intentSelection != null && intentSelection.equals(searchAction)) { 11086 selectionFound = true; 11087 break; 11088 } 11089 } 11090 11091 // the selection criteria wasn't found in this filter's set; this filter 11092 // is not a potential match 11093 if (!selectionFound) { 11094 intentIter.remove(); 11095 } 11096 } 11097 } 11098 } 11099 11100 private boolean isProtectedAction(ActivityIntentInfo filter) { 11101 final Iterator<String> actionsIter = filter.actionsIterator(); 11102 while (actionsIter != null && actionsIter.hasNext()) { 11103 final String filterAction = actionsIter.next(); 11104 if (PROTECTED_ACTIONS.contains(filterAction)) { 11105 return true; 11106 } 11107 } 11108 return false; 11109 } 11110 11111 /** 11112 * Adjusts the priority of the given intent filter according to policy. 11113 * <p> 11114 * <ul> 11115 * <li>The priority for non privileged applications is capped to '0'</li> 11116 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11117 * <li>The priority for unbundled updates to privileged applications is capped to the 11118 * priority defined on the system partition</li> 11119 * </ul> 11120 * <p> 11121 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11122 * allowed to obtain any priority on any action. 11123 */ 11124 private void adjustPriority( 11125 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11126 // nothing to do; priority is fine as-is 11127 if (intent.getPriority() <= 0) { 11128 return; 11129 } 11130 11131 final ActivityInfo activityInfo = intent.activity.info; 11132 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11133 11134 final boolean privilegedApp = 11135 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11136 if (!privilegedApp) { 11137 // non-privileged applications can never define a priority >0 11138 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11139 + " package: " + applicationInfo.packageName 11140 + " activity: " + intent.activity.className 11141 + " origPrio: " + intent.getPriority()); 11142 intent.setPriority(0); 11143 return; 11144 } 11145 11146 if (systemActivities == null) { 11147 // the system package is not disabled; we're parsing the system partition 11148 if (isProtectedAction(intent)) { 11149 if (mDeferProtectedFilters) { 11150 // We can't deal with these just yet. No component should ever obtain a 11151 // >0 priority for a protected actions, with ONE exception -- the setup 11152 // wizard. The setup wizard, however, cannot be known until we're able to 11153 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11154 // until all intent filters have been processed. Chicken, meet egg. 11155 // Let the filter temporarily have a high priority and rectify the 11156 // priorities after all system packages have been scanned. 11157 mProtectedFilters.add(intent); 11158 if (DEBUG_FILTERS) { 11159 Slog.i(TAG, "Protected action; save for later;" 11160 + " package: " + applicationInfo.packageName 11161 + " activity: " + intent.activity.className 11162 + " origPrio: " + intent.getPriority()); 11163 } 11164 return; 11165 } else { 11166 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11167 Slog.i(TAG, "No setup wizard;" 11168 + " All protected intents capped to priority 0"); 11169 } 11170 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11171 if (DEBUG_FILTERS) { 11172 Slog.i(TAG, "Found setup wizard;" 11173 + " allow priority " + intent.getPriority() + ";" 11174 + " package: " + intent.activity.info.packageName 11175 + " activity: " + intent.activity.className 11176 + " priority: " + intent.getPriority()); 11177 } 11178 // setup wizard gets whatever it wants 11179 return; 11180 } 11181 Slog.w(TAG, "Protected action; cap priority to 0;" 11182 + " package: " + intent.activity.info.packageName 11183 + " activity: " + intent.activity.className 11184 + " origPrio: " + intent.getPriority()); 11185 intent.setPriority(0); 11186 return; 11187 } 11188 } 11189 // privileged apps on the system image get whatever priority they request 11190 return; 11191 } 11192 11193 // privileged app unbundled update ... try to find the same activity 11194 final PackageParser.Activity foundActivity = 11195 findMatchingActivity(systemActivities, activityInfo); 11196 if (foundActivity == null) { 11197 // this is a new activity; it cannot obtain >0 priority 11198 if (DEBUG_FILTERS) { 11199 Slog.i(TAG, "New activity; cap priority to 0;" 11200 + " package: " + applicationInfo.packageName 11201 + " activity: " + intent.activity.className 11202 + " origPrio: " + intent.getPriority()); 11203 } 11204 intent.setPriority(0); 11205 return; 11206 } 11207 11208 // found activity, now check for filter equivalence 11209 11210 // a shallow copy is enough; we modify the list, not its contents 11211 final List<ActivityIntentInfo> intentListCopy = 11212 new ArrayList<>(foundActivity.intents); 11213 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11214 11215 // find matching action subsets 11216 final Iterator<String> actionsIterator = intent.actionsIterator(); 11217 if (actionsIterator != null) { 11218 getIntentListSubset( 11219 intentListCopy, new ActionIterGenerator(), actionsIterator); 11220 if (intentListCopy.size() == 0) { 11221 // no more intents to match; we're not equivalent 11222 if (DEBUG_FILTERS) { 11223 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11224 + " package: " + applicationInfo.packageName 11225 + " activity: " + intent.activity.className 11226 + " origPrio: " + intent.getPriority()); 11227 } 11228 intent.setPriority(0); 11229 return; 11230 } 11231 } 11232 11233 // find matching category subsets 11234 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11235 if (categoriesIterator != null) { 11236 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11237 categoriesIterator); 11238 if (intentListCopy.size() == 0) { 11239 // no more intents to match; we're not equivalent 11240 if (DEBUG_FILTERS) { 11241 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11242 + " package: " + applicationInfo.packageName 11243 + " activity: " + intent.activity.className 11244 + " origPrio: " + intent.getPriority()); 11245 } 11246 intent.setPriority(0); 11247 return; 11248 } 11249 } 11250 11251 // find matching schemes subsets 11252 final Iterator<String> schemesIterator = intent.schemesIterator(); 11253 if (schemesIterator != null) { 11254 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11255 schemesIterator); 11256 if (intentListCopy.size() == 0) { 11257 // no more intents to match; we're not equivalent 11258 if (DEBUG_FILTERS) { 11259 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11260 + " package: " + applicationInfo.packageName 11261 + " activity: " + intent.activity.className 11262 + " origPrio: " + intent.getPriority()); 11263 } 11264 intent.setPriority(0); 11265 return; 11266 } 11267 } 11268 11269 // find matching authorities subsets 11270 final Iterator<IntentFilter.AuthorityEntry> 11271 authoritiesIterator = intent.authoritiesIterator(); 11272 if (authoritiesIterator != null) { 11273 getIntentListSubset(intentListCopy, 11274 new AuthoritiesIterGenerator(), 11275 authoritiesIterator); 11276 if (intentListCopy.size() == 0) { 11277 // no more intents to match; we're not equivalent 11278 if (DEBUG_FILTERS) { 11279 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11280 + " package: " + applicationInfo.packageName 11281 + " activity: " + intent.activity.className 11282 + " origPrio: " + intent.getPriority()); 11283 } 11284 intent.setPriority(0); 11285 return; 11286 } 11287 } 11288 11289 // we found matching filter(s); app gets the max priority of all intents 11290 int cappedPriority = 0; 11291 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11292 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11293 } 11294 if (intent.getPriority() > cappedPriority) { 11295 if (DEBUG_FILTERS) { 11296 Slog.i(TAG, "Found matching filter(s);" 11297 + " cap priority to " + cappedPriority + ";" 11298 + " package: " + applicationInfo.packageName 11299 + " activity: " + intent.activity.className 11300 + " origPrio: " + intent.getPriority()); 11301 } 11302 intent.setPriority(cappedPriority); 11303 return; 11304 } 11305 // all this for nothing; the requested priority was <= what was on the system 11306 } 11307 11308 public final void addActivity(PackageParser.Activity a, String type) { 11309 mActivities.put(a.getComponentName(), a); 11310 if (DEBUG_SHOW_INFO) 11311 Log.v( 11312 TAG, " " + type + " " + 11313 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11314 if (DEBUG_SHOW_INFO) 11315 Log.v(TAG, " Class=" + a.info.name); 11316 final int NI = a.intents.size(); 11317 for (int j=0; j<NI; j++) { 11318 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11319 if ("activity".equals(type)) { 11320 final PackageSetting ps = 11321 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11322 final List<PackageParser.Activity> systemActivities = 11323 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11324 adjustPriority(systemActivities, intent); 11325 } 11326 if (DEBUG_SHOW_INFO) { 11327 Log.v(TAG, " IntentFilter:"); 11328 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11329 } 11330 if (!intent.debugCheck()) { 11331 Log.w(TAG, "==> For Activity " + a.info.name); 11332 } 11333 addFilter(intent); 11334 } 11335 } 11336 11337 public final void removeActivity(PackageParser.Activity a, String type) { 11338 mActivities.remove(a.getComponentName()); 11339 if (DEBUG_SHOW_INFO) { 11340 Log.v(TAG, " " + type + " " 11341 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11342 : a.info.name) + ":"); 11343 Log.v(TAG, " Class=" + a.info.name); 11344 } 11345 final int NI = a.intents.size(); 11346 for (int j=0; j<NI; j++) { 11347 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11348 if (DEBUG_SHOW_INFO) { 11349 Log.v(TAG, " IntentFilter:"); 11350 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11351 } 11352 removeFilter(intent); 11353 } 11354 } 11355 11356 @Override 11357 protected boolean allowFilterResult( 11358 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11359 ActivityInfo filterAi = filter.activity.info; 11360 for (int i=dest.size()-1; i>=0; i--) { 11361 ActivityInfo destAi = dest.get(i).activityInfo; 11362 if (destAi.name == filterAi.name 11363 && destAi.packageName == filterAi.packageName) { 11364 return false; 11365 } 11366 } 11367 return true; 11368 } 11369 11370 @Override 11371 protected ActivityIntentInfo[] newArray(int size) { 11372 return new ActivityIntentInfo[size]; 11373 } 11374 11375 @Override 11376 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11377 if (!sUserManager.exists(userId)) return true; 11378 PackageParser.Package p = filter.activity.owner; 11379 if (p != null) { 11380 PackageSetting ps = (PackageSetting)p.mExtras; 11381 if (ps != null) { 11382 // System apps are never considered stopped for purposes of 11383 // filtering, because there may be no way for the user to 11384 // actually re-launch them. 11385 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11386 && ps.getStopped(userId); 11387 } 11388 } 11389 return false; 11390 } 11391 11392 @Override 11393 protected boolean isPackageForFilter(String packageName, 11394 PackageParser.ActivityIntentInfo info) { 11395 return packageName.equals(info.activity.owner.packageName); 11396 } 11397 11398 @Override 11399 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11400 int match, int userId) { 11401 if (!sUserManager.exists(userId)) return null; 11402 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11403 return null; 11404 } 11405 final PackageParser.Activity activity = info.activity; 11406 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11407 if (ps == null) { 11408 return null; 11409 } 11410 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11411 ps.readUserState(userId), userId); 11412 if (ai == null) { 11413 return null; 11414 } 11415 final ResolveInfo res = new ResolveInfo(); 11416 res.activityInfo = ai; 11417 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11418 res.filter = info; 11419 } 11420 if (info != null) { 11421 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11422 } 11423 res.priority = info.getPriority(); 11424 res.preferredOrder = activity.owner.mPreferredOrder; 11425 //System.out.println("Result: " + res.activityInfo.className + 11426 // " = " + res.priority); 11427 res.match = match; 11428 res.isDefault = info.hasDefault; 11429 res.labelRes = info.labelRes; 11430 res.nonLocalizedLabel = info.nonLocalizedLabel; 11431 if (userNeedsBadging(userId)) { 11432 res.noResourceId = true; 11433 } else { 11434 res.icon = info.icon; 11435 } 11436 res.iconResourceId = info.icon; 11437 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11438 return res; 11439 } 11440 11441 @Override 11442 protected void sortResults(List<ResolveInfo> results) { 11443 Collections.sort(results, mResolvePrioritySorter); 11444 } 11445 11446 @Override 11447 protected void dumpFilter(PrintWriter out, String prefix, 11448 PackageParser.ActivityIntentInfo filter) { 11449 out.print(prefix); out.print( 11450 Integer.toHexString(System.identityHashCode(filter.activity))); 11451 out.print(' '); 11452 filter.activity.printComponentShortName(out); 11453 out.print(" filter "); 11454 out.println(Integer.toHexString(System.identityHashCode(filter))); 11455 } 11456 11457 @Override 11458 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11459 return filter.activity; 11460 } 11461 11462 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11463 PackageParser.Activity activity = (PackageParser.Activity)label; 11464 out.print(prefix); out.print( 11465 Integer.toHexString(System.identityHashCode(activity))); 11466 out.print(' '); 11467 activity.printComponentShortName(out); 11468 if (count > 1) { 11469 out.print(" ("); out.print(count); out.print(" filters)"); 11470 } 11471 out.println(); 11472 } 11473 11474 // Keys are String (activity class name), values are Activity. 11475 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11476 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11477 private int mFlags; 11478 } 11479 11480 private final class ServiceIntentResolver 11481 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11482 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11483 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11484 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11485 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11486 isEphemeral, userId); 11487 } 11488 11489 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11490 int userId) { 11491 if (!sUserManager.exists(userId)) return null; 11492 mFlags = flags; 11493 return super.queryIntent(intent, resolvedType, 11494 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11495 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11496 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11497 } 11498 11499 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11500 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11501 if (!sUserManager.exists(userId)) return null; 11502 if (packageServices == null) { 11503 return null; 11504 } 11505 mFlags = flags; 11506 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11507 final boolean vislbleToEphemeral = 11508 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11509 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11510 final int N = packageServices.size(); 11511 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11512 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11513 11514 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11515 for (int i = 0; i < N; ++i) { 11516 intentFilters = packageServices.get(i).intents; 11517 if (intentFilters != null && intentFilters.size() > 0) { 11518 PackageParser.ServiceIntentInfo[] array = 11519 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11520 intentFilters.toArray(array); 11521 listCut.add(array); 11522 } 11523 } 11524 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11525 vislbleToEphemeral, isEphemeral, listCut, userId); 11526 } 11527 11528 public final void addService(PackageParser.Service s) { 11529 mServices.put(s.getComponentName(), s); 11530 if (DEBUG_SHOW_INFO) { 11531 Log.v(TAG, " " 11532 + (s.info.nonLocalizedLabel != null 11533 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11534 Log.v(TAG, " Class=" + s.info.name); 11535 } 11536 final int NI = s.intents.size(); 11537 int j; 11538 for (j=0; j<NI; j++) { 11539 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11540 if (DEBUG_SHOW_INFO) { 11541 Log.v(TAG, " IntentFilter:"); 11542 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11543 } 11544 if (!intent.debugCheck()) { 11545 Log.w(TAG, "==> For Service " + s.info.name); 11546 } 11547 addFilter(intent); 11548 } 11549 } 11550 11551 public final void removeService(PackageParser.Service s) { 11552 mServices.remove(s.getComponentName()); 11553 if (DEBUG_SHOW_INFO) { 11554 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11555 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11556 Log.v(TAG, " Class=" + s.info.name); 11557 } 11558 final int NI = s.intents.size(); 11559 int j; 11560 for (j=0; j<NI; j++) { 11561 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11562 if (DEBUG_SHOW_INFO) { 11563 Log.v(TAG, " IntentFilter:"); 11564 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11565 } 11566 removeFilter(intent); 11567 } 11568 } 11569 11570 @Override 11571 protected boolean allowFilterResult( 11572 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11573 ServiceInfo filterSi = filter.service.info; 11574 for (int i=dest.size()-1; i>=0; i--) { 11575 ServiceInfo destAi = dest.get(i).serviceInfo; 11576 if (destAi.name == filterSi.name 11577 && destAi.packageName == filterSi.packageName) { 11578 return false; 11579 } 11580 } 11581 return true; 11582 } 11583 11584 @Override 11585 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11586 return new PackageParser.ServiceIntentInfo[size]; 11587 } 11588 11589 @Override 11590 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11591 if (!sUserManager.exists(userId)) return true; 11592 PackageParser.Package p = filter.service.owner; 11593 if (p != null) { 11594 PackageSetting ps = (PackageSetting)p.mExtras; 11595 if (ps != null) { 11596 // System apps are never considered stopped for purposes of 11597 // filtering, because there may be no way for the user to 11598 // actually re-launch them. 11599 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11600 && ps.getStopped(userId); 11601 } 11602 } 11603 return false; 11604 } 11605 11606 @Override 11607 protected boolean isPackageForFilter(String packageName, 11608 PackageParser.ServiceIntentInfo info) { 11609 return packageName.equals(info.service.owner.packageName); 11610 } 11611 11612 @Override 11613 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11614 int match, int userId) { 11615 if (!sUserManager.exists(userId)) return null; 11616 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11617 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11618 return null; 11619 } 11620 final PackageParser.Service service = info.service; 11621 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11622 if (ps == null) { 11623 return null; 11624 } 11625 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11626 ps.readUserState(userId), userId); 11627 if (si == null) { 11628 return null; 11629 } 11630 final ResolveInfo res = new ResolveInfo(); 11631 res.serviceInfo = si; 11632 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11633 res.filter = filter; 11634 } 11635 res.priority = info.getPriority(); 11636 res.preferredOrder = service.owner.mPreferredOrder; 11637 res.match = match; 11638 res.isDefault = info.hasDefault; 11639 res.labelRes = info.labelRes; 11640 res.nonLocalizedLabel = info.nonLocalizedLabel; 11641 res.icon = info.icon; 11642 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11643 return res; 11644 } 11645 11646 @Override 11647 protected void sortResults(List<ResolveInfo> results) { 11648 Collections.sort(results, mResolvePrioritySorter); 11649 } 11650 11651 @Override 11652 protected void dumpFilter(PrintWriter out, String prefix, 11653 PackageParser.ServiceIntentInfo filter) { 11654 out.print(prefix); out.print( 11655 Integer.toHexString(System.identityHashCode(filter.service))); 11656 out.print(' '); 11657 filter.service.printComponentShortName(out); 11658 out.print(" filter "); 11659 out.println(Integer.toHexString(System.identityHashCode(filter))); 11660 } 11661 11662 @Override 11663 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11664 return filter.service; 11665 } 11666 11667 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11668 PackageParser.Service service = (PackageParser.Service)label; 11669 out.print(prefix); out.print( 11670 Integer.toHexString(System.identityHashCode(service))); 11671 out.print(' '); 11672 service.printComponentShortName(out); 11673 if (count > 1) { 11674 out.print(" ("); out.print(count); out.print(" filters)"); 11675 } 11676 out.println(); 11677 } 11678 11679// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11680// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11681// final List<ResolveInfo> retList = Lists.newArrayList(); 11682// while (i.hasNext()) { 11683// final ResolveInfo resolveInfo = (ResolveInfo) i; 11684// if (isEnabledLP(resolveInfo.serviceInfo)) { 11685// retList.add(resolveInfo); 11686// } 11687// } 11688// return retList; 11689// } 11690 11691 // Keys are String (activity class name), values are Activity. 11692 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11693 = new ArrayMap<ComponentName, PackageParser.Service>(); 11694 private int mFlags; 11695 } 11696 11697 private final class ProviderIntentResolver 11698 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11699 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11700 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11701 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11702 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11703 isEphemeral, userId); 11704 } 11705 11706 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11707 int userId) { 11708 if (!sUserManager.exists(userId)) 11709 return null; 11710 mFlags = flags; 11711 return super.queryIntent(intent, resolvedType, 11712 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11713 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11714 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11715 } 11716 11717 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11718 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11719 if (!sUserManager.exists(userId)) 11720 return null; 11721 if (packageProviders == null) { 11722 return null; 11723 } 11724 mFlags = flags; 11725 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11726 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11727 final boolean vislbleToEphemeral = 11728 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11729 final int N = packageProviders.size(); 11730 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11731 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11732 11733 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11734 for (int i = 0; i < N; ++i) { 11735 intentFilters = packageProviders.get(i).intents; 11736 if (intentFilters != null && intentFilters.size() > 0) { 11737 PackageParser.ProviderIntentInfo[] array = 11738 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11739 intentFilters.toArray(array); 11740 listCut.add(array); 11741 } 11742 } 11743 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11744 vislbleToEphemeral, isEphemeral, listCut, userId); 11745 } 11746 11747 public final void addProvider(PackageParser.Provider p) { 11748 if (mProviders.containsKey(p.getComponentName())) { 11749 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11750 return; 11751 } 11752 11753 mProviders.put(p.getComponentName(), p); 11754 if (DEBUG_SHOW_INFO) { 11755 Log.v(TAG, " " 11756 + (p.info.nonLocalizedLabel != null 11757 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11758 Log.v(TAG, " Class=" + p.info.name); 11759 } 11760 final int NI = p.intents.size(); 11761 int j; 11762 for (j = 0; j < NI; j++) { 11763 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11764 if (DEBUG_SHOW_INFO) { 11765 Log.v(TAG, " IntentFilter:"); 11766 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11767 } 11768 if (!intent.debugCheck()) { 11769 Log.w(TAG, "==> For Provider " + p.info.name); 11770 } 11771 addFilter(intent); 11772 } 11773 } 11774 11775 public final void removeProvider(PackageParser.Provider p) { 11776 mProviders.remove(p.getComponentName()); 11777 if (DEBUG_SHOW_INFO) { 11778 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11779 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11780 Log.v(TAG, " Class=" + p.info.name); 11781 } 11782 final int NI = p.intents.size(); 11783 int j; 11784 for (j = 0; j < NI; j++) { 11785 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11786 if (DEBUG_SHOW_INFO) { 11787 Log.v(TAG, " IntentFilter:"); 11788 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11789 } 11790 removeFilter(intent); 11791 } 11792 } 11793 11794 @Override 11795 protected boolean allowFilterResult( 11796 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11797 ProviderInfo filterPi = filter.provider.info; 11798 for (int i = dest.size() - 1; i >= 0; i--) { 11799 ProviderInfo destPi = dest.get(i).providerInfo; 11800 if (destPi.name == filterPi.name 11801 && destPi.packageName == filterPi.packageName) { 11802 return false; 11803 } 11804 } 11805 return true; 11806 } 11807 11808 @Override 11809 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11810 return new PackageParser.ProviderIntentInfo[size]; 11811 } 11812 11813 @Override 11814 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11815 if (!sUserManager.exists(userId)) 11816 return true; 11817 PackageParser.Package p = filter.provider.owner; 11818 if (p != null) { 11819 PackageSetting ps = (PackageSetting) p.mExtras; 11820 if (ps != null) { 11821 // System apps are never considered stopped for purposes of 11822 // filtering, because there may be no way for the user to 11823 // actually re-launch them. 11824 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11825 && ps.getStopped(userId); 11826 } 11827 } 11828 return false; 11829 } 11830 11831 @Override 11832 protected boolean isPackageForFilter(String packageName, 11833 PackageParser.ProviderIntentInfo info) { 11834 return packageName.equals(info.provider.owner.packageName); 11835 } 11836 11837 @Override 11838 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11839 int match, int userId) { 11840 if (!sUserManager.exists(userId)) 11841 return null; 11842 final PackageParser.ProviderIntentInfo info = filter; 11843 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11844 return null; 11845 } 11846 final PackageParser.Provider provider = info.provider; 11847 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11848 if (ps == null) { 11849 return null; 11850 } 11851 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11852 ps.readUserState(userId), userId); 11853 if (pi == null) { 11854 return null; 11855 } 11856 final ResolveInfo res = new ResolveInfo(); 11857 res.providerInfo = pi; 11858 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11859 res.filter = filter; 11860 } 11861 res.priority = info.getPriority(); 11862 res.preferredOrder = provider.owner.mPreferredOrder; 11863 res.match = match; 11864 res.isDefault = info.hasDefault; 11865 res.labelRes = info.labelRes; 11866 res.nonLocalizedLabel = info.nonLocalizedLabel; 11867 res.icon = info.icon; 11868 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11869 return res; 11870 } 11871 11872 @Override 11873 protected void sortResults(List<ResolveInfo> results) { 11874 Collections.sort(results, mResolvePrioritySorter); 11875 } 11876 11877 @Override 11878 protected void dumpFilter(PrintWriter out, String prefix, 11879 PackageParser.ProviderIntentInfo filter) { 11880 out.print(prefix); 11881 out.print( 11882 Integer.toHexString(System.identityHashCode(filter.provider))); 11883 out.print(' '); 11884 filter.provider.printComponentShortName(out); 11885 out.print(" filter "); 11886 out.println(Integer.toHexString(System.identityHashCode(filter))); 11887 } 11888 11889 @Override 11890 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11891 return filter.provider; 11892 } 11893 11894 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11895 PackageParser.Provider provider = (PackageParser.Provider)label; 11896 out.print(prefix); out.print( 11897 Integer.toHexString(System.identityHashCode(provider))); 11898 out.print(' '); 11899 provider.printComponentShortName(out); 11900 if (count > 1) { 11901 out.print(" ("); out.print(count); out.print(" filters)"); 11902 } 11903 out.println(); 11904 } 11905 11906 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11907 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11908 private int mFlags; 11909 } 11910 11911 static final class EphemeralIntentResolver 11912 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11913 /** 11914 * The result that has the highest defined order. Ordering applies on a 11915 * per-package basis. Mapping is from package name to Pair of order and 11916 * EphemeralResolveInfo. 11917 * <p> 11918 * NOTE: This is implemented as a field variable for convenience and efficiency. 11919 * By having a field variable, we're able to track filter ordering as soon as 11920 * a non-zero order is defined. Otherwise, multiple loops across the result set 11921 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11922 * this needs to be contained entirely within {@link #filterResults()}. 11923 */ 11924 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11925 11926 @Override 11927 protected EphemeralResponse[] newArray(int size) { 11928 return new EphemeralResponse[size]; 11929 } 11930 11931 @Override 11932 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11933 return true; 11934 } 11935 11936 @Override 11937 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11938 int userId) { 11939 if (!sUserManager.exists(userId)) { 11940 return null; 11941 } 11942 final String packageName = responseObj.resolveInfo.getPackageName(); 11943 final Integer order = responseObj.getOrder(); 11944 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11945 mOrderResult.get(packageName); 11946 // ordering is enabled and this item's order isn't high enough 11947 if (lastOrderResult != null && lastOrderResult.first >= order) { 11948 return null; 11949 } 11950 final EphemeralResolveInfo res = responseObj.resolveInfo; 11951 if (order > 0) { 11952 // non-zero order, enable ordering 11953 mOrderResult.put(packageName, new Pair<>(order, res)); 11954 } 11955 return responseObj; 11956 } 11957 11958 @Override 11959 protected void filterResults(List<EphemeralResponse> results) { 11960 // only do work if ordering is enabled [most of the time it won't be] 11961 if (mOrderResult.size() == 0) { 11962 return; 11963 } 11964 int resultSize = results.size(); 11965 for (int i = 0; i < resultSize; i++) { 11966 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11967 final String packageName = info.getPackageName(); 11968 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11969 if (savedInfo == null) { 11970 // package doesn't having ordering 11971 continue; 11972 } 11973 if (savedInfo.second == info) { 11974 // circled back to the highest ordered item; remove from order list 11975 mOrderResult.remove(savedInfo); 11976 if (mOrderResult.size() == 0) { 11977 // no more ordered items 11978 break; 11979 } 11980 continue; 11981 } 11982 // item has a worse order, remove it from the result list 11983 results.remove(i); 11984 resultSize--; 11985 i--; 11986 } 11987 } 11988 } 11989 11990 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11991 new Comparator<ResolveInfo>() { 11992 public int compare(ResolveInfo r1, ResolveInfo r2) { 11993 int v1 = r1.priority; 11994 int v2 = r2.priority; 11995 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11996 if (v1 != v2) { 11997 return (v1 > v2) ? -1 : 1; 11998 } 11999 v1 = r1.preferredOrder; 12000 v2 = r2.preferredOrder; 12001 if (v1 != v2) { 12002 return (v1 > v2) ? -1 : 1; 12003 } 12004 if (r1.isDefault != r2.isDefault) { 12005 return r1.isDefault ? -1 : 1; 12006 } 12007 v1 = r1.match; 12008 v2 = r2.match; 12009 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12010 if (v1 != v2) { 12011 return (v1 > v2) ? -1 : 1; 12012 } 12013 if (r1.system != r2.system) { 12014 return r1.system ? -1 : 1; 12015 } 12016 if (r1.activityInfo != null) { 12017 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12018 } 12019 if (r1.serviceInfo != null) { 12020 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12021 } 12022 if (r1.providerInfo != null) { 12023 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12024 } 12025 return 0; 12026 } 12027 }; 12028 12029 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12030 new Comparator<ProviderInfo>() { 12031 public int compare(ProviderInfo p1, ProviderInfo p2) { 12032 final int v1 = p1.initOrder; 12033 final int v2 = p2.initOrder; 12034 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12035 } 12036 }; 12037 12038 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12039 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12040 final int[] userIds) { 12041 mHandler.post(new Runnable() { 12042 @Override 12043 public void run() { 12044 try { 12045 final IActivityManager am = ActivityManager.getService(); 12046 if (am == null) return; 12047 final int[] resolvedUserIds; 12048 if (userIds == null) { 12049 resolvedUserIds = am.getRunningUserIds(); 12050 } else { 12051 resolvedUserIds = userIds; 12052 } 12053 for (int id : resolvedUserIds) { 12054 final Intent intent = new Intent(action, 12055 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12056 if (extras != null) { 12057 intent.putExtras(extras); 12058 } 12059 if (targetPkg != null) { 12060 intent.setPackage(targetPkg); 12061 } 12062 // Modify the UID when posting to other users 12063 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12064 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12065 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12066 intent.putExtra(Intent.EXTRA_UID, uid); 12067 } 12068 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12069 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12070 if (DEBUG_BROADCASTS) { 12071 RuntimeException here = new RuntimeException("here"); 12072 here.fillInStackTrace(); 12073 Slog.d(TAG, "Sending to user " + id + ": " 12074 + intent.toShortString(false, true, false, false) 12075 + " " + intent.getExtras(), here); 12076 } 12077 am.broadcastIntent(null, intent, null, finishedReceiver, 12078 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12079 null, finishedReceiver != null, false, id); 12080 } 12081 } catch (RemoteException ex) { 12082 } 12083 } 12084 }); 12085 } 12086 12087 /** 12088 * Check if the external storage media is available. This is true if there 12089 * is a mounted external storage medium or if the external storage is 12090 * emulated. 12091 */ 12092 private boolean isExternalMediaAvailable() { 12093 return mMediaMounted || Environment.isExternalStorageEmulated(); 12094 } 12095 12096 @Override 12097 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12098 // writer 12099 synchronized (mPackages) { 12100 if (!isExternalMediaAvailable()) { 12101 // If the external storage is no longer mounted at this point, 12102 // the caller may not have been able to delete all of this 12103 // packages files and can not delete any more. Bail. 12104 return null; 12105 } 12106 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12107 if (lastPackage != null) { 12108 pkgs.remove(lastPackage); 12109 } 12110 if (pkgs.size() > 0) { 12111 return pkgs.get(0); 12112 } 12113 } 12114 return null; 12115 } 12116 12117 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12118 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12119 userId, andCode ? 1 : 0, packageName); 12120 if (mSystemReady) { 12121 msg.sendToTarget(); 12122 } else { 12123 if (mPostSystemReadyMessages == null) { 12124 mPostSystemReadyMessages = new ArrayList<>(); 12125 } 12126 mPostSystemReadyMessages.add(msg); 12127 } 12128 } 12129 12130 void startCleaningPackages() { 12131 // reader 12132 if (!isExternalMediaAvailable()) { 12133 return; 12134 } 12135 synchronized (mPackages) { 12136 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12137 return; 12138 } 12139 } 12140 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12141 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12142 IActivityManager am = ActivityManager.getService(); 12143 if (am != null) { 12144 try { 12145 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12146 UserHandle.USER_SYSTEM); 12147 } catch (RemoteException e) { 12148 } 12149 } 12150 } 12151 12152 @Override 12153 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12154 int installFlags, String installerPackageName, int userId) { 12155 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12156 12157 final int callingUid = Binder.getCallingUid(); 12158 enforceCrossUserPermission(callingUid, userId, 12159 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12160 12161 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12162 try { 12163 if (observer != null) { 12164 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12165 } 12166 } catch (RemoteException re) { 12167 } 12168 return; 12169 } 12170 12171 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12172 installFlags |= PackageManager.INSTALL_FROM_ADB; 12173 12174 } else { 12175 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12176 // about installerPackageName. 12177 12178 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12179 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12180 } 12181 12182 UserHandle user; 12183 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12184 user = UserHandle.ALL; 12185 } else { 12186 user = new UserHandle(userId); 12187 } 12188 12189 // Only system components can circumvent runtime permissions when installing. 12190 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12191 && mContext.checkCallingOrSelfPermission(Manifest.permission 12192 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12193 throw new SecurityException("You need the " 12194 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12195 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12196 } 12197 12198 final File originFile = new File(originPath); 12199 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12200 12201 final Message msg = mHandler.obtainMessage(INIT_COPY); 12202 final VerificationInfo verificationInfo = new VerificationInfo( 12203 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12204 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12205 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12206 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12207 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12208 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12209 msg.obj = params; 12210 12211 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12212 System.identityHashCode(msg.obj)); 12213 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12214 System.identityHashCode(msg.obj)); 12215 12216 mHandler.sendMessage(msg); 12217 } 12218 12219 12220 /** 12221 * Ensure that the install reason matches what we know about the package installer (e.g. whether 12222 * it is acting on behalf on an enterprise or the user). 12223 * 12224 * Note that the ordering of the conditionals in this method is important. The checks we perform 12225 * are as follows, in this order: 12226 * 12227 * 1) If the install is being performed by a system app, we can trust the app to have set the 12228 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 12229 * what it is. 12230 * 2) If the install is being performed by a device or profile owner app, the install reason 12231 * should be enterprise policy. However, we cannot be sure that the device or profile owner 12232 * set the install reason correctly. If the app targets an older SDK version where install 12233 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 12234 * unset or wrong. Thus, we force the install reason to be enterprise policy. 12235 * 3) In all other cases, the install is being performed by a regular app that is neither part 12236 * of the system nor a device or profile owner. We have no reason to believe that this app is 12237 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 12238 * set to enterprise policy and if so, change it to unknown instead. 12239 */ 12240 private int fixUpInstallReason(String installerPackageName, int installerUid, 12241 int installReason) { 12242 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 12243 == PERMISSION_GRANTED) { 12244 // If the install is being performed by a system app, we trust that app to have set the 12245 // install reason correctly. 12246 return installReason; 12247 } 12248 12249 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 12250 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 12251 if (dpm != null) { 12252 ComponentName owner = null; 12253 try { 12254 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 12255 if (owner == null) { 12256 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 12257 } 12258 } catch (RemoteException e) { 12259 } 12260 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 12261 // If the install is being performed by a device or profile owner, the install 12262 // reason should be enterprise policy. 12263 return PackageManager.INSTALL_REASON_POLICY; 12264 } 12265 } 12266 12267 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 12268 // If the install is being performed by a regular app (i.e. neither system app nor 12269 // device or profile owner), we have no reason to believe that the app is acting on 12270 // behalf of an enterprise. If the app set the install reason to enterprise policy, 12271 // change it to unknown instead. 12272 return PackageManager.INSTALL_REASON_UNKNOWN; 12273 } 12274 12275 // If the install is being performed by a regular app and the install reason was set to any 12276 // value but enterprise policy, leave the install reason unchanged. 12277 return installReason; 12278 } 12279 12280 void installStage(String packageName, File stagedDir, String stagedCid, 12281 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12282 String installerPackageName, int installerUid, UserHandle user, 12283 Certificate[][] certificates) { 12284 if (DEBUG_EPHEMERAL) { 12285 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12286 Slog.d(TAG, "Ephemeral install of " + packageName); 12287 } 12288 } 12289 final VerificationInfo verificationInfo = new VerificationInfo( 12290 sessionParams.originatingUri, sessionParams.referrerUri, 12291 sessionParams.originatingUid, installerUid); 12292 12293 final OriginInfo origin; 12294 if (stagedDir != null) { 12295 origin = OriginInfo.fromStagedFile(stagedDir); 12296 } else { 12297 origin = OriginInfo.fromStagedContainer(stagedCid); 12298 } 12299 12300 final Message msg = mHandler.obtainMessage(INIT_COPY); 12301 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 12302 sessionParams.installReason); 12303 final InstallParams params = new InstallParams(origin, null, observer, 12304 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12305 verificationInfo, user, sessionParams.abiOverride, 12306 sessionParams.grantedRuntimePermissions, certificates, installReason); 12307 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12308 msg.obj = params; 12309 12310 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12311 System.identityHashCode(msg.obj)); 12312 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12313 System.identityHashCode(msg.obj)); 12314 12315 mHandler.sendMessage(msg); 12316 } 12317 12318 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12319 int userId) { 12320 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12321 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12322 } 12323 12324 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12325 int appId, int... userIds) { 12326 if (ArrayUtils.isEmpty(userIds)) { 12327 return; 12328 } 12329 Bundle extras = new Bundle(1); 12330 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12331 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12332 12333 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12334 packageName, extras, 0, null, null, userIds); 12335 if (isSystem) { 12336 mHandler.post(() -> { 12337 for (int userId : userIds) { 12338 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12339 } 12340 } 12341 ); 12342 } 12343 } 12344 12345 /** 12346 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12347 * automatically without needing an explicit launch. 12348 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12349 */ 12350 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12351 // If user is not running, the app didn't miss any broadcast 12352 if (!mUserManagerInternal.isUserRunning(userId)) { 12353 return; 12354 } 12355 final IActivityManager am = ActivityManager.getService(); 12356 try { 12357 // Deliver LOCKED_BOOT_COMPLETED first 12358 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12359 .setPackage(packageName); 12360 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12361 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12362 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12363 12364 // Deliver BOOT_COMPLETED only if user is unlocked 12365 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12366 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12367 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12368 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12369 } 12370 } catch (RemoteException e) { 12371 throw e.rethrowFromSystemServer(); 12372 } 12373 } 12374 12375 @Override 12376 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12377 int userId) { 12378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12379 PackageSetting pkgSetting; 12380 final int uid = Binder.getCallingUid(); 12381 enforceCrossUserPermission(uid, userId, 12382 true /* requireFullPermission */, true /* checkShell */, 12383 "setApplicationHiddenSetting for user " + userId); 12384 12385 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12386 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12387 return false; 12388 } 12389 12390 long callingId = Binder.clearCallingIdentity(); 12391 try { 12392 boolean sendAdded = false; 12393 boolean sendRemoved = false; 12394 // writer 12395 synchronized (mPackages) { 12396 pkgSetting = mSettings.mPackages.get(packageName); 12397 if (pkgSetting == null) { 12398 return false; 12399 } 12400 // Do not allow "android" is being disabled 12401 if ("android".equals(packageName)) { 12402 Slog.w(TAG, "Cannot hide package: android"); 12403 return false; 12404 } 12405 // Only allow protected packages to hide themselves. 12406 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12407 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12408 Slog.w(TAG, "Not hiding protected package: " + packageName); 12409 return false; 12410 } 12411 12412 if (pkgSetting.getHidden(userId) != hidden) { 12413 pkgSetting.setHidden(hidden, userId); 12414 mSettings.writePackageRestrictionsLPr(userId); 12415 if (hidden) { 12416 sendRemoved = true; 12417 } else { 12418 sendAdded = true; 12419 } 12420 } 12421 } 12422 if (sendAdded) { 12423 sendPackageAddedForUser(packageName, pkgSetting, userId); 12424 return true; 12425 } 12426 if (sendRemoved) { 12427 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12428 "hiding pkg"); 12429 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12430 return true; 12431 } 12432 } finally { 12433 Binder.restoreCallingIdentity(callingId); 12434 } 12435 return false; 12436 } 12437 12438 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12439 int userId) { 12440 final PackageRemovedInfo info = new PackageRemovedInfo(); 12441 info.removedPackage = packageName; 12442 info.removedUsers = new int[] {userId}; 12443 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12444 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12445 } 12446 12447 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12448 if (pkgList.length > 0) { 12449 Bundle extras = new Bundle(1); 12450 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12451 12452 sendPackageBroadcast( 12453 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12454 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12455 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12456 new int[] {userId}); 12457 } 12458 } 12459 12460 /** 12461 * Returns true if application is not found or there was an error. Otherwise it returns 12462 * the hidden state of the package for the given user. 12463 */ 12464 @Override 12465 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12466 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12467 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12468 true /* requireFullPermission */, false /* checkShell */, 12469 "getApplicationHidden for user " + userId); 12470 PackageSetting pkgSetting; 12471 long callingId = Binder.clearCallingIdentity(); 12472 try { 12473 // writer 12474 synchronized (mPackages) { 12475 pkgSetting = mSettings.mPackages.get(packageName); 12476 if (pkgSetting == null) { 12477 return true; 12478 } 12479 return pkgSetting.getHidden(userId); 12480 } 12481 } finally { 12482 Binder.restoreCallingIdentity(callingId); 12483 } 12484 } 12485 12486 /** 12487 * @hide 12488 */ 12489 @Override 12490 public int installExistingPackageAsUser(String packageName, int userId, int installReason) { 12491 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12492 null); 12493 PackageSetting pkgSetting; 12494 final int uid = Binder.getCallingUid(); 12495 enforceCrossUserPermission(uid, userId, 12496 true /* requireFullPermission */, true /* checkShell */, 12497 "installExistingPackage for user " + userId); 12498 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12499 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12500 } 12501 12502 long callingId = Binder.clearCallingIdentity(); 12503 try { 12504 boolean installed = false; 12505 12506 // writer 12507 synchronized (mPackages) { 12508 pkgSetting = mSettings.mPackages.get(packageName); 12509 if (pkgSetting == null) { 12510 return PackageManager.INSTALL_FAILED_INVALID_URI; 12511 } 12512 if (!pkgSetting.getInstalled(userId)) { 12513 pkgSetting.setInstalled(true, userId); 12514 pkgSetting.setHidden(false, userId); 12515 pkgSetting.setInstallReason(installReason, userId); 12516 mSettings.writePackageRestrictionsLPr(userId); 12517 installed = true; 12518 } 12519 } 12520 12521 if (installed) { 12522 if (pkgSetting.pkg != null) { 12523 synchronized (mInstallLock) { 12524 // We don't need to freeze for a brand new install 12525 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12526 } 12527 } 12528 sendPackageAddedForUser(packageName, pkgSetting, userId); 12529 } 12530 } finally { 12531 Binder.restoreCallingIdentity(callingId); 12532 } 12533 12534 return PackageManager.INSTALL_SUCCEEDED; 12535 } 12536 12537 boolean isUserRestricted(int userId, String restrictionKey) { 12538 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12539 if (restrictions.getBoolean(restrictionKey, false)) { 12540 Log.w(TAG, "User is restricted: " + restrictionKey); 12541 return true; 12542 } 12543 return false; 12544 } 12545 12546 @Override 12547 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12548 int userId) { 12549 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12550 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12551 true /* requireFullPermission */, true /* checkShell */, 12552 "setPackagesSuspended for user " + userId); 12553 12554 if (ArrayUtils.isEmpty(packageNames)) { 12555 return packageNames; 12556 } 12557 12558 // List of package names for whom the suspended state has changed. 12559 List<String> changedPackages = new ArrayList<>(packageNames.length); 12560 // List of package names for whom the suspended state is not set as requested in this 12561 // method. 12562 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12563 long callingId = Binder.clearCallingIdentity(); 12564 try { 12565 for (int i = 0; i < packageNames.length; i++) { 12566 String packageName = packageNames[i]; 12567 boolean changed = false; 12568 final int appId; 12569 synchronized (mPackages) { 12570 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12571 if (pkgSetting == null) { 12572 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12573 + "\". Skipping suspending/un-suspending."); 12574 unactionedPackages.add(packageName); 12575 continue; 12576 } 12577 appId = pkgSetting.appId; 12578 if (pkgSetting.getSuspended(userId) != suspended) { 12579 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12580 unactionedPackages.add(packageName); 12581 continue; 12582 } 12583 pkgSetting.setSuspended(suspended, userId); 12584 mSettings.writePackageRestrictionsLPr(userId); 12585 changed = true; 12586 changedPackages.add(packageName); 12587 } 12588 } 12589 12590 if (changed && suspended) { 12591 killApplication(packageName, UserHandle.getUid(userId, appId), 12592 "suspending package"); 12593 } 12594 } 12595 } finally { 12596 Binder.restoreCallingIdentity(callingId); 12597 } 12598 12599 if (!changedPackages.isEmpty()) { 12600 sendPackagesSuspendedForUser(changedPackages.toArray( 12601 new String[changedPackages.size()]), userId, suspended); 12602 } 12603 12604 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12605 } 12606 12607 @Override 12608 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12609 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12610 true /* requireFullPermission */, false /* checkShell */, 12611 "isPackageSuspendedForUser for user " + userId); 12612 synchronized (mPackages) { 12613 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12614 if (pkgSetting == null) { 12615 throw new IllegalArgumentException("Unknown target package: " + packageName); 12616 } 12617 return pkgSetting.getSuspended(userId); 12618 } 12619 } 12620 12621 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12622 if (isPackageDeviceAdmin(packageName, userId)) { 12623 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12624 + "\": has an active device admin"); 12625 return false; 12626 } 12627 12628 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12629 if (packageName.equals(activeLauncherPackageName)) { 12630 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12631 + "\": contains the active launcher"); 12632 return false; 12633 } 12634 12635 if (packageName.equals(mRequiredInstallerPackage)) { 12636 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12637 + "\": required for package installation"); 12638 return false; 12639 } 12640 12641 if (packageName.equals(mRequiredUninstallerPackage)) { 12642 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12643 + "\": required for package uninstallation"); 12644 return false; 12645 } 12646 12647 if (packageName.equals(mRequiredVerifierPackage)) { 12648 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12649 + "\": required for package verification"); 12650 return false; 12651 } 12652 12653 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12654 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12655 + "\": is the default dialer"); 12656 return false; 12657 } 12658 12659 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12660 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12661 + "\": protected package"); 12662 return false; 12663 } 12664 12665 return true; 12666 } 12667 12668 private String getActiveLauncherPackageName(int userId) { 12669 Intent intent = new Intent(Intent.ACTION_MAIN); 12670 intent.addCategory(Intent.CATEGORY_HOME); 12671 ResolveInfo resolveInfo = resolveIntent( 12672 intent, 12673 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12674 PackageManager.MATCH_DEFAULT_ONLY, 12675 userId); 12676 12677 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12678 } 12679 12680 private String getDefaultDialerPackageName(int userId) { 12681 synchronized (mPackages) { 12682 return mSettings.getDefaultDialerPackageNameLPw(userId); 12683 } 12684 } 12685 12686 @Override 12687 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12688 mContext.enforceCallingOrSelfPermission( 12689 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12690 "Only package verification agents can verify applications"); 12691 12692 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12693 final PackageVerificationResponse response = new PackageVerificationResponse( 12694 verificationCode, Binder.getCallingUid()); 12695 msg.arg1 = id; 12696 msg.obj = response; 12697 mHandler.sendMessage(msg); 12698 } 12699 12700 @Override 12701 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12702 long millisecondsToDelay) { 12703 mContext.enforceCallingOrSelfPermission( 12704 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12705 "Only package verification agents can extend verification timeouts"); 12706 12707 final PackageVerificationState state = mPendingVerification.get(id); 12708 final PackageVerificationResponse response = new PackageVerificationResponse( 12709 verificationCodeAtTimeout, Binder.getCallingUid()); 12710 12711 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12712 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12713 } 12714 if (millisecondsToDelay < 0) { 12715 millisecondsToDelay = 0; 12716 } 12717 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12718 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12719 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12720 } 12721 12722 if ((state != null) && !state.timeoutExtended()) { 12723 state.extendTimeout(); 12724 12725 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12726 msg.arg1 = id; 12727 msg.obj = response; 12728 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12729 } 12730 } 12731 12732 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12733 int verificationCode, UserHandle user) { 12734 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12735 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12736 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12737 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12738 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12739 12740 mContext.sendBroadcastAsUser(intent, user, 12741 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12742 } 12743 12744 private ComponentName matchComponentForVerifier(String packageName, 12745 List<ResolveInfo> receivers) { 12746 ActivityInfo targetReceiver = null; 12747 12748 final int NR = receivers.size(); 12749 for (int i = 0; i < NR; i++) { 12750 final ResolveInfo info = receivers.get(i); 12751 if (info.activityInfo == null) { 12752 continue; 12753 } 12754 12755 if (packageName.equals(info.activityInfo.packageName)) { 12756 targetReceiver = info.activityInfo; 12757 break; 12758 } 12759 } 12760 12761 if (targetReceiver == null) { 12762 return null; 12763 } 12764 12765 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12766 } 12767 12768 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12769 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12770 if (pkgInfo.verifiers.length == 0) { 12771 return null; 12772 } 12773 12774 final int N = pkgInfo.verifiers.length; 12775 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12776 for (int i = 0; i < N; i++) { 12777 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12778 12779 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12780 receivers); 12781 if (comp == null) { 12782 continue; 12783 } 12784 12785 final int verifierUid = getUidForVerifier(verifierInfo); 12786 if (verifierUid == -1) { 12787 continue; 12788 } 12789 12790 if (DEBUG_VERIFY) { 12791 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12792 + " with the correct signature"); 12793 } 12794 sufficientVerifiers.add(comp); 12795 verificationState.addSufficientVerifier(verifierUid); 12796 } 12797 12798 return sufficientVerifiers; 12799 } 12800 12801 private int getUidForVerifier(VerifierInfo verifierInfo) { 12802 synchronized (mPackages) { 12803 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12804 if (pkg == null) { 12805 return -1; 12806 } else if (pkg.mSignatures.length != 1) { 12807 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12808 + " has more than one signature; ignoring"); 12809 return -1; 12810 } 12811 12812 /* 12813 * If the public key of the package's signature does not match 12814 * our expected public key, then this is a different package and 12815 * we should skip. 12816 */ 12817 12818 final byte[] expectedPublicKey; 12819 try { 12820 final Signature verifierSig = pkg.mSignatures[0]; 12821 final PublicKey publicKey = verifierSig.getPublicKey(); 12822 expectedPublicKey = publicKey.getEncoded(); 12823 } catch (CertificateException e) { 12824 return -1; 12825 } 12826 12827 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12828 12829 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12830 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12831 + " does not have the expected public key; ignoring"); 12832 return -1; 12833 } 12834 12835 return pkg.applicationInfo.uid; 12836 } 12837 } 12838 12839 @Override 12840 public void finishPackageInstall(int token, boolean didLaunch) { 12841 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12842 12843 if (DEBUG_INSTALL) { 12844 Slog.v(TAG, "BM finishing package install for " + token); 12845 } 12846 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12847 12848 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12849 mHandler.sendMessage(msg); 12850 } 12851 12852 /** 12853 * Get the verification agent timeout. 12854 * 12855 * @return verification timeout in milliseconds 12856 */ 12857 private long getVerificationTimeout() { 12858 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12859 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12860 DEFAULT_VERIFICATION_TIMEOUT); 12861 } 12862 12863 /** 12864 * Get the default verification agent response code. 12865 * 12866 * @return default verification response code 12867 */ 12868 private int getDefaultVerificationResponse() { 12869 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12870 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12871 DEFAULT_VERIFICATION_RESPONSE); 12872 } 12873 12874 /** 12875 * Check whether or not package verification has been enabled. 12876 * 12877 * @return true if verification should be performed 12878 */ 12879 private boolean isVerificationEnabled(int userId, int installFlags) { 12880 if (!DEFAULT_VERIFY_ENABLE) { 12881 return false; 12882 } 12883 // Ephemeral apps don't get the full verification treatment 12884 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12885 if (DEBUG_EPHEMERAL) { 12886 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12887 } 12888 return false; 12889 } 12890 12891 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12892 12893 // Check if installing from ADB 12894 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12895 // Do not run verification in a test harness environment 12896 if (ActivityManager.isRunningInTestHarness()) { 12897 return false; 12898 } 12899 if (ensureVerifyAppsEnabled) { 12900 return true; 12901 } 12902 // Check if the developer does not want package verification for ADB installs 12903 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12904 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12905 return false; 12906 } 12907 } 12908 12909 if (ensureVerifyAppsEnabled) { 12910 return true; 12911 } 12912 12913 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12914 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12915 } 12916 12917 @Override 12918 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12919 throws RemoteException { 12920 mContext.enforceCallingOrSelfPermission( 12921 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12922 "Only intentfilter verification agents can verify applications"); 12923 12924 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12925 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12926 Binder.getCallingUid(), verificationCode, failedDomains); 12927 msg.arg1 = id; 12928 msg.obj = response; 12929 mHandler.sendMessage(msg); 12930 } 12931 12932 @Override 12933 public int getIntentVerificationStatus(String packageName, int userId) { 12934 synchronized (mPackages) { 12935 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12936 } 12937 } 12938 12939 @Override 12940 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12941 mContext.enforceCallingOrSelfPermission( 12942 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12943 12944 boolean result = false; 12945 synchronized (mPackages) { 12946 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12947 } 12948 if (result) { 12949 scheduleWritePackageRestrictionsLocked(userId); 12950 } 12951 return result; 12952 } 12953 12954 @Override 12955 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12956 String packageName) { 12957 synchronized (mPackages) { 12958 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12959 } 12960 } 12961 12962 @Override 12963 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12964 if (TextUtils.isEmpty(packageName)) { 12965 return ParceledListSlice.emptyList(); 12966 } 12967 synchronized (mPackages) { 12968 PackageParser.Package pkg = mPackages.get(packageName); 12969 if (pkg == null || pkg.activities == null) { 12970 return ParceledListSlice.emptyList(); 12971 } 12972 final int count = pkg.activities.size(); 12973 ArrayList<IntentFilter> result = new ArrayList<>(); 12974 for (int n=0; n<count; n++) { 12975 PackageParser.Activity activity = pkg.activities.get(n); 12976 if (activity.intents != null && activity.intents.size() > 0) { 12977 result.addAll(activity.intents); 12978 } 12979 } 12980 return new ParceledListSlice<>(result); 12981 } 12982 } 12983 12984 @Override 12985 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12986 mContext.enforceCallingOrSelfPermission( 12987 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12988 12989 synchronized (mPackages) { 12990 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12991 if (packageName != null) { 12992 result |= updateIntentVerificationStatus(packageName, 12993 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12994 userId); 12995 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12996 packageName, userId); 12997 } 12998 return result; 12999 } 13000 } 13001 13002 @Override 13003 public String getDefaultBrowserPackageName(int userId) { 13004 synchronized (mPackages) { 13005 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13006 } 13007 } 13008 13009 /** 13010 * Get the "allow unknown sources" setting. 13011 * 13012 * @return the current "allow unknown sources" setting 13013 */ 13014 private int getUnknownSourcesSettings() { 13015 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13016 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13017 -1); 13018 } 13019 13020 @Override 13021 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13022 final int uid = Binder.getCallingUid(); 13023 // writer 13024 synchronized (mPackages) { 13025 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13026 if (targetPackageSetting == null) { 13027 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13028 } 13029 13030 PackageSetting installerPackageSetting; 13031 if (installerPackageName != null) { 13032 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13033 if (installerPackageSetting == null) { 13034 throw new IllegalArgumentException("Unknown installer package: " 13035 + installerPackageName); 13036 } 13037 } else { 13038 installerPackageSetting = null; 13039 } 13040 13041 Signature[] callerSignature; 13042 Object obj = mSettings.getUserIdLPr(uid); 13043 if (obj != null) { 13044 if (obj instanceof SharedUserSetting) { 13045 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13046 } else if (obj instanceof PackageSetting) { 13047 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13048 } else { 13049 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13050 } 13051 } else { 13052 throw new SecurityException("Unknown calling UID: " + uid); 13053 } 13054 13055 // Verify: can't set installerPackageName to a package that is 13056 // not signed with the same cert as the caller. 13057 if (installerPackageSetting != null) { 13058 if (compareSignatures(callerSignature, 13059 installerPackageSetting.signatures.mSignatures) 13060 != PackageManager.SIGNATURE_MATCH) { 13061 throw new SecurityException( 13062 "Caller does not have same cert as new installer package " 13063 + installerPackageName); 13064 } 13065 } 13066 13067 // Verify: if target already has an installer package, it must 13068 // be signed with the same cert as the caller. 13069 if (targetPackageSetting.installerPackageName != null) { 13070 PackageSetting setting = mSettings.mPackages.get( 13071 targetPackageSetting.installerPackageName); 13072 // If the currently set package isn't valid, then it's always 13073 // okay to change it. 13074 if (setting != null) { 13075 if (compareSignatures(callerSignature, 13076 setting.signatures.mSignatures) 13077 != PackageManager.SIGNATURE_MATCH) { 13078 throw new SecurityException( 13079 "Caller does not have same cert as old installer package " 13080 + targetPackageSetting.installerPackageName); 13081 } 13082 } 13083 } 13084 13085 // Okay! 13086 targetPackageSetting.installerPackageName = installerPackageName; 13087 if (installerPackageName != null) { 13088 mSettings.mInstallerPackages.add(installerPackageName); 13089 } 13090 scheduleWriteSettingsLocked(); 13091 } 13092 } 13093 13094 @Override 13095 public void setApplicationCategoryHint(String packageName, int categoryHint, 13096 String callerPackageName) { 13097 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13098 callerPackageName); 13099 synchronized (mPackages) { 13100 PackageSetting ps = mSettings.mPackages.get(packageName); 13101 if (ps == null) { 13102 throw new IllegalArgumentException("Unknown target package " + packageName); 13103 } 13104 13105 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13106 throw new IllegalArgumentException("Calling package " + callerPackageName 13107 + " is not installer for " + packageName); 13108 } 13109 13110 if (ps.categoryHint != categoryHint) { 13111 ps.categoryHint = categoryHint; 13112 scheduleWriteSettingsLocked(); 13113 } 13114 } 13115 } 13116 13117 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13118 // Queue up an async operation since the package installation may take a little while. 13119 mHandler.post(new Runnable() { 13120 public void run() { 13121 mHandler.removeCallbacks(this); 13122 // Result object to be returned 13123 PackageInstalledInfo res = new PackageInstalledInfo(); 13124 res.setReturnCode(currentStatus); 13125 res.uid = -1; 13126 res.pkg = null; 13127 res.removedInfo = null; 13128 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13129 args.doPreInstall(res.returnCode); 13130 synchronized (mInstallLock) { 13131 installPackageTracedLI(args, res); 13132 } 13133 args.doPostInstall(res.returnCode, res.uid); 13134 } 13135 13136 // A restore should be performed at this point if (a) the install 13137 // succeeded, (b) the operation is not an update, and (c) the new 13138 // package has not opted out of backup participation. 13139 final boolean update = res.removedInfo != null 13140 && res.removedInfo.removedPackage != null; 13141 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13142 boolean doRestore = !update 13143 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13144 13145 // Set up the post-install work request bookkeeping. This will be used 13146 // and cleaned up by the post-install event handling regardless of whether 13147 // there's a restore pass performed. Token values are >= 1. 13148 int token; 13149 if (mNextInstallToken < 0) mNextInstallToken = 1; 13150 token = mNextInstallToken++; 13151 13152 PostInstallData data = new PostInstallData(args, res); 13153 mRunningInstalls.put(token, data); 13154 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13155 13156 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13157 // Pass responsibility to the Backup Manager. It will perform a 13158 // restore if appropriate, then pass responsibility back to the 13159 // Package Manager to run the post-install observer callbacks 13160 // and broadcasts. 13161 IBackupManager bm = IBackupManager.Stub.asInterface( 13162 ServiceManager.getService(Context.BACKUP_SERVICE)); 13163 if (bm != null) { 13164 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 13165 + " to BM for possible restore"); 13166 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13167 try { 13168 // TODO: http://b/22388012 13169 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 13170 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 13171 } else { 13172 doRestore = false; 13173 } 13174 } catch (RemoteException e) { 13175 // can't happen; the backup manager is local 13176 } catch (Exception e) { 13177 Slog.e(TAG, "Exception trying to enqueue restore", e); 13178 doRestore = false; 13179 } 13180 } else { 13181 Slog.e(TAG, "Backup Manager not found!"); 13182 doRestore = false; 13183 } 13184 } 13185 13186 if (!doRestore) { 13187 // No restore possible, or the Backup Manager was mysteriously not 13188 // available -- just fire the post-install work request directly. 13189 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 13190 13191 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 13192 13193 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 13194 mHandler.sendMessage(msg); 13195 } 13196 } 13197 }); 13198 } 13199 13200 /** 13201 * Callback from PackageSettings whenever an app is first transitioned out of the 13202 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 13203 * the app was "launched" for a restoreAtInstall operation. Therefore we check 13204 * here whether the app is the target of an ongoing install, and only send the 13205 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13206 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13207 * handling. 13208 */ 13209 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13210 // Serialize this with the rest of the install-process message chain. In the 13211 // restore-at-install case, this Runnable will necessarily run before the 13212 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13213 // are coherent. In the non-restore case, the app has already completed install 13214 // and been launched through some other means, so it is not in a problematic 13215 // state for observers to see the FIRST_LAUNCH signal. 13216 mHandler.post(new Runnable() { 13217 @Override 13218 public void run() { 13219 for (int i = 0; i < mRunningInstalls.size(); i++) { 13220 final PostInstallData data = mRunningInstalls.valueAt(i); 13221 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13222 continue; 13223 } 13224 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13225 // right package; but is it for the right user? 13226 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13227 if (userId == data.res.newUsers[uIndex]) { 13228 if (DEBUG_BACKUP) { 13229 Slog.i(TAG, "Package " + pkgName 13230 + " being restored so deferring FIRST_LAUNCH"); 13231 } 13232 return; 13233 } 13234 } 13235 } 13236 } 13237 // didn't find it, so not being restored 13238 if (DEBUG_BACKUP) { 13239 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13240 } 13241 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13242 } 13243 }); 13244 } 13245 13246 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13247 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13248 installerPkg, null, userIds); 13249 } 13250 13251 private abstract class HandlerParams { 13252 private static final int MAX_RETRIES = 4; 13253 13254 /** 13255 * Number of times startCopy() has been attempted and had a non-fatal 13256 * error. 13257 */ 13258 private int mRetries = 0; 13259 13260 /** User handle for the user requesting the information or installation. */ 13261 private final UserHandle mUser; 13262 String traceMethod; 13263 int traceCookie; 13264 13265 HandlerParams(UserHandle user) { 13266 mUser = user; 13267 } 13268 13269 UserHandle getUser() { 13270 return mUser; 13271 } 13272 13273 HandlerParams setTraceMethod(String traceMethod) { 13274 this.traceMethod = traceMethod; 13275 return this; 13276 } 13277 13278 HandlerParams setTraceCookie(int traceCookie) { 13279 this.traceCookie = traceCookie; 13280 return this; 13281 } 13282 13283 final boolean startCopy() { 13284 boolean res; 13285 try { 13286 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13287 13288 if (++mRetries > MAX_RETRIES) { 13289 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13290 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13291 handleServiceError(); 13292 return false; 13293 } else { 13294 handleStartCopy(); 13295 res = true; 13296 } 13297 } catch (RemoteException e) { 13298 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13299 mHandler.sendEmptyMessage(MCS_RECONNECT); 13300 res = false; 13301 } 13302 handleReturnCode(); 13303 return res; 13304 } 13305 13306 final void serviceError() { 13307 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13308 handleServiceError(); 13309 handleReturnCode(); 13310 } 13311 13312 abstract void handleStartCopy() throws RemoteException; 13313 abstract void handleServiceError(); 13314 abstract void handleReturnCode(); 13315 } 13316 13317 class MeasureParams extends HandlerParams { 13318 private final PackageStats mStats; 13319 private boolean mSuccess; 13320 13321 private final IPackageStatsObserver mObserver; 13322 13323 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 13324 super(new UserHandle(stats.userHandle)); 13325 mObserver = observer; 13326 mStats = stats; 13327 } 13328 13329 @Override 13330 public String toString() { 13331 return "MeasureParams{" 13332 + Integer.toHexString(System.identityHashCode(this)) 13333 + " " + mStats.packageName + "}"; 13334 } 13335 13336 @Override 13337 void handleStartCopy() throws RemoteException { 13338 synchronized (mInstallLock) { 13339 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 13340 } 13341 13342 if (mSuccess) { 13343 boolean mounted = false; 13344 try { 13345 final String status = Environment.getExternalStorageState(); 13346 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13347 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13348 } catch (Exception e) { 13349 } 13350 13351 if (mounted) { 13352 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13353 13354 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13355 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13356 13357 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13358 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13359 13360 // Always subtract cache size, since it's a subdirectory 13361 mStats.externalDataSize -= mStats.externalCacheSize; 13362 13363 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13364 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13365 13366 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13367 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13368 } 13369 } 13370 } 13371 13372 @Override 13373 void handleReturnCode() { 13374 if (mObserver != null) { 13375 try { 13376 mObserver.onGetStatsCompleted(mStats, mSuccess); 13377 } catch (RemoteException e) { 13378 Slog.i(TAG, "Observer no longer exists."); 13379 } 13380 } 13381 } 13382 13383 @Override 13384 void handleServiceError() { 13385 Slog.e(TAG, "Could not measure application " + mStats.packageName 13386 + " external storage"); 13387 } 13388 } 13389 13390 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13391 throws RemoteException { 13392 long result = 0; 13393 for (File path : paths) { 13394 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13395 } 13396 return result; 13397 } 13398 13399 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13400 for (File path : paths) { 13401 try { 13402 mcs.clearDirectory(path.getAbsolutePath()); 13403 } catch (RemoteException e) { 13404 } 13405 } 13406 } 13407 13408 static class OriginInfo { 13409 /** 13410 * Location where install is coming from, before it has been 13411 * copied/renamed into place. This could be a single monolithic APK 13412 * file, or a cluster directory. This location may be untrusted. 13413 */ 13414 final File file; 13415 final String cid; 13416 13417 /** 13418 * Flag indicating that {@link #file} or {@link #cid} has already been 13419 * staged, meaning downstream users don't need to defensively copy the 13420 * contents. 13421 */ 13422 final boolean staged; 13423 13424 /** 13425 * Flag indicating that {@link #file} or {@link #cid} is an already 13426 * installed app that is being moved. 13427 */ 13428 final boolean existing; 13429 13430 final String resolvedPath; 13431 final File resolvedFile; 13432 13433 static OriginInfo fromNothing() { 13434 return new OriginInfo(null, null, false, false); 13435 } 13436 13437 static OriginInfo fromUntrustedFile(File file) { 13438 return new OriginInfo(file, null, false, false); 13439 } 13440 13441 static OriginInfo fromExistingFile(File file) { 13442 return new OriginInfo(file, null, false, true); 13443 } 13444 13445 static OriginInfo fromStagedFile(File file) { 13446 return new OriginInfo(file, null, true, false); 13447 } 13448 13449 static OriginInfo fromStagedContainer(String cid) { 13450 return new OriginInfo(null, cid, true, false); 13451 } 13452 13453 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13454 this.file = file; 13455 this.cid = cid; 13456 this.staged = staged; 13457 this.existing = existing; 13458 13459 if (cid != null) { 13460 resolvedPath = PackageHelper.getSdDir(cid); 13461 resolvedFile = new File(resolvedPath); 13462 } else if (file != null) { 13463 resolvedPath = file.getAbsolutePath(); 13464 resolvedFile = file; 13465 } else { 13466 resolvedPath = null; 13467 resolvedFile = null; 13468 } 13469 } 13470 } 13471 13472 static class MoveInfo { 13473 final int moveId; 13474 final String fromUuid; 13475 final String toUuid; 13476 final String packageName; 13477 final String dataAppName; 13478 final int appId; 13479 final String seinfo; 13480 final int targetSdkVersion; 13481 13482 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13483 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13484 this.moveId = moveId; 13485 this.fromUuid = fromUuid; 13486 this.toUuid = toUuid; 13487 this.packageName = packageName; 13488 this.dataAppName = dataAppName; 13489 this.appId = appId; 13490 this.seinfo = seinfo; 13491 this.targetSdkVersion = targetSdkVersion; 13492 } 13493 } 13494 13495 static class VerificationInfo { 13496 /** A constant used to indicate that a uid value is not present. */ 13497 public static final int NO_UID = -1; 13498 13499 /** URI referencing where the package was downloaded from. */ 13500 final Uri originatingUri; 13501 13502 /** HTTP referrer URI associated with the originatingURI. */ 13503 final Uri referrer; 13504 13505 /** UID of the application that the install request originated from. */ 13506 final int originatingUid; 13507 13508 /** UID of application requesting the install */ 13509 final int installerUid; 13510 13511 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13512 this.originatingUri = originatingUri; 13513 this.referrer = referrer; 13514 this.originatingUid = originatingUid; 13515 this.installerUid = installerUid; 13516 } 13517 } 13518 13519 class InstallParams extends HandlerParams { 13520 final OriginInfo origin; 13521 final MoveInfo move; 13522 final IPackageInstallObserver2 observer; 13523 int installFlags; 13524 final String installerPackageName; 13525 final String volumeUuid; 13526 private InstallArgs mArgs; 13527 private int mRet; 13528 final String packageAbiOverride; 13529 final String[] grantedRuntimePermissions; 13530 final VerificationInfo verificationInfo; 13531 final Certificate[][] certificates; 13532 final int installReason; 13533 13534 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13535 int installFlags, String installerPackageName, String volumeUuid, 13536 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13537 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 13538 super(user); 13539 this.origin = origin; 13540 this.move = move; 13541 this.observer = observer; 13542 this.installFlags = installFlags; 13543 this.installerPackageName = installerPackageName; 13544 this.volumeUuid = volumeUuid; 13545 this.verificationInfo = verificationInfo; 13546 this.packageAbiOverride = packageAbiOverride; 13547 this.grantedRuntimePermissions = grantedPermissions; 13548 this.certificates = certificates; 13549 this.installReason = installReason; 13550 } 13551 13552 @Override 13553 public String toString() { 13554 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13555 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13556 } 13557 13558 private int installLocationPolicy(PackageInfoLite pkgLite) { 13559 String packageName = pkgLite.packageName; 13560 int installLocation = pkgLite.installLocation; 13561 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13562 // reader 13563 synchronized (mPackages) { 13564 // Currently installed package which the new package is attempting to replace or 13565 // null if no such package is installed. 13566 PackageParser.Package installedPkg = mPackages.get(packageName); 13567 // Package which currently owns the data which the new package will own if installed. 13568 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13569 // will be null whereas dataOwnerPkg will contain information about the package 13570 // which was uninstalled while keeping its data. 13571 PackageParser.Package dataOwnerPkg = installedPkg; 13572 if (dataOwnerPkg == null) { 13573 PackageSetting ps = mSettings.mPackages.get(packageName); 13574 if (ps != null) { 13575 dataOwnerPkg = ps.pkg; 13576 } 13577 } 13578 13579 if (dataOwnerPkg != null) { 13580 // If installed, the package will get access to data left on the device by its 13581 // predecessor. As a security measure, this is permited only if this is not a 13582 // version downgrade or if the predecessor package is marked as debuggable and 13583 // a downgrade is explicitly requested. 13584 // 13585 // On debuggable platform builds, downgrades are permitted even for 13586 // non-debuggable packages to make testing easier. Debuggable platform builds do 13587 // not offer security guarantees and thus it's OK to disable some security 13588 // mechanisms to make debugging/testing easier on those builds. However, even on 13589 // debuggable builds downgrades of packages are permitted only if requested via 13590 // installFlags. This is because we aim to keep the behavior of debuggable 13591 // platform builds as close as possible to the behavior of non-debuggable 13592 // platform builds. 13593 final boolean downgradeRequested = 13594 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13595 final boolean packageDebuggable = 13596 (dataOwnerPkg.applicationInfo.flags 13597 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13598 final boolean downgradePermitted = 13599 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13600 if (!downgradePermitted) { 13601 try { 13602 checkDowngrade(dataOwnerPkg, pkgLite); 13603 } catch (PackageManagerException e) { 13604 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13605 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13606 } 13607 } 13608 } 13609 13610 if (installedPkg != null) { 13611 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13612 // Check for updated system application. 13613 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13614 if (onSd) { 13615 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13616 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13617 } 13618 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13619 } else { 13620 if (onSd) { 13621 // Install flag overrides everything. 13622 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13623 } 13624 // If current upgrade specifies particular preference 13625 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13626 // Application explicitly specified internal. 13627 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13628 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13629 // App explictly prefers external. Let policy decide 13630 } else { 13631 // Prefer previous location 13632 if (isExternal(installedPkg)) { 13633 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13634 } 13635 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13636 } 13637 } 13638 } else { 13639 // Invalid install. Return error code 13640 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13641 } 13642 } 13643 } 13644 // All the special cases have been taken care of. 13645 // Return result based on recommended install location. 13646 if (onSd) { 13647 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13648 } 13649 return pkgLite.recommendedInstallLocation; 13650 } 13651 13652 /* 13653 * Invoke remote method to get package information and install 13654 * location values. Override install location based on default 13655 * policy if needed and then create install arguments based 13656 * on the install location. 13657 */ 13658 public void handleStartCopy() throws RemoteException { 13659 int ret = PackageManager.INSTALL_SUCCEEDED; 13660 13661 // If we're already staged, we've firmly committed to an install location 13662 if (origin.staged) { 13663 if (origin.file != null) { 13664 installFlags |= PackageManager.INSTALL_INTERNAL; 13665 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13666 } else if (origin.cid != null) { 13667 installFlags |= PackageManager.INSTALL_EXTERNAL; 13668 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13669 } else { 13670 throw new IllegalStateException("Invalid stage location"); 13671 } 13672 } 13673 13674 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13675 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13676 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13677 PackageInfoLite pkgLite = null; 13678 13679 if (onInt && onSd) { 13680 // Check if both bits are set. 13681 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13682 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13683 } else if (onSd && ephemeral) { 13684 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13685 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13686 } else { 13687 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13688 packageAbiOverride); 13689 13690 if (DEBUG_EPHEMERAL && ephemeral) { 13691 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13692 } 13693 13694 /* 13695 * If we have too little free space, try to free cache 13696 * before giving up. 13697 */ 13698 if (!origin.staged && pkgLite.recommendedInstallLocation 13699 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13700 // TODO: focus freeing disk space on the target device 13701 final StorageManager storage = StorageManager.from(mContext); 13702 final long lowThreshold = storage.getStorageLowBytes( 13703 Environment.getDataDirectory()); 13704 13705 final long sizeBytes = mContainerService.calculateInstalledSize( 13706 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13707 13708 try { 13709 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 13710 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13711 installFlags, packageAbiOverride); 13712 } catch (InstallerException e) { 13713 Slog.w(TAG, "Failed to free cache", e); 13714 } 13715 13716 /* 13717 * The cache free must have deleted the file we 13718 * downloaded to install. 13719 * 13720 * TODO: fix the "freeCache" call to not delete 13721 * the file we care about. 13722 */ 13723 if (pkgLite.recommendedInstallLocation 13724 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13725 pkgLite.recommendedInstallLocation 13726 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13727 } 13728 } 13729 } 13730 13731 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13732 int loc = pkgLite.recommendedInstallLocation; 13733 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13734 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13735 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13736 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13737 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13738 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13739 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13740 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13741 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13742 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13743 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13744 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13745 } else { 13746 // Override with defaults if needed. 13747 loc = installLocationPolicy(pkgLite); 13748 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13749 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13750 } else if (!onSd && !onInt) { 13751 // Override install location with flags 13752 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13753 // Set the flag to install on external media. 13754 installFlags |= PackageManager.INSTALL_EXTERNAL; 13755 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13756 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13757 if (DEBUG_EPHEMERAL) { 13758 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13759 } 13760 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13761 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13762 |PackageManager.INSTALL_INTERNAL); 13763 } else { 13764 // Make sure the flag for installing on external 13765 // media is unset 13766 installFlags |= PackageManager.INSTALL_INTERNAL; 13767 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13768 } 13769 } 13770 } 13771 } 13772 13773 final InstallArgs args = createInstallArgs(this); 13774 mArgs = args; 13775 13776 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13777 // TODO: http://b/22976637 13778 // Apps installed for "all" users use the device owner to verify the app 13779 UserHandle verifierUser = getUser(); 13780 if (verifierUser == UserHandle.ALL) { 13781 verifierUser = UserHandle.SYSTEM; 13782 } 13783 13784 /* 13785 * Determine if we have any installed package verifiers. If we 13786 * do, then we'll defer to them to verify the packages. 13787 */ 13788 final int requiredUid = mRequiredVerifierPackage == null ? -1 13789 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13790 verifierUser.getIdentifier()); 13791 if (!origin.existing && requiredUid != -1 13792 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13793 final Intent verification = new Intent( 13794 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13795 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13796 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13797 PACKAGE_MIME_TYPE); 13798 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13799 13800 // Query all live verifiers based on current user state 13801 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13802 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13803 13804 if (DEBUG_VERIFY) { 13805 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13806 + verification.toString() + " with " + pkgLite.verifiers.length 13807 + " optional verifiers"); 13808 } 13809 13810 final int verificationId = mPendingVerificationToken++; 13811 13812 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13813 13814 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13815 installerPackageName); 13816 13817 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13818 installFlags); 13819 13820 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13821 pkgLite.packageName); 13822 13823 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13824 pkgLite.versionCode); 13825 13826 if (verificationInfo != null) { 13827 if (verificationInfo.originatingUri != null) { 13828 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13829 verificationInfo.originatingUri); 13830 } 13831 if (verificationInfo.referrer != null) { 13832 verification.putExtra(Intent.EXTRA_REFERRER, 13833 verificationInfo.referrer); 13834 } 13835 if (verificationInfo.originatingUid >= 0) { 13836 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13837 verificationInfo.originatingUid); 13838 } 13839 if (verificationInfo.installerUid >= 0) { 13840 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13841 verificationInfo.installerUid); 13842 } 13843 } 13844 13845 final PackageVerificationState verificationState = new PackageVerificationState( 13846 requiredUid, args); 13847 13848 mPendingVerification.append(verificationId, verificationState); 13849 13850 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13851 receivers, verificationState); 13852 13853 /* 13854 * If any sufficient verifiers were listed in the package 13855 * manifest, attempt to ask them. 13856 */ 13857 if (sufficientVerifiers != null) { 13858 final int N = sufficientVerifiers.size(); 13859 if (N == 0) { 13860 Slog.i(TAG, "Additional verifiers required, but none installed."); 13861 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13862 } else { 13863 for (int i = 0; i < N; i++) { 13864 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13865 13866 final Intent sufficientIntent = new Intent(verification); 13867 sufficientIntent.setComponent(verifierComponent); 13868 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13869 } 13870 } 13871 } 13872 13873 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13874 mRequiredVerifierPackage, receivers); 13875 if (ret == PackageManager.INSTALL_SUCCEEDED 13876 && mRequiredVerifierPackage != null) { 13877 Trace.asyncTraceBegin( 13878 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13879 /* 13880 * Send the intent to the required verification agent, 13881 * but only start the verification timeout after the 13882 * target BroadcastReceivers have run. 13883 */ 13884 verification.setComponent(requiredVerifierComponent); 13885 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13886 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13887 new BroadcastReceiver() { 13888 @Override 13889 public void onReceive(Context context, Intent intent) { 13890 final Message msg = mHandler 13891 .obtainMessage(CHECK_PENDING_VERIFICATION); 13892 msg.arg1 = verificationId; 13893 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13894 } 13895 }, null, 0, null, null); 13896 13897 /* 13898 * We don't want the copy to proceed until verification 13899 * succeeds, so null out this field. 13900 */ 13901 mArgs = null; 13902 } 13903 } else { 13904 /* 13905 * No package verification is enabled, so immediately start 13906 * the remote call to initiate copy using temporary file. 13907 */ 13908 ret = args.copyApk(mContainerService, true); 13909 } 13910 } 13911 13912 mRet = ret; 13913 } 13914 13915 @Override 13916 void handleReturnCode() { 13917 // If mArgs is null, then MCS couldn't be reached. When it 13918 // reconnects, it will try again to install. At that point, this 13919 // will succeed. 13920 if (mArgs != null) { 13921 processPendingInstall(mArgs, mRet); 13922 } 13923 } 13924 13925 @Override 13926 void handleServiceError() { 13927 mArgs = createInstallArgs(this); 13928 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13929 } 13930 13931 public boolean isForwardLocked() { 13932 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13933 } 13934 } 13935 13936 /** 13937 * Used during creation of InstallArgs 13938 * 13939 * @param installFlags package installation flags 13940 * @return true if should be installed on external storage 13941 */ 13942 private static boolean installOnExternalAsec(int installFlags) { 13943 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13944 return false; 13945 } 13946 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13947 return true; 13948 } 13949 return false; 13950 } 13951 13952 /** 13953 * Used during creation of InstallArgs 13954 * 13955 * @param installFlags package installation flags 13956 * @return true if should be installed as forward locked 13957 */ 13958 private static boolean installForwardLocked(int installFlags) { 13959 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13960 } 13961 13962 private InstallArgs createInstallArgs(InstallParams params) { 13963 if (params.move != null) { 13964 return new MoveInstallArgs(params); 13965 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13966 return new AsecInstallArgs(params); 13967 } else { 13968 return new FileInstallArgs(params); 13969 } 13970 } 13971 13972 /** 13973 * Create args that describe an existing installed package. Typically used 13974 * when cleaning up old installs, or used as a move source. 13975 */ 13976 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13977 String resourcePath, String[] instructionSets) { 13978 final boolean isInAsec; 13979 if (installOnExternalAsec(installFlags)) { 13980 /* Apps on SD card are always in ASEC containers. */ 13981 isInAsec = true; 13982 } else if (installForwardLocked(installFlags) 13983 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13984 /* 13985 * Forward-locked apps are only in ASEC containers if they're the 13986 * new style 13987 */ 13988 isInAsec = true; 13989 } else { 13990 isInAsec = false; 13991 } 13992 13993 if (isInAsec) { 13994 return new AsecInstallArgs(codePath, instructionSets, 13995 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13996 } else { 13997 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13998 } 13999 } 14000 14001 static abstract class InstallArgs { 14002 /** @see InstallParams#origin */ 14003 final OriginInfo origin; 14004 /** @see InstallParams#move */ 14005 final MoveInfo move; 14006 14007 final IPackageInstallObserver2 observer; 14008 // Always refers to PackageManager flags only 14009 final int installFlags; 14010 final String installerPackageName; 14011 final String volumeUuid; 14012 final UserHandle user; 14013 final String abiOverride; 14014 final String[] installGrantPermissions; 14015 /** If non-null, drop an async trace when the install completes */ 14016 final String traceMethod; 14017 final int traceCookie; 14018 final Certificate[][] certificates; 14019 final int installReason; 14020 14021 // The list of instruction sets supported by this app. This is currently 14022 // only used during the rmdex() phase to clean up resources. We can get rid of this 14023 // if we move dex files under the common app path. 14024 /* nullable */ String[] instructionSets; 14025 14026 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14027 int installFlags, String installerPackageName, String volumeUuid, 14028 UserHandle user, String[] instructionSets, 14029 String abiOverride, String[] installGrantPermissions, 14030 String traceMethod, int traceCookie, Certificate[][] certificates, 14031 int installReason) { 14032 this.origin = origin; 14033 this.move = move; 14034 this.installFlags = installFlags; 14035 this.observer = observer; 14036 this.installerPackageName = installerPackageName; 14037 this.volumeUuid = volumeUuid; 14038 this.user = user; 14039 this.instructionSets = instructionSets; 14040 this.abiOverride = abiOverride; 14041 this.installGrantPermissions = installGrantPermissions; 14042 this.traceMethod = traceMethod; 14043 this.traceCookie = traceCookie; 14044 this.certificates = certificates; 14045 this.installReason = installReason; 14046 } 14047 14048 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14049 abstract int doPreInstall(int status); 14050 14051 /** 14052 * Rename package into final resting place. All paths on the given 14053 * scanned package should be updated to reflect the rename. 14054 */ 14055 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14056 abstract int doPostInstall(int status, int uid); 14057 14058 /** @see PackageSettingBase#codePathString */ 14059 abstract String getCodePath(); 14060 /** @see PackageSettingBase#resourcePathString */ 14061 abstract String getResourcePath(); 14062 14063 // Need installer lock especially for dex file removal. 14064 abstract void cleanUpResourcesLI(); 14065 abstract boolean doPostDeleteLI(boolean delete); 14066 14067 /** 14068 * Called before the source arguments are copied. This is used mostly 14069 * for MoveParams when it needs to read the source file to put it in the 14070 * destination. 14071 */ 14072 int doPreCopy() { 14073 return PackageManager.INSTALL_SUCCEEDED; 14074 } 14075 14076 /** 14077 * Called after the source arguments are copied. This is used mostly for 14078 * MoveParams when it needs to read the source file to put it in the 14079 * destination. 14080 */ 14081 int doPostCopy(int uid) { 14082 return PackageManager.INSTALL_SUCCEEDED; 14083 } 14084 14085 protected boolean isFwdLocked() { 14086 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14087 } 14088 14089 protected boolean isExternalAsec() { 14090 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14091 } 14092 14093 protected boolean isEphemeral() { 14094 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14095 } 14096 14097 UserHandle getUser() { 14098 return user; 14099 } 14100 } 14101 14102 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14103 if (!allCodePaths.isEmpty()) { 14104 if (instructionSets == null) { 14105 throw new IllegalStateException("instructionSet == null"); 14106 } 14107 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14108 for (String codePath : allCodePaths) { 14109 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14110 try { 14111 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14112 } catch (InstallerException ignored) { 14113 } 14114 } 14115 } 14116 } 14117 } 14118 14119 /** 14120 * Logic to handle installation of non-ASEC applications, including copying 14121 * and renaming logic. 14122 */ 14123 class FileInstallArgs extends InstallArgs { 14124 private File codeFile; 14125 private File resourceFile; 14126 14127 // Example topology: 14128 // /data/app/com.example/base.apk 14129 // /data/app/com.example/split_foo.apk 14130 // /data/app/com.example/lib/arm/libfoo.so 14131 // /data/app/com.example/lib/arm64/libfoo.so 14132 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14133 14134 /** New install */ 14135 FileInstallArgs(InstallParams params) { 14136 super(params.origin, params.move, params.observer, params.installFlags, 14137 params.installerPackageName, params.volumeUuid, 14138 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14139 params.grantedRuntimePermissions, 14140 params.traceMethod, params.traceCookie, params.certificates, 14141 params.installReason); 14142 if (isFwdLocked()) { 14143 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14144 } 14145 } 14146 14147 /** Existing install */ 14148 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14149 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14150 null, null, null, 0, null /*certificates*/, 14151 PackageManager.INSTALL_REASON_UNKNOWN); 14152 this.codeFile = (codePath != null) ? new File(codePath) : null; 14153 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14154 } 14155 14156 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14157 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14158 try { 14159 return doCopyApk(imcs, temp); 14160 } finally { 14161 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14162 } 14163 } 14164 14165 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14166 if (origin.staged) { 14167 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14168 codeFile = origin.file; 14169 resourceFile = origin.file; 14170 return PackageManager.INSTALL_SUCCEEDED; 14171 } 14172 14173 try { 14174 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14175 final File tempDir = 14176 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14177 codeFile = tempDir; 14178 resourceFile = tempDir; 14179 } catch (IOException e) { 14180 Slog.w(TAG, "Failed to create copy file: " + e); 14181 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14182 } 14183 14184 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14185 @Override 14186 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14187 if (!FileUtils.isValidExtFilename(name)) { 14188 throw new IllegalArgumentException("Invalid filename: " + name); 14189 } 14190 try { 14191 final File file = new File(codeFile, name); 14192 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14193 O_RDWR | O_CREAT, 0644); 14194 Os.chmod(file.getAbsolutePath(), 0644); 14195 return new ParcelFileDescriptor(fd); 14196 } catch (ErrnoException e) { 14197 throw new RemoteException("Failed to open: " + e.getMessage()); 14198 } 14199 } 14200 }; 14201 14202 int ret = PackageManager.INSTALL_SUCCEEDED; 14203 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14204 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14205 Slog.e(TAG, "Failed to copy package"); 14206 return ret; 14207 } 14208 14209 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14210 NativeLibraryHelper.Handle handle = null; 14211 try { 14212 handle = NativeLibraryHelper.Handle.create(codeFile); 14213 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14214 abiOverride); 14215 } catch (IOException e) { 14216 Slog.e(TAG, "Copying native libraries failed", e); 14217 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14218 } finally { 14219 IoUtils.closeQuietly(handle); 14220 } 14221 14222 return ret; 14223 } 14224 14225 int doPreInstall(int status) { 14226 if (status != PackageManager.INSTALL_SUCCEEDED) { 14227 cleanUp(); 14228 } 14229 return status; 14230 } 14231 14232 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14233 if (status != PackageManager.INSTALL_SUCCEEDED) { 14234 cleanUp(); 14235 return false; 14236 } 14237 14238 final File targetDir = codeFile.getParentFile(); 14239 final File beforeCodeFile = codeFile; 14240 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14241 14242 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14243 try { 14244 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14245 } catch (ErrnoException e) { 14246 Slog.w(TAG, "Failed to rename", e); 14247 return false; 14248 } 14249 14250 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14251 Slog.w(TAG, "Failed to restorecon"); 14252 return false; 14253 } 14254 14255 // Reflect the rename internally 14256 codeFile = afterCodeFile; 14257 resourceFile = afterCodeFile; 14258 14259 // Reflect the rename in scanned details 14260 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14261 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14262 afterCodeFile, pkg.baseCodePath)); 14263 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14264 afterCodeFile, pkg.splitCodePaths)); 14265 14266 // Reflect the rename in app info 14267 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14268 pkg.setApplicationInfoCodePath(pkg.codePath); 14269 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14270 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14271 pkg.setApplicationInfoResourcePath(pkg.codePath); 14272 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14273 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14274 14275 return true; 14276 } 14277 14278 int doPostInstall(int status, int uid) { 14279 if (status != PackageManager.INSTALL_SUCCEEDED) { 14280 cleanUp(); 14281 } 14282 return status; 14283 } 14284 14285 @Override 14286 String getCodePath() { 14287 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14288 } 14289 14290 @Override 14291 String getResourcePath() { 14292 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14293 } 14294 14295 private boolean cleanUp() { 14296 if (codeFile == null || !codeFile.exists()) { 14297 return false; 14298 } 14299 14300 removeCodePathLI(codeFile); 14301 14302 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14303 resourceFile.delete(); 14304 } 14305 14306 return true; 14307 } 14308 14309 void cleanUpResourcesLI() { 14310 // Try enumerating all code paths before deleting 14311 List<String> allCodePaths = Collections.EMPTY_LIST; 14312 if (codeFile != null && codeFile.exists()) { 14313 try { 14314 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14315 allCodePaths = pkg.getAllCodePaths(); 14316 } catch (PackageParserException e) { 14317 // Ignored; we tried our best 14318 } 14319 } 14320 14321 cleanUp(); 14322 removeDexFiles(allCodePaths, instructionSets); 14323 } 14324 14325 boolean doPostDeleteLI(boolean delete) { 14326 // XXX err, shouldn't we respect the delete flag? 14327 cleanUpResourcesLI(); 14328 return true; 14329 } 14330 } 14331 14332 private boolean isAsecExternal(String cid) { 14333 final String asecPath = PackageHelper.getSdFilesystem(cid); 14334 return !asecPath.startsWith(mAsecInternalPath); 14335 } 14336 14337 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 14338 PackageManagerException { 14339 if (copyRet < 0) { 14340 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 14341 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 14342 throw new PackageManagerException(copyRet, message); 14343 } 14344 } 14345 } 14346 14347 /** 14348 * Extract the StorageManagerService "container ID" from the full code path of an 14349 * .apk. 14350 */ 14351 static String cidFromCodePath(String fullCodePath) { 14352 int eidx = fullCodePath.lastIndexOf("/"); 14353 String subStr1 = fullCodePath.substring(0, eidx); 14354 int sidx = subStr1.lastIndexOf("/"); 14355 return subStr1.substring(sidx+1, eidx); 14356 } 14357 14358 /** 14359 * Logic to handle installation of ASEC applications, including copying and 14360 * renaming logic. 14361 */ 14362 class AsecInstallArgs extends InstallArgs { 14363 static final String RES_FILE_NAME = "pkg.apk"; 14364 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14365 14366 String cid; 14367 String packagePath; 14368 String resourcePath; 14369 14370 /** New install */ 14371 AsecInstallArgs(InstallParams params) { 14372 super(params.origin, params.move, params.observer, params.installFlags, 14373 params.installerPackageName, params.volumeUuid, 14374 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14375 params.grantedRuntimePermissions, 14376 params.traceMethod, params.traceCookie, params.certificates, 14377 params.installReason); 14378 } 14379 14380 /** Existing install */ 14381 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14382 boolean isExternal, boolean isForwardLocked) { 14383 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14384 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14385 instructionSets, null, null, null, 0, null /*certificates*/, 14386 PackageManager.INSTALL_REASON_UNKNOWN); 14387 // Hackily pretend we're still looking at a full code path 14388 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14389 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14390 } 14391 14392 // Extract cid from fullCodePath 14393 int eidx = fullCodePath.lastIndexOf("/"); 14394 String subStr1 = fullCodePath.substring(0, eidx); 14395 int sidx = subStr1.lastIndexOf("/"); 14396 cid = subStr1.substring(sidx+1, eidx); 14397 setMountPath(subStr1); 14398 } 14399 14400 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14401 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14402 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14403 instructionSets, null, null, null, 0, null /*certificates*/, 14404 PackageManager.INSTALL_REASON_UNKNOWN); 14405 this.cid = cid; 14406 setMountPath(PackageHelper.getSdDir(cid)); 14407 } 14408 14409 void createCopyFile() { 14410 cid = mInstallerService.allocateExternalStageCidLegacy(); 14411 } 14412 14413 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14414 if (origin.staged && origin.cid != null) { 14415 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14416 cid = origin.cid; 14417 setMountPath(PackageHelper.getSdDir(cid)); 14418 return PackageManager.INSTALL_SUCCEEDED; 14419 } 14420 14421 if (temp) { 14422 createCopyFile(); 14423 } else { 14424 /* 14425 * Pre-emptively destroy the container since it's destroyed if 14426 * copying fails due to it existing anyway. 14427 */ 14428 PackageHelper.destroySdDir(cid); 14429 } 14430 14431 final String newMountPath = imcs.copyPackageToContainer( 14432 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14433 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14434 14435 if (newMountPath != null) { 14436 setMountPath(newMountPath); 14437 return PackageManager.INSTALL_SUCCEEDED; 14438 } else { 14439 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14440 } 14441 } 14442 14443 @Override 14444 String getCodePath() { 14445 return packagePath; 14446 } 14447 14448 @Override 14449 String getResourcePath() { 14450 return resourcePath; 14451 } 14452 14453 int doPreInstall(int status) { 14454 if (status != PackageManager.INSTALL_SUCCEEDED) { 14455 // Destroy container 14456 PackageHelper.destroySdDir(cid); 14457 } else { 14458 boolean mounted = PackageHelper.isContainerMounted(cid); 14459 if (!mounted) { 14460 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14461 Process.SYSTEM_UID); 14462 if (newMountPath != null) { 14463 setMountPath(newMountPath); 14464 } else { 14465 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14466 } 14467 } 14468 } 14469 return status; 14470 } 14471 14472 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14473 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14474 String newMountPath = null; 14475 if (PackageHelper.isContainerMounted(cid)) { 14476 // Unmount the container 14477 if (!PackageHelper.unMountSdDir(cid)) { 14478 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14479 return false; 14480 } 14481 } 14482 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14483 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14484 " which might be stale. Will try to clean up."); 14485 // Clean up the stale container and proceed to recreate. 14486 if (!PackageHelper.destroySdDir(newCacheId)) { 14487 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14488 return false; 14489 } 14490 // Successfully cleaned up stale container. Try to rename again. 14491 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14492 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14493 + " inspite of cleaning it up."); 14494 return false; 14495 } 14496 } 14497 if (!PackageHelper.isContainerMounted(newCacheId)) { 14498 Slog.w(TAG, "Mounting container " + newCacheId); 14499 newMountPath = PackageHelper.mountSdDir(newCacheId, 14500 getEncryptKey(), Process.SYSTEM_UID); 14501 } else { 14502 newMountPath = PackageHelper.getSdDir(newCacheId); 14503 } 14504 if (newMountPath == null) { 14505 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14506 return false; 14507 } 14508 Log.i(TAG, "Succesfully renamed " + cid + 14509 " to " + newCacheId + 14510 " at new path: " + newMountPath); 14511 cid = newCacheId; 14512 14513 final File beforeCodeFile = new File(packagePath); 14514 setMountPath(newMountPath); 14515 final File afterCodeFile = new File(packagePath); 14516 14517 // Reflect the rename in scanned details 14518 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14519 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14520 afterCodeFile, pkg.baseCodePath)); 14521 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14522 afterCodeFile, pkg.splitCodePaths)); 14523 14524 // Reflect the rename in app info 14525 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14526 pkg.setApplicationInfoCodePath(pkg.codePath); 14527 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14528 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14529 pkg.setApplicationInfoResourcePath(pkg.codePath); 14530 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14531 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14532 14533 return true; 14534 } 14535 14536 private void setMountPath(String mountPath) { 14537 final File mountFile = new File(mountPath); 14538 14539 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14540 if (monolithicFile.exists()) { 14541 packagePath = monolithicFile.getAbsolutePath(); 14542 if (isFwdLocked()) { 14543 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14544 } else { 14545 resourcePath = packagePath; 14546 } 14547 } else { 14548 packagePath = mountFile.getAbsolutePath(); 14549 resourcePath = packagePath; 14550 } 14551 } 14552 14553 int doPostInstall(int status, int uid) { 14554 if (status != PackageManager.INSTALL_SUCCEEDED) { 14555 cleanUp(); 14556 } else { 14557 final int groupOwner; 14558 final String protectedFile; 14559 if (isFwdLocked()) { 14560 groupOwner = UserHandle.getSharedAppGid(uid); 14561 protectedFile = RES_FILE_NAME; 14562 } else { 14563 groupOwner = -1; 14564 protectedFile = null; 14565 } 14566 14567 if (uid < Process.FIRST_APPLICATION_UID 14568 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14569 Slog.e(TAG, "Failed to finalize " + cid); 14570 PackageHelper.destroySdDir(cid); 14571 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14572 } 14573 14574 boolean mounted = PackageHelper.isContainerMounted(cid); 14575 if (!mounted) { 14576 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14577 } 14578 } 14579 return status; 14580 } 14581 14582 private void cleanUp() { 14583 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14584 14585 // Destroy secure container 14586 PackageHelper.destroySdDir(cid); 14587 } 14588 14589 private List<String> getAllCodePaths() { 14590 final File codeFile = new File(getCodePath()); 14591 if (codeFile != null && codeFile.exists()) { 14592 try { 14593 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14594 return pkg.getAllCodePaths(); 14595 } catch (PackageParserException e) { 14596 // Ignored; we tried our best 14597 } 14598 } 14599 return Collections.EMPTY_LIST; 14600 } 14601 14602 void cleanUpResourcesLI() { 14603 // Enumerate all code paths before deleting 14604 cleanUpResourcesLI(getAllCodePaths()); 14605 } 14606 14607 private void cleanUpResourcesLI(List<String> allCodePaths) { 14608 cleanUp(); 14609 removeDexFiles(allCodePaths, instructionSets); 14610 } 14611 14612 String getPackageName() { 14613 return getAsecPackageName(cid); 14614 } 14615 14616 boolean doPostDeleteLI(boolean delete) { 14617 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14618 final List<String> allCodePaths = getAllCodePaths(); 14619 boolean mounted = PackageHelper.isContainerMounted(cid); 14620 if (mounted) { 14621 // Unmount first 14622 if (PackageHelper.unMountSdDir(cid)) { 14623 mounted = false; 14624 } 14625 } 14626 if (!mounted && delete) { 14627 cleanUpResourcesLI(allCodePaths); 14628 } 14629 return !mounted; 14630 } 14631 14632 @Override 14633 int doPreCopy() { 14634 if (isFwdLocked()) { 14635 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14636 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14637 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14638 } 14639 } 14640 14641 return PackageManager.INSTALL_SUCCEEDED; 14642 } 14643 14644 @Override 14645 int doPostCopy(int uid) { 14646 if (isFwdLocked()) { 14647 if (uid < Process.FIRST_APPLICATION_UID 14648 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14649 RES_FILE_NAME)) { 14650 Slog.e(TAG, "Failed to finalize " + cid); 14651 PackageHelper.destroySdDir(cid); 14652 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14653 } 14654 } 14655 14656 return PackageManager.INSTALL_SUCCEEDED; 14657 } 14658 } 14659 14660 /** 14661 * Logic to handle movement of existing installed applications. 14662 */ 14663 class MoveInstallArgs extends InstallArgs { 14664 private File codeFile; 14665 private File resourceFile; 14666 14667 /** New install */ 14668 MoveInstallArgs(InstallParams params) { 14669 super(params.origin, params.move, params.observer, params.installFlags, 14670 params.installerPackageName, params.volumeUuid, 14671 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14672 params.grantedRuntimePermissions, 14673 params.traceMethod, params.traceCookie, params.certificates, 14674 params.installReason); 14675 } 14676 14677 int copyApk(IMediaContainerService imcs, boolean temp) { 14678 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14679 + move.fromUuid + " to " + move.toUuid); 14680 synchronized (mInstaller) { 14681 try { 14682 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14683 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14684 } catch (InstallerException e) { 14685 Slog.w(TAG, "Failed to move app", e); 14686 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14687 } 14688 } 14689 14690 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14691 resourceFile = codeFile; 14692 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14693 14694 return PackageManager.INSTALL_SUCCEEDED; 14695 } 14696 14697 int doPreInstall(int status) { 14698 if (status != PackageManager.INSTALL_SUCCEEDED) { 14699 cleanUp(move.toUuid); 14700 } 14701 return status; 14702 } 14703 14704 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14705 if (status != PackageManager.INSTALL_SUCCEEDED) { 14706 cleanUp(move.toUuid); 14707 return false; 14708 } 14709 14710 // Reflect the move in app info 14711 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14712 pkg.setApplicationInfoCodePath(pkg.codePath); 14713 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14714 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14715 pkg.setApplicationInfoResourcePath(pkg.codePath); 14716 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14717 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14718 14719 return true; 14720 } 14721 14722 int doPostInstall(int status, int uid) { 14723 if (status == PackageManager.INSTALL_SUCCEEDED) { 14724 cleanUp(move.fromUuid); 14725 } else { 14726 cleanUp(move.toUuid); 14727 } 14728 return status; 14729 } 14730 14731 @Override 14732 String getCodePath() { 14733 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14734 } 14735 14736 @Override 14737 String getResourcePath() { 14738 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14739 } 14740 14741 private boolean cleanUp(String volumeUuid) { 14742 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14743 move.dataAppName); 14744 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14745 final int[] userIds = sUserManager.getUserIds(); 14746 synchronized (mInstallLock) { 14747 // Clean up both app data and code 14748 // All package moves are frozen until finished 14749 for (int userId : userIds) { 14750 try { 14751 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14752 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14753 } catch (InstallerException e) { 14754 Slog.w(TAG, String.valueOf(e)); 14755 } 14756 } 14757 removeCodePathLI(codeFile); 14758 } 14759 return true; 14760 } 14761 14762 void cleanUpResourcesLI() { 14763 throw new UnsupportedOperationException(); 14764 } 14765 14766 boolean doPostDeleteLI(boolean delete) { 14767 throw new UnsupportedOperationException(); 14768 } 14769 } 14770 14771 static String getAsecPackageName(String packageCid) { 14772 int idx = packageCid.lastIndexOf("-"); 14773 if (idx == -1) { 14774 return packageCid; 14775 } 14776 return packageCid.substring(0, idx); 14777 } 14778 14779 // Utility method used to create code paths based on package name and available index. 14780 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14781 String idxStr = ""; 14782 int idx = 1; 14783 // Fall back to default value of idx=1 if prefix is not 14784 // part of oldCodePath 14785 if (oldCodePath != null) { 14786 String subStr = oldCodePath; 14787 // Drop the suffix right away 14788 if (suffix != null && subStr.endsWith(suffix)) { 14789 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14790 } 14791 // If oldCodePath already contains prefix find out the 14792 // ending index to either increment or decrement. 14793 int sidx = subStr.lastIndexOf(prefix); 14794 if (sidx != -1) { 14795 subStr = subStr.substring(sidx + prefix.length()); 14796 if (subStr != null) { 14797 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14798 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14799 } 14800 try { 14801 idx = Integer.parseInt(subStr); 14802 if (idx <= 1) { 14803 idx++; 14804 } else { 14805 idx--; 14806 } 14807 } catch(NumberFormatException e) { 14808 } 14809 } 14810 } 14811 } 14812 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14813 return prefix + idxStr; 14814 } 14815 14816 private File getNextCodePath(File targetDir, String packageName) { 14817 File result; 14818 SecureRandom random = new SecureRandom(); 14819 byte[] bytes = new byte[16]; 14820 do { 14821 random.nextBytes(bytes); 14822 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14823 result = new File(targetDir, packageName + "-" + suffix); 14824 } while (result.exists()); 14825 return result; 14826 } 14827 14828 // Utility method that returns the relative package path with respect 14829 // to the installation directory. Like say for /data/data/com.test-1.apk 14830 // string com.test-1 is returned. 14831 static String deriveCodePathName(String codePath) { 14832 if (codePath == null) { 14833 return null; 14834 } 14835 final File codeFile = new File(codePath); 14836 final String name = codeFile.getName(); 14837 if (codeFile.isDirectory()) { 14838 return name; 14839 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14840 final int lastDot = name.lastIndexOf('.'); 14841 return name.substring(0, lastDot); 14842 } else { 14843 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14844 return null; 14845 } 14846 } 14847 14848 static class PackageInstalledInfo { 14849 String name; 14850 int uid; 14851 // The set of users that originally had this package installed. 14852 int[] origUsers; 14853 // The set of users that now have this package installed. 14854 int[] newUsers; 14855 PackageParser.Package pkg; 14856 int returnCode; 14857 String returnMsg; 14858 PackageRemovedInfo removedInfo; 14859 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14860 14861 public void setError(int code, String msg) { 14862 setReturnCode(code); 14863 setReturnMessage(msg); 14864 Slog.w(TAG, msg); 14865 } 14866 14867 public void setError(String msg, PackageParserException e) { 14868 setReturnCode(e.error); 14869 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14870 Slog.w(TAG, msg, e); 14871 } 14872 14873 public void setError(String msg, PackageManagerException e) { 14874 returnCode = e.error; 14875 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14876 Slog.w(TAG, msg, e); 14877 } 14878 14879 public void setReturnCode(int returnCode) { 14880 this.returnCode = returnCode; 14881 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14882 for (int i = 0; i < childCount; i++) { 14883 addedChildPackages.valueAt(i).returnCode = returnCode; 14884 } 14885 } 14886 14887 private void setReturnMessage(String returnMsg) { 14888 this.returnMsg = returnMsg; 14889 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14890 for (int i = 0; i < childCount; i++) { 14891 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14892 } 14893 } 14894 14895 // In some error cases we want to convey more info back to the observer 14896 String origPackage; 14897 String origPermission; 14898 } 14899 14900 /* 14901 * Install a non-existing package. 14902 */ 14903 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14904 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14905 PackageInstalledInfo res, int installReason) { 14906 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14907 14908 // Remember this for later, in case we need to rollback this install 14909 String pkgName = pkg.packageName; 14910 14911 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14912 14913 synchronized(mPackages) { 14914 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14915 if (renamedPackage != null) { 14916 // A package with the same name is already installed, though 14917 // it has been renamed to an older name. The package we 14918 // are trying to install should be installed as an update to 14919 // the existing one, but that has not been requested, so bail. 14920 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14921 + " without first uninstalling package running as " 14922 + renamedPackage); 14923 return; 14924 } 14925 if (mPackages.containsKey(pkgName)) { 14926 // Don't allow installation over an existing package with the same name. 14927 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14928 + " without first uninstalling."); 14929 return; 14930 } 14931 } 14932 14933 try { 14934 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14935 System.currentTimeMillis(), user); 14936 14937 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 14938 14939 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14940 prepareAppDataAfterInstallLIF(newPackage); 14941 14942 } else { 14943 // Remove package from internal structures, but keep around any 14944 // data that might have already existed 14945 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14946 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14947 } 14948 } catch (PackageManagerException e) { 14949 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14950 } 14951 14952 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14953 } 14954 14955 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14956 // Can't rotate keys during boot or if sharedUser. 14957 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14958 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14959 return false; 14960 } 14961 // app is using upgradeKeySets; make sure all are valid 14962 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14963 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14964 for (int i = 0; i < upgradeKeySets.length; i++) { 14965 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14966 Slog.wtf(TAG, "Package " 14967 + (oldPs.name != null ? oldPs.name : "<null>") 14968 + " contains upgrade-key-set reference to unknown key-set: " 14969 + upgradeKeySets[i] 14970 + " reverting to signatures check."); 14971 return false; 14972 } 14973 } 14974 return true; 14975 } 14976 14977 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14978 // Upgrade keysets are being used. Determine if new package has a superset of the 14979 // required keys. 14980 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14981 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14982 for (int i = 0; i < upgradeKeySets.length; i++) { 14983 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14984 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14985 return true; 14986 } 14987 } 14988 return false; 14989 } 14990 14991 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14992 try (DigestInputStream digestStream = 14993 new DigestInputStream(new FileInputStream(file), digest)) { 14994 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14995 } 14996 } 14997 14998 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14999 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15000 int installReason) { 15001 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 15002 15003 final PackageParser.Package oldPackage; 15004 final String pkgName = pkg.packageName; 15005 final int[] allUsers; 15006 final int[] installedUsers; 15007 15008 synchronized(mPackages) { 15009 oldPackage = mPackages.get(pkgName); 15010 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15011 15012 // don't allow upgrade to target a release SDK from a pre-release SDK 15013 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15014 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15015 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15016 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15017 if (oldTargetsPreRelease 15018 && !newTargetsPreRelease 15019 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15020 Slog.w(TAG, "Can't install package targeting released sdk"); 15021 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15022 return; 15023 } 15024 15025 // don't allow an upgrade from full to ephemeral 15026 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 15027 if (isEphemeral && !oldIsEphemeral) { 15028 // can't downgrade from full to ephemeral 15029 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 15030 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15031 return; 15032 } 15033 15034 // verify signatures are valid 15035 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15036 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15037 if (!checkUpgradeKeySetLP(ps, pkg)) { 15038 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15039 "New package not signed by keys specified by upgrade-keysets: " 15040 + pkgName); 15041 return; 15042 } 15043 } else { 15044 // default to original signature matching 15045 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15046 != PackageManager.SIGNATURE_MATCH) { 15047 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15048 "New package has a different signature: " + pkgName); 15049 return; 15050 } 15051 } 15052 15053 // don't allow a system upgrade unless the upgrade hash matches 15054 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15055 byte[] digestBytes = null; 15056 try { 15057 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15058 updateDigest(digest, new File(pkg.baseCodePath)); 15059 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15060 for (String path : pkg.splitCodePaths) { 15061 updateDigest(digest, new File(path)); 15062 } 15063 } 15064 digestBytes = digest.digest(); 15065 } catch (NoSuchAlgorithmException | IOException e) { 15066 res.setError(INSTALL_FAILED_INVALID_APK, 15067 "Could not compute hash: " + pkgName); 15068 return; 15069 } 15070 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15071 res.setError(INSTALL_FAILED_INVALID_APK, 15072 "New package fails restrict-update check: " + pkgName); 15073 return; 15074 } 15075 // retain upgrade restriction 15076 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15077 } 15078 15079 // Check for shared user id changes 15080 String invalidPackageName = 15081 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15082 if (invalidPackageName != null) { 15083 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15084 "Package " + invalidPackageName + " tried to change user " 15085 + oldPackage.mSharedUserId); 15086 return; 15087 } 15088 15089 // In case of rollback, remember per-user/profile install state 15090 allUsers = sUserManager.getUserIds(); 15091 installedUsers = ps.queryInstalledUsers(allUsers, true); 15092 } 15093 15094 // Update what is removed 15095 res.removedInfo = new PackageRemovedInfo(); 15096 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15097 res.removedInfo.removedPackage = oldPackage.packageName; 15098 res.removedInfo.isUpdate = true; 15099 res.removedInfo.origUsers = installedUsers; 15100 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15101 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15102 for (int i = 0; i < installedUsers.length; i++) { 15103 final int userId = installedUsers[i]; 15104 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15105 } 15106 15107 final int childCount = (oldPackage.childPackages != null) 15108 ? oldPackage.childPackages.size() : 0; 15109 for (int i = 0; i < childCount; i++) { 15110 boolean childPackageUpdated = false; 15111 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15112 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15113 if (res.addedChildPackages != null) { 15114 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15115 if (childRes != null) { 15116 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15117 childRes.removedInfo.removedPackage = childPkg.packageName; 15118 childRes.removedInfo.isUpdate = true; 15119 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15120 childPackageUpdated = true; 15121 } 15122 } 15123 if (!childPackageUpdated) { 15124 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15125 childRemovedRes.removedPackage = childPkg.packageName; 15126 childRemovedRes.isUpdate = false; 15127 childRemovedRes.dataRemoved = true; 15128 synchronized (mPackages) { 15129 if (childPs != null) { 15130 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15131 } 15132 } 15133 if (res.removedInfo.removedChildPackages == null) { 15134 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15135 } 15136 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15137 } 15138 } 15139 15140 boolean sysPkg = (isSystemApp(oldPackage)); 15141 if (sysPkg) { 15142 // Set the system/privileged flags as needed 15143 final boolean privileged = 15144 (oldPackage.applicationInfo.privateFlags 15145 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15146 final int systemPolicyFlags = policyFlags 15147 | PackageParser.PARSE_IS_SYSTEM 15148 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15149 15150 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15151 user, allUsers, installerPackageName, res, installReason); 15152 } else { 15153 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15154 user, allUsers, installerPackageName, res, installReason); 15155 } 15156 } 15157 15158 public List<String> getPreviousCodePaths(String packageName) { 15159 final PackageSetting ps = mSettings.mPackages.get(packageName); 15160 final List<String> result = new ArrayList<String>(); 15161 if (ps != null && ps.oldCodePaths != null) { 15162 result.addAll(ps.oldCodePaths); 15163 } 15164 return result; 15165 } 15166 15167 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15168 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15169 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15170 int installReason) { 15171 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15172 + deletedPackage); 15173 15174 String pkgName = deletedPackage.packageName; 15175 boolean deletedPkg = true; 15176 boolean addedPkg = false; 15177 boolean updatedSettings = false; 15178 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15179 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15180 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15181 15182 final long origUpdateTime = (pkg.mExtras != null) 15183 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15184 15185 // First delete the existing package while retaining the data directory 15186 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15187 res.removedInfo, true, pkg)) { 15188 // If the existing package wasn't successfully deleted 15189 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15190 deletedPkg = false; 15191 } else { 15192 // Successfully deleted the old package; proceed with replace. 15193 15194 // If deleted package lived in a container, give users a chance to 15195 // relinquish resources before killing. 15196 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15197 if (DEBUG_INSTALL) { 15198 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15199 } 15200 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15201 final ArrayList<String> pkgList = new ArrayList<String>(1); 15202 pkgList.add(deletedPackage.applicationInfo.packageName); 15203 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15204 } 15205 15206 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15207 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15208 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15209 15210 try { 15211 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15212 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15213 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15214 installReason); 15215 15216 // Update the in-memory copy of the previous code paths. 15217 PackageSetting ps = mSettings.mPackages.get(pkgName); 15218 if (!killApp) { 15219 if (ps.oldCodePaths == null) { 15220 ps.oldCodePaths = new ArraySet<>(); 15221 } 15222 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15223 if (deletedPackage.splitCodePaths != null) { 15224 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15225 } 15226 } else { 15227 ps.oldCodePaths = null; 15228 } 15229 if (ps.childPackageNames != null) { 15230 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15231 final String childPkgName = ps.childPackageNames.get(i); 15232 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15233 childPs.oldCodePaths = ps.oldCodePaths; 15234 } 15235 } 15236 prepareAppDataAfterInstallLIF(newPackage); 15237 addedPkg = true; 15238 } catch (PackageManagerException e) { 15239 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15240 } 15241 } 15242 15243 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15244 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15245 15246 // Revert all internal state mutations and added folders for the failed install 15247 if (addedPkg) { 15248 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15249 res.removedInfo, true, null); 15250 } 15251 15252 // Restore the old package 15253 if (deletedPkg) { 15254 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15255 File restoreFile = new File(deletedPackage.codePath); 15256 // Parse old package 15257 boolean oldExternal = isExternal(deletedPackage); 15258 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15259 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15260 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15261 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15262 try { 15263 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15264 null); 15265 } catch (PackageManagerException e) { 15266 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15267 + e.getMessage()); 15268 return; 15269 } 15270 15271 synchronized (mPackages) { 15272 // Ensure the installer package name up to date 15273 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15274 15275 // Update permissions for restored package 15276 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15277 15278 mSettings.writeLPr(); 15279 } 15280 15281 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15282 } 15283 } else { 15284 synchronized (mPackages) { 15285 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15286 if (ps != null) { 15287 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15288 if (res.removedInfo.removedChildPackages != null) { 15289 final int childCount = res.removedInfo.removedChildPackages.size(); 15290 // Iterate in reverse as we may modify the collection 15291 for (int i = childCount - 1; i >= 0; i--) { 15292 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15293 if (res.addedChildPackages.containsKey(childPackageName)) { 15294 res.removedInfo.removedChildPackages.removeAt(i); 15295 } else { 15296 PackageRemovedInfo childInfo = res.removedInfo 15297 .removedChildPackages.valueAt(i); 15298 childInfo.removedForAllUsers = mPackages.get( 15299 childInfo.removedPackage) == null; 15300 } 15301 } 15302 } 15303 } 15304 } 15305 } 15306 } 15307 15308 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15309 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15310 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15311 int installReason) { 15312 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15313 + ", old=" + deletedPackage); 15314 15315 final boolean disabledSystem; 15316 15317 // Remove existing system package 15318 removePackageLI(deletedPackage, true); 15319 15320 synchronized (mPackages) { 15321 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15322 } 15323 if (!disabledSystem) { 15324 // We didn't need to disable the .apk as a current system package, 15325 // which means we are replacing another update that is already 15326 // installed. We need to make sure to delete the older one's .apk. 15327 res.removedInfo.args = createInstallArgsForExisting(0, 15328 deletedPackage.applicationInfo.getCodePath(), 15329 deletedPackage.applicationInfo.getResourcePath(), 15330 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15331 } else { 15332 res.removedInfo.args = null; 15333 } 15334 15335 // Successfully disabled the old package. Now proceed with re-installation 15336 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15337 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15338 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15339 15340 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15341 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15342 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15343 15344 PackageParser.Package newPackage = null; 15345 try { 15346 // Add the package to the internal data structures 15347 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 15348 15349 // Set the update and install times 15350 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15351 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15352 System.currentTimeMillis()); 15353 15354 // Update the package dynamic state if succeeded 15355 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15356 // Now that the install succeeded make sure we remove data 15357 // directories for any child package the update removed. 15358 final int deletedChildCount = (deletedPackage.childPackages != null) 15359 ? deletedPackage.childPackages.size() : 0; 15360 final int newChildCount = (newPackage.childPackages != null) 15361 ? newPackage.childPackages.size() : 0; 15362 for (int i = 0; i < deletedChildCount; i++) { 15363 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15364 boolean childPackageDeleted = true; 15365 for (int j = 0; j < newChildCount; j++) { 15366 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15367 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15368 childPackageDeleted = false; 15369 break; 15370 } 15371 } 15372 if (childPackageDeleted) { 15373 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15374 deletedChildPkg.packageName); 15375 if (ps != null && res.removedInfo.removedChildPackages != null) { 15376 PackageRemovedInfo removedChildRes = res.removedInfo 15377 .removedChildPackages.get(deletedChildPkg.packageName); 15378 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15379 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15380 } 15381 } 15382 } 15383 15384 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15385 installReason); 15386 prepareAppDataAfterInstallLIF(newPackage); 15387 } 15388 } catch (PackageManagerException e) { 15389 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15390 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15391 } 15392 15393 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15394 // Re installation failed. Restore old information 15395 // Remove new pkg information 15396 if (newPackage != null) { 15397 removeInstalledPackageLI(newPackage, true); 15398 } 15399 // Add back the old system package 15400 try { 15401 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15402 } catch (PackageManagerException e) { 15403 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15404 } 15405 15406 synchronized (mPackages) { 15407 if (disabledSystem) { 15408 enableSystemPackageLPw(deletedPackage); 15409 } 15410 15411 // Ensure the installer package name up to date 15412 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15413 15414 // Update permissions for restored package 15415 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15416 15417 mSettings.writeLPr(); 15418 } 15419 15420 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15421 + " after failed upgrade"); 15422 } 15423 } 15424 15425 /** 15426 * Checks whether the parent or any of the child packages have a change shared 15427 * user. For a package to be a valid update the shred users of the parent and 15428 * the children should match. We may later support changing child shared users. 15429 * @param oldPkg The updated package. 15430 * @param newPkg The update package. 15431 * @return The shared user that change between the versions. 15432 */ 15433 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15434 PackageParser.Package newPkg) { 15435 // Check parent shared user 15436 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15437 return newPkg.packageName; 15438 } 15439 // Check child shared users 15440 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15441 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15442 for (int i = 0; i < newChildCount; i++) { 15443 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15444 // If this child was present, did it have the same shared user? 15445 for (int j = 0; j < oldChildCount; j++) { 15446 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15447 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15448 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15449 return newChildPkg.packageName; 15450 } 15451 } 15452 } 15453 return null; 15454 } 15455 15456 private void removeNativeBinariesLI(PackageSetting ps) { 15457 // Remove the lib path for the parent package 15458 if (ps != null) { 15459 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15460 // Remove the lib path for the child packages 15461 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15462 for (int i = 0; i < childCount; i++) { 15463 PackageSetting childPs = null; 15464 synchronized (mPackages) { 15465 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15466 } 15467 if (childPs != null) { 15468 NativeLibraryHelper.removeNativeBinariesLI(childPs 15469 .legacyNativeLibraryPathString); 15470 } 15471 } 15472 } 15473 } 15474 15475 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15476 // Enable the parent package 15477 mSettings.enableSystemPackageLPw(pkg.packageName); 15478 // Enable the child packages 15479 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15480 for (int i = 0; i < childCount; i++) { 15481 PackageParser.Package childPkg = pkg.childPackages.get(i); 15482 mSettings.enableSystemPackageLPw(childPkg.packageName); 15483 } 15484 } 15485 15486 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15487 PackageParser.Package newPkg) { 15488 // Disable the parent package (parent always replaced) 15489 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15490 // Disable the child packages 15491 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15492 for (int i = 0; i < childCount; i++) { 15493 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15494 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15495 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15496 } 15497 return disabled; 15498 } 15499 15500 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15501 String installerPackageName) { 15502 // Enable the parent package 15503 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15504 // Enable the child packages 15505 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15506 for (int i = 0; i < childCount; i++) { 15507 PackageParser.Package childPkg = pkg.childPackages.get(i); 15508 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15509 } 15510 } 15511 15512 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15513 // Collect all used permissions in the UID 15514 ArraySet<String> usedPermissions = new ArraySet<>(); 15515 final int packageCount = su.packages.size(); 15516 for (int i = 0; i < packageCount; i++) { 15517 PackageSetting ps = su.packages.valueAt(i); 15518 if (ps.pkg == null) { 15519 continue; 15520 } 15521 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15522 for (int j = 0; j < requestedPermCount; j++) { 15523 String permission = ps.pkg.requestedPermissions.get(j); 15524 BasePermission bp = mSettings.mPermissions.get(permission); 15525 if (bp != null) { 15526 usedPermissions.add(permission); 15527 } 15528 } 15529 } 15530 15531 PermissionsState permissionsState = su.getPermissionsState(); 15532 // Prune install permissions 15533 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15534 final int installPermCount = installPermStates.size(); 15535 for (int i = installPermCount - 1; i >= 0; i--) { 15536 PermissionState permissionState = installPermStates.get(i); 15537 if (!usedPermissions.contains(permissionState.getName())) { 15538 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15539 if (bp != null) { 15540 permissionsState.revokeInstallPermission(bp); 15541 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15542 PackageManager.MASK_PERMISSION_FLAGS, 0); 15543 } 15544 } 15545 } 15546 15547 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15548 15549 // Prune runtime permissions 15550 for (int userId : allUserIds) { 15551 List<PermissionState> runtimePermStates = permissionsState 15552 .getRuntimePermissionStates(userId); 15553 final int runtimePermCount = runtimePermStates.size(); 15554 for (int i = runtimePermCount - 1; i >= 0; i--) { 15555 PermissionState permissionState = runtimePermStates.get(i); 15556 if (!usedPermissions.contains(permissionState.getName())) { 15557 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15558 if (bp != null) { 15559 permissionsState.revokeRuntimePermission(bp, userId); 15560 permissionsState.updatePermissionFlags(bp, userId, 15561 PackageManager.MASK_PERMISSION_FLAGS, 0); 15562 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15563 runtimePermissionChangedUserIds, userId); 15564 } 15565 } 15566 } 15567 } 15568 15569 return runtimePermissionChangedUserIds; 15570 } 15571 15572 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15573 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 15574 // Update the parent package setting 15575 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15576 res, user, installReason); 15577 // Update the child packages setting 15578 final int childCount = (newPackage.childPackages != null) 15579 ? newPackage.childPackages.size() : 0; 15580 for (int i = 0; i < childCount; i++) { 15581 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15582 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15583 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15584 childRes.origUsers, childRes, user, installReason); 15585 } 15586 } 15587 15588 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15589 String installerPackageName, int[] allUsers, int[] installedForUsers, 15590 PackageInstalledInfo res, UserHandle user, int installReason) { 15591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15592 15593 String pkgName = newPackage.packageName; 15594 synchronized (mPackages) { 15595 //write settings. the installStatus will be incomplete at this stage. 15596 //note that the new package setting would have already been 15597 //added to mPackages. It hasn't been persisted yet. 15598 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15599 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15600 mSettings.writeLPr(); 15601 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15602 } 15603 15604 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15605 synchronized (mPackages) { 15606 updatePermissionsLPw(newPackage.packageName, newPackage, 15607 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15608 ? UPDATE_PERMISSIONS_ALL : 0)); 15609 // For system-bundled packages, we assume that installing an upgraded version 15610 // of the package implies that the user actually wants to run that new code, 15611 // so we enable the package. 15612 PackageSetting ps = mSettings.mPackages.get(pkgName); 15613 final int userId = user.getIdentifier(); 15614 if (ps != null) { 15615 if (isSystemApp(newPackage)) { 15616 if (DEBUG_INSTALL) { 15617 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15618 } 15619 // Enable system package for requested users 15620 if (res.origUsers != null) { 15621 for (int origUserId : res.origUsers) { 15622 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15623 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15624 origUserId, installerPackageName); 15625 } 15626 } 15627 } 15628 // Also convey the prior install/uninstall state 15629 if (allUsers != null && installedForUsers != null) { 15630 for (int currentUserId : allUsers) { 15631 final boolean installed = ArrayUtils.contains( 15632 installedForUsers, currentUserId); 15633 if (DEBUG_INSTALL) { 15634 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15635 } 15636 ps.setInstalled(installed, currentUserId); 15637 } 15638 // these install state changes will be persisted in the 15639 // upcoming call to mSettings.writeLPr(). 15640 } 15641 } 15642 // It's implied that when a user requests installation, they want the app to be 15643 // installed and enabled. 15644 if (userId != UserHandle.USER_ALL) { 15645 ps.setInstalled(true, userId); 15646 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15647 } 15648 15649 // When replacing an existing package, preserve the original install reason for all 15650 // users that had the package installed before. 15651 final Set<Integer> previousUserIds = new ArraySet<>(); 15652 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 15653 final int installReasonCount = res.removedInfo.installReasons.size(); 15654 for (int i = 0; i < installReasonCount; i++) { 15655 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 15656 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 15657 ps.setInstallReason(previousInstallReason, previousUserId); 15658 previousUserIds.add(previousUserId); 15659 } 15660 } 15661 15662 // Set install reason for users that are having the package newly installed. 15663 if (userId == UserHandle.USER_ALL) { 15664 for (int currentUserId : sUserManager.getUserIds()) { 15665 if (!previousUserIds.contains(currentUserId)) { 15666 ps.setInstallReason(installReason, currentUserId); 15667 } 15668 } 15669 } else if (!previousUserIds.contains(userId)) { 15670 ps.setInstallReason(installReason, userId); 15671 } 15672 } 15673 res.name = pkgName; 15674 res.uid = newPackage.applicationInfo.uid; 15675 res.pkg = newPackage; 15676 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15677 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15678 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15679 //to update install status 15680 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15681 mSettings.writeLPr(); 15682 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15683 } 15684 15685 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15686 } 15687 15688 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15689 try { 15690 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15691 installPackageLI(args, res); 15692 } finally { 15693 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15694 } 15695 } 15696 15697 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15698 final int installFlags = args.installFlags; 15699 final String installerPackageName = args.installerPackageName; 15700 final String volumeUuid = args.volumeUuid; 15701 final File tmpPackageFile = new File(args.getCodePath()); 15702 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15703 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15704 || (args.volumeUuid != null)); 15705 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15706 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15707 boolean replace = false; 15708 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15709 if (args.move != null) { 15710 // moving a complete application; perform an initial scan on the new install location 15711 scanFlags |= SCAN_INITIAL; 15712 } 15713 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15714 scanFlags |= SCAN_DONT_KILL_APP; 15715 } 15716 15717 // Result object to be returned 15718 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15719 15720 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15721 15722 // Sanity check 15723 if (ephemeral && (forwardLocked || onExternal)) { 15724 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15725 + " external=" + onExternal); 15726 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15727 return; 15728 } 15729 15730 // Retrieve PackageSettings and parse package 15731 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15732 | PackageParser.PARSE_ENFORCE_CODE 15733 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15734 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15735 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15736 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15737 PackageParser pp = new PackageParser(); 15738 pp.setSeparateProcesses(mSeparateProcesses); 15739 pp.setDisplayMetrics(mMetrics); 15740 15741 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15742 final PackageParser.Package pkg; 15743 try { 15744 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15745 } catch (PackageParserException e) { 15746 res.setError("Failed parse during installPackageLI", e); 15747 return; 15748 } finally { 15749 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15750 } 15751 15752 // Ephemeral apps must have target SDK >= O. 15753 // TODO: Update conditional and error message when O gets locked down 15754 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 15755 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 15756 "Ephemeral apps must have target SDK version of at least O"); 15757 return; 15758 } 15759 15760 // If we are installing a clustered package add results for the children 15761 if (pkg.childPackages != null) { 15762 synchronized (mPackages) { 15763 final int childCount = pkg.childPackages.size(); 15764 for (int i = 0; i < childCount; i++) { 15765 PackageParser.Package childPkg = pkg.childPackages.get(i); 15766 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15767 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15768 childRes.pkg = childPkg; 15769 childRes.name = childPkg.packageName; 15770 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15771 if (childPs != null) { 15772 childRes.origUsers = childPs.queryInstalledUsers( 15773 sUserManager.getUserIds(), true); 15774 } 15775 if ((mPackages.containsKey(childPkg.packageName))) { 15776 childRes.removedInfo = new PackageRemovedInfo(); 15777 childRes.removedInfo.removedPackage = childPkg.packageName; 15778 } 15779 if (res.addedChildPackages == null) { 15780 res.addedChildPackages = new ArrayMap<>(); 15781 } 15782 res.addedChildPackages.put(childPkg.packageName, childRes); 15783 } 15784 } 15785 } 15786 15787 // If package doesn't declare API override, mark that we have an install 15788 // time CPU ABI override. 15789 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15790 pkg.cpuAbiOverride = args.abiOverride; 15791 } 15792 15793 String pkgName = res.name = pkg.packageName; 15794 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15795 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15796 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15797 return; 15798 } 15799 } 15800 15801 try { 15802 // either use what we've been given or parse directly from the APK 15803 if (args.certificates != null) { 15804 try { 15805 PackageParser.populateCertificates(pkg, args.certificates); 15806 } catch (PackageParserException e) { 15807 // there was something wrong with the certificates we were given; 15808 // try to pull them from the APK 15809 PackageParser.collectCertificates(pkg, parseFlags); 15810 } 15811 } else { 15812 PackageParser.collectCertificates(pkg, parseFlags); 15813 } 15814 } catch (PackageParserException e) { 15815 res.setError("Failed collect during installPackageLI", e); 15816 return; 15817 } 15818 15819 // Get rid of all references to package scan path via parser. 15820 pp = null; 15821 String oldCodePath = null; 15822 boolean systemApp = false; 15823 synchronized (mPackages) { 15824 // Check if installing already existing package 15825 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15826 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15827 if (pkg.mOriginalPackages != null 15828 && pkg.mOriginalPackages.contains(oldName) 15829 && mPackages.containsKey(oldName)) { 15830 // This package is derived from an original package, 15831 // and this device has been updating from that original 15832 // name. We must continue using the original name, so 15833 // rename the new package here. 15834 pkg.setPackageName(oldName); 15835 pkgName = pkg.packageName; 15836 replace = true; 15837 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15838 + oldName + " pkgName=" + pkgName); 15839 } else if (mPackages.containsKey(pkgName)) { 15840 // This package, under its official name, already exists 15841 // on the device; we should replace it. 15842 replace = true; 15843 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15844 } 15845 15846 // Child packages are installed through the parent package 15847 if (pkg.parentPackage != null) { 15848 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15849 "Package " + pkg.packageName + " is child of package " 15850 + pkg.parentPackage.parentPackage + ". Child packages " 15851 + "can be updated only through the parent package."); 15852 return; 15853 } 15854 15855 if (replace) { 15856 // Prevent apps opting out from runtime permissions 15857 PackageParser.Package oldPackage = mPackages.get(pkgName); 15858 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15859 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15860 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15861 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15862 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15863 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15864 + " doesn't support runtime permissions but the old" 15865 + " target SDK " + oldTargetSdk + " does."); 15866 return; 15867 } 15868 15869 // Prevent installing of child packages 15870 if (oldPackage.parentPackage != null) { 15871 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15872 "Package " + pkg.packageName + " is child of package " 15873 + oldPackage.parentPackage + ". Child packages " 15874 + "can be updated only through the parent package."); 15875 return; 15876 } 15877 } 15878 } 15879 15880 PackageSetting ps = mSettings.mPackages.get(pkgName); 15881 if (ps != null) { 15882 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15883 15884 // Quick sanity check that we're signed correctly if updating; 15885 // we'll check this again later when scanning, but we want to 15886 // bail early here before tripping over redefined permissions. 15887 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15888 if (!checkUpgradeKeySetLP(ps, pkg)) { 15889 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15890 + pkg.packageName + " upgrade keys do not match the " 15891 + "previously installed version"); 15892 return; 15893 } 15894 } else { 15895 try { 15896 verifySignaturesLP(ps, pkg); 15897 } catch (PackageManagerException e) { 15898 res.setError(e.error, e.getMessage()); 15899 return; 15900 } 15901 } 15902 15903 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15904 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15905 systemApp = (ps.pkg.applicationInfo.flags & 15906 ApplicationInfo.FLAG_SYSTEM) != 0; 15907 } 15908 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15909 } 15910 15911 // Check whether the newly-scanned package wants to define an already-defined perm 15912 int N = pkg.permissions.size(); 15913 for (int i = N-1; i >= 0; i--) { 15914 PackageParser.Permission perm = pkg.permissions.get(i); 15915 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15916 if (bp != null) { 15917 // If the defining package is signed with our cert, it's okay. This 15918 // also includes the "updating the same package" case, of course. 15919 // "updating same package" could also involve key-rotation. 15920 final boolean sigsOk; 15921 if (bp.sourcePackage.equals(pkg.packageName) 15922 && (bp.packageSetting instanceof PackageSetting) 15923 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15924 scanFlags))) { 15925 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15926 } else { 15927 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15928 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15929 } 15930 if (!sigsOk) { 15931 // If the owning package is the system itself, we log but allow 15932 // install to proceed; we fail the install on all other permission 15933 // redefinitions. 15934 if (!bp.sourcePackage.equals("android")) { 15935 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15936 + pkg.packageName + " attempting to redeclare permission " 15937 + perm.info.name + " already owned by " + bp.sourcePackage); 15938 res.origPermission = perm.info.name; 15939 res.origPackage = bp.sourcePackage; 15940 return; 15941 } else { 15942 Slog.w(TAG, "Package " + pkg.packageName 15943 + " attempting to redeclare system permission " 15944 + perm.info.name + "; ignoring new declaration"); 15945 pkg.permissions.remove(i); 15946 } 15947 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 15948 // Prevent apps to change protection level to dangerous from any other 15949 // type as this would allow a privilege escalation where an app adds a 15950 // normal/signature permission in other app's group and later redefines 15951 // it as dangerous leading to the group auto-grant. 15952 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 15953 == PermissionInfo.PROTECTION_DANGEROUS) { 15954 if (bp != null && !bp.isRuntime()) { 15955 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 15956 + "non-runtime permission " + perm.info.name 15957 + " to runtime; keeping old protection level"); 15958 perm.info.protectionLevel = bp.protectionLevel; 15959 } 15960 } 15961 } 15962 } 15963 } 15964 } 15965 15966 if (systemApp) { 15967 if (onExternal) { 15968 // Abort update; system app can't be replaced with app on sdcard 15969 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15970 "Cannot install updates to system apps on sdcard"); 15971 return; 15972 } else if (ephemeral) { 15973 // Abort update; system app can't be replaced with an ephemeral app 15974 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15975 "Cannot update a system app with an ephemeral app"); 15976 return; 15977 } 15978 } 15979 15980 if (args.move != null) { 15981 // We did an in-place move, so dex is ready to roll 15982 scanFlags |= SCAN_NO_DEX; 15983 scanFlags |= SCAN_MOVE; 15984 15985 synchronized (mPackages) { 15986 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15987 if (ps == null) { 15988 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15989 "Missing settings for moved package " + pkgName); 15990 } 15991 15992 // We moved the entire application as-is, so bring over the 15993 // previously derived ABI information. 15994 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15995 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15996 } 15997 15998 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15999 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16000 scanFlags |= SCAN_NO_DEX; 16001 16002 try { 16003 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16004 args.abiOverride : pkg.cpuAbiOverride); 16005 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16006 true /*extractLibs*/, mAppLib32InstallDir); 16007 } catch (PackageManagerException pme) { 16008 Slog.e(TAG, "Error deriving application ABI", pme); 16009 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16010 return; 16011 } 16012 16013 // Shared libraries for the package need to be updated. 16014 synchronized (mPackages) { 16015 try { 16016 updateSharedLibrariesLPr(pkg, null); 16017 } catch (PackageManagerException e) { 16018 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 16019 } 16020 } 16021 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16022 // Do not run PackageDexOptimizer through the local performDexOpt 16023 // method because `pkg` may not be in `mPackages` yet. 16024 // 16025 // Also, don't fail application installs if the dexopt step fails. 16026 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16027 null /* instructionSets */, false /* checkProfiles */, 16028 getCompilerFilterForReason(REASON_INSTALL), 16029 getOrCreateCompilerPackageStats(pkg)); 16030 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16031 16032 // Notify BackgroundDexOptService that the package has been changed. 16033 // If this is an update of a package which used to fail to compile, 16034 // BDOS will remove it from its blacklist. 16035 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16036 } 16037 16038 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16039 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16040 return; 16041 } 16042 16043 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16044 16045 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16046 "installPackageLI")) { 16047 if (replace) { 16048 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16049 installerPackageName, res, args.installReason); 16050 } else { 16051 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16052 args.user, installerPackageName, volumeUuid, res, args.installReason); 16053 } 16054 } 16055 synchronized (mPackages) { 16056 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16057 if (ps != null) { 16058 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16059 } 16060 16061 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16062 for (int i = 0; i < childCount; i++) { 16063 PackageParser.Package childPkg = pkg.childPackages.get(i); 16064 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16065 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16066 if (childPs != null) { 16067 childRes.newUsers = childPs.queryInstalledUsers( 16068 sUserManager.getUserIds(), true); 16069 } 16070 } 16071 } 16072 } 16073 16074 private void startIntentFilterVerifications(int userId, boolean replacing, 16075 PackageParser.Package pkg) { 16076 if (mIntentFilterVerifierComponent == null) { 16077 Slog.w(TAG, "No IntentFilter verification will not be done as " 16078 + "there is no IntentFilterVerifier available!"); 16079 return; 16080 } 16081 16082 final int verifierUid = getPackageUid( 16083 mIntentFilterVerifierComponent.getPackageName(), 16084 MATCH_DEBUG_TRIAGED_MISSING, 16085 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16086 16087 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16088 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16089 mHandler.sendMessage(msg); 16090 16091 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16092 for (int i = 0; i < childCount; i++) { 16093 PackageParser.Package childPkg = pkg.childPackages.get(i); 16094 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16095 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16096 mHandler.sendMessage(msg); 16097 } 16098 } 16099 16100 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16101 PackageParser.Package pkg) { 16102 int size = pkg.activities.size(); 16103 if (size == 0) { 16104 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16105 "No activity, so no need to verify any IntentFilter!"); 16106 return; 16107 } 16108 16109 final boolean hasDomainURLs = hasDomainURLs(pkg); 16110 if (!hasDomainURLs) { 16111 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16112 "No domain URLs, so no need to verify any IntentFilter!"); 16113 return; 16114 } 16115 16116 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16117 + " if any IntentFilter from the " + size 16118 + " Activities needs verification ..."); 16119 16120 int count = 0; 16121 final String packageName = pkg.packageName; 16122 16123 synchronized (mPackages) { 16124 // If this is a new install and we see that we've already run verification for this 16125 // package, we have nothing to do: it means the state was restored from backup. 16126 if (!replacing) { 16127 IntentFilterVerificationInfo ivi = 16128 mSettings.getIntentFilterVerificationLPr(packageName); 16129 if (ivi != null) { 16130 if (DEBUG_DOMAIN_VERIFICATION) { 16131 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16132 + ivi.getStatusString()); 16133 } 16134 return; 16135 } 16136 } 16137 16138 // If any filters need to be verified, then all need to be. 16139 boolean needToVerify = false; 16140 for (PackageParser.Activity a : pkg.activities) { 16141 for (ActivityIntentInfo filter : a.intents) { 16142 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16143 if (DEBUG_DOMAIN_VERIFICATION) { 16144 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16145 } 16146 needToVerify = true; 16147 break; 16148 } 16149 } 16150 } 16151 16152 if (needToVerify) { 16153 final int verificationId = mIntentFilterVerificationToken++; 16154 for (PackageParser.Activity a : pkg.activities) { 16155 for (ActivityIntentInfo filter : a.intents) { 16156 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16157 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16158 "Verification needed for IntentFilter:" + filter.toString()); 16159 mIntentFilterVerifier.addOneIntentFilterVerification( 16160 verifierUid, userId, verificationId, filter, packageName); 16161 count++; 16162 } 16163 } 16164 } 16165 } 16166 } 16167 16168 if (count > 0) { 16169 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16170 + " IntentFilter verification" + (count > 1 ? "s" : "") 16171 + " for userId:" + userId); 16172 mIntentFilterVerifier.startVerifications(userId); 16173 } else { 16174 if (DEBUG_DOMAIN_VERIFICATION) { 16175 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16176 } 16177 } 16178 } 16179 16180 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16181 final ComponentName cn = filter.activity.getComponentName(); 16182 final String packageName = cn.getPackageName(); 16183 16184 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 16185 packageName); 16186 if (ivi == null) { 16187 return true; 16188 } 16189 int status = ivi.getStatus(); 16190 switch (status) { 16191 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 16192 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 16193 return true; 16194 16195 default: 16196 // Nothing to do 16197 return false; 16198 } 16199 } 16200 16201 private static boolean isMultiArch(ApplicationInfo info) { 16202 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 16203 } 16204 16205 private static boolean isExternal(PackageParser.Package pkg) { 16206 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16207 } 16208 16209 private static boolean isExternal(PackageSetting ps) { 16210 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16211 } 16212 16213 private static boolean isEphemeral(PackageParser.Package pkg) { 16214 return pkg.applicationInfo.isEphemeralApp(); 16215 } 16216 16217 private static boolean isEphemeral(PackageSetting ps) { 16218 return ps.pkg != null && isEphemeral(ps.pkg); 16219 } 16220 16221 private static boolean isSystemApp(PackageParser.Package pkg) { 16222 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 16223 } 16224 16225 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 16226 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16227 } 16228 16229 private static boolean hasDomainURLs(PackageParser.Package pkg) { 16230 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 16231 } 16232 16233 private static boolean isSystemApp(PackageSetting ps) { 16234 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 16235 } 16236 16237 private static boolean isUpdatedSystemApp(PackageSetting ps) { 16238 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 16239 } 16240 16241 private int packageFlagsToInstallFlags(PackageSetting ps) { 16242 int installFlags = 0; 16243 if (isEphemeral(ps)) { 16244 installFlags |= PackageManager.INSTALL_EPHEMERAL; 16245 } 16246 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 16247 // This existing package was an external ASEC install when we have 16248 // the external flag without a UUID 16249 installFlags |= PackageManager.INSTALL_EXTERNAL; 16250 } 16251 if (ps.isForwardLocked()) { 16252 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16253 } 16254 return installFlags; 16255 } 16256 16257 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 16258 if (isExternal(pkg)) { 16259 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16260 return StorageManager.UUID_PRIMARY_PHYSICAL; 16261 } else { 16262 return pkg.volumeUuid; 16263 } 16264 } else { 16265 return StorageManager.UUID_PRIVATE_INTERNAL; 16266 } 16267 } 16268 16269 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16270 if (isExternal(pkg)) { 16271 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16272 return mSettings.getExternalVersion(); 16273 } else { 16274 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16275 } 16276 } else { 16277 return mSettings.getInternalVersion(); 16278 } 16279 } 16280 16281 private void deleteTempPackageFiles() { 16282 final FilenameFilter filter = new FilenameFilter() { 16283 public boolean accept(File dir, String name) { 16284 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16285 } 16286 }; 16287 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16288 file.delete(); 16289 } 16290 } 16291 16292 @Override 16293 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 16294 int flags) { 16295 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 16296 flags); 16297 } 16298 16299 @Override 16300 public void deletePackage(final String packageName, 16301 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16302 mContext.enforceCallingOrSelfPermission( 16303 android.Manifest.permission.DELETE_PACKAGES, null); 16304 Preconditions.checkNotNull(packageName); 16305 Preconditions.checkNotNull(observer); 16306 final int uid = Binder.getCallingUid(); 16307 if (!isOrphaned(packageName) 16308 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 16309 try { 16310 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16311 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16312 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16313 observer.onUserActionRequired(intent); 16314 } catch (RemoteException re) { 16315 } 16316 return; 16317 } 16318 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16319 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16320 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16321 mContext.enforceCallingOrSelfPermission( 16322 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16323 "deletePackage for user " + userId); 16324 } 16325 16326 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16327 try { 16328 observer.onPackageDeleted(packageName, 16329 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16330 } catch (RemoteException re) { 16331 } 16332 return; 16333 } 16334 16335 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 16336 try { 16337 observer.onPackageDeleted(packageName, 16338 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16339 } catch (RemoteException re) { 16340 } 16341 return; 16342 } 16343 16344 if (DEBUG_REMOVE) { 16345 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 16346 + " deleteAllUsers: " + deleteAllUsers ); 16347 } 16348 // Queue up an async operation since the package deletion may take a little while. 16349 mHandler.post(new Runnable() { 16350 public void run() { 16351 mHandler.removeCallbacks(this); 16352 int returnCode; 16353 if (!deleteAllUsers) { 16354 returnCode = deletePackageX(packageName, userId, deleteFlags); 16355 } else { 16356 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 16357 // If nobody is blocking uninstall, proceed with delete for all users 16358 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16359 returnCode = deletePackageX(packageName, userId, deleteFlags); 16360 } else { 16361 // Otherwise uninstall individually for users with blockUninstalls=false 16362 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16363 for (int userId : users) { 16364 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16365 returnCode = deletePackageX(packageName, userId, userFlags); 16366 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16367 Slog.w(TAG, "Package delete failed for user " + userId 16368 + ", returnCode " + returnCode); 16369 } 16370 } 16371 } 16372 // The app has only been marked uninstalled for certain users. 16373 // We still need to report that delete was blocked 16374 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16375 } 16376 } 16377 try { 16378 observer.onPackageDeleted(packageName, returnCode, null); 16379 } catch (RemoteException e) { 16380 Log.i(TAG, "Observer no longer exists."); 16381 } //end catch 16382 } //end run 16383 }); 16384 } 16385 16386 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 16387 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 16388 || callingUid == Process.SYSTEM_UID) { 16389 return true; 16390 } 16391 final int callingUserId = UserHandle.getUserId(callingUid); 16392 // If the caller installed the pkgName, then allow it to silently uninstall. 16393 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 16394 return true; 16395 } 16396 16397 // Allow package verifier to silently uninstall. 16398 if (mRequiredVerifierPackage != null && 16399 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 16400 return true; 16401 } 16402 16403 // Allow package uninstaller to silently uninstall. 16404 if (mRequiredUninstallerPackage != null && 16405 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 16406 return true; 16407 } 16408 16409 // Allow storage manager to silently uninstall. 16410 if (mStorageManagerPackage != null && 16411 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 16412 return true; 16413 } 16414 return false; 16415 } 16416 16417 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16418 int[] result = EMPTY_INT_ARRAY; 16419 for (int userId : userIds) { 16420 if (getBlockUninstallForUser(packageName, userId)) { 16421 result = ArrayUtils.appendInt(result, userId); 16422 } 16423 } 16424 return result; 16425 } 16426 16427 @Override 16428 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16429 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16430 } 16431 16432 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16433 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16434 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16435 try { 16436 if (dpm != null) { 16437 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16438 /* callingUserOnly =*/ false); 16439 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16440 : deviceOwnerComponentName.getPackageName(); 16441 // Does the package contains the device owner? 16442 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16443 // this check is probably not needed, since DO should be registered as a device 16444 // admin on some user too. (Original bug for this: b/17657954) 16445 if (packageName.equals(deviceOwnerPackageName)) { 16446 return true; 16447 } 16448 // Does it contain a device admin for any user? 16449 int[] users; 16450 if (userId == UserHandle.USER_ALL) { 16451 users = sUserManager.getUserIds(); 16452 } else { 16453 users = new int[]{userId}; 16454 } 16455 for (int i = 0; i < users.length; ++i) { 16456 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16457 return true; 16458 } 16459 } 16460 } 16461 } catch (RemoteException e) { 16462 } 16463 return false; 16464 } 16465 16466 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16467 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16468 } 16469 16470 /** 16471 * This method is an internal method that could be get invoked either 16472 * to delete an installed package or to clean up a failed installation. 16473 * After deleting an installed package, a broadcast is sent to notify any 16474 * listeners that the package has been removed. For cleaning up a failed 16475 * installation, the broadcast is not necessary since the package's 16476 * installation wouldn't have sent the initial broadcast either 16477 * The key steps in deleting a package are 16478 * deleting the package information in internal structures like mPackages, 16479 * deleting the packages base directories through installd 16480 * updating mSettings to reflect current status 16481 * persisting settings for later use 16482 * sending a broadcast if necessary 16483 */ 16484 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16485 final PackageRemovedInfo info = new PackageRemovedInfo(); 16486 final boolean res; 16487 16488 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16489 ? UserHandle.USER_ALL : userId; 16490 16491 if (isPackageDeviceAdmin(packageName, removeUser)) { 16492 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16493 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16494 } 16495 16496 PackageSetting uninstalledPs = null; 16497 16498 // for the uninstall-updates case and restricted profiles, remember the per- 16499 // user handle installed state 16500 int[] allUsers; 16501 synchronized (mPackages) { 16502 uninstalledPs = mSettings.mPackages.get(packageName); 16503 if (uninstalledPs == null) { 16504 Slog.w(TAG, "Not removing non-existent package " + packageName); 16505 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16506 } 16507 allUsers = sUserManager.getUserIds(); 16508 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16509 } 16510 16511 final int freezeUser; 16512 if (isUpdatedSystemApp(uninstalledPs) 16513 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16514 // We're downgrading a system app, which will apply to all users, so 16515 // freeze them all during the downgrade 16516 freezeUser = UserHandle.USER_ALL; 16517 } else { 16518 freezeUser = removeUser; 16519 } 16520 16521 synchronized (mInstallLock) { 16522 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16523 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16524 deleteFlags, "deletePackageX")) { 16525 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16526 deleteFlags | REMOVE_CHATTY, info, true, null); 16527 } 16528 synchronized (mPackages) { 16529 if (res) { 16530 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16531 } 16532 } 16533 } 16534 16535 if (res) { 16536 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16537 info.sendPackageRemovedBroadcasts(killApp); 16538 info.sendSystemPackageUpdatedBroadcasts(); 16539 info.sendSystemPackageAppearedBroadcasts(); 16540 } 16541 // Force a gc here. 16542 Runtime.getRuntime().gc(); 16543 // Delete the resources here after sending the broadcast to let 16544 // other processes clean up before deleting resources. 16545 if (info.args != null) { 16546 synchronized (mInstallLock) { 16547 info.args.doPostDeleteLI(true); 16548 } 16549 } 16550 16551 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16552 } 16553 16554 class PackageRemovedInfo { 16555 String removedPackage; 16556 int uid = -1; 16557 int removedAppId = -1; 16558 int[] origUsers; 16559 int[] removedUsers = null; 16560 SparseArray<Integer> installReasons; 16561 boolean isRemovedPackageSystemUpdate = false; 16562 boolean isUpdate; 16563 boolean dataRemoved; 16564 boolean removedForAllUsers; 16565 // Clean up resources deleted packages. 16566 InstallArgs args = null; 16567 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16568 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16569 16570 void sendPackageRemovedBroadcasts(boolean killApp) { 16571 sendPackageRemovedBroadcastInternal(killApp); 16572 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16573 for (int i = 0; i < childCount; i++) { 16574 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16575 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16576 } 16577 } 16578 16579 void sendSystemPackageUpdatedBroadcasts() { 16580 if (isRemovedPackageSystemUpdate) { 16581 sendSystemPackageUpdatedBroadcastsInternal(); 16582 final int childCount = (removedChildPackages != null) 16583 ? removedChildPackages.size() : 0; 16584 for (int i = 0; i < childCount; i++) { 16585 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16586 if (childInfo.isRemovedPackageSystemUpdate) { 16587 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16588 } 16589 } 16590 } 16591 } 16592 16593 void sendSystemPackageAppearedBroadcasts() { 16594 final int packageCount = (appearedChildPackages != null) 16595 ? appearedChildPackages.size() : 0; 16596 for (int i = 0; i < packageCount; i++) { 16597 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16598 sendPackageAddedForNewUsers(installedInfo.name, true, 16599 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16600 } 16601 } 16602 16603 private void sendSystemPackageUpdatedBroadcastsInternal() { 16604 Bundle extras = new Bundle(2); 16605 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16606 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16607 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16608 extras, 0, null, null, null); 16609 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16610 extras, 0, null, null, null); 16611 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16612 null, 0, removedPackage, null, null); 16613 } 16614 16615 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16616 Bundle extras = new Bundle(2); 16617 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16618 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16619 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16620 if (isUpdate || isRemovedPackageSystemUpdate) { 16621 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16622 } 16623 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16624 if (removedPackage != null) { 16625 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16626 extras, 0, null, null, removedUsers); 16627 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16628 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16629 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 16630 null, null, removedUsers); 16631 } 16632 } 16633 if (removedAppId >= 0) { 16634 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16635 removedUsers); 16636 } 16637 } 16638 } 16639 16640 /* 16641 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16642 * flag is not set, the data directory is removed as well. 16643 * make sure this flag is set for partially installed apps. If not its meaningless to 16644 * delete a partially installed application. 16645 */ 16646 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16647 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16648 String packageName = ps.name; 16649 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16650 // Retrieve object to delete permissions for shared user later on 16651 final PackageParser.Package deletedPkg; 16652 final PackageSetting deletedPs; 16653 // reader 16654 synchronized (mPackages) { 16655 deletedPkg = mPackages.get(packageName); 16656 deletedPs = mSettings.mPackages.get(packageName); 16657 if (outInfo != null) { 16658 outInfo.removedPackage = packageName; 16659 outInfo.removedUsers = deletedPs != null 16660 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16661 : null; 16662 } 16663 } 16664 16665 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16666 16667 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16668 final PackageParser.Package resolvedPkg; 16669 if (deletedPkg != null) { 16670 resolvedPkg = deletedPkg; 16671 } else { 16672 // We don't have a parsed package when it lives on an ejected 16673 // adopted storage device, so fake something together 16674 resolvedPkg = new PackageParser.Package(ps.name); 16675 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16676 } 16677 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16678 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16679 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16680 if (outInfo != null) { 16681 outInfo.dataRemoved = true; 16682 } 16683 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16684 } 16685 16686 // writer 16687 synchronized (mPackages) { 16688 if (deletedPs != null) { 16689 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16690 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16691 clearDefaultBrowserIfNeeded(packageName); 16692 if (outInfo != null) { 16693 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16694 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16695 } 16696 updatePermissionsLPw(deletedPs.name, null, 0); 16697 if (deletedPs.sharedUser != null) { 16698 // Remove permissions associated with package. Since runtime 16699 // permissions are per user we have to kill the removed package 16700 // or packages running under the shared user of the removed 16701 // package if revoking the permissions requested only by the removed 16702 // package is successful and this causes a change in gids. 16703 for (int userId : UserManagerService.getInstance().getUserIds()) { 16704 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16705 userId); 16706 if (userIdToKill == UserHandle.USER_ALL 16707 || userIdToKill >= UserHandle.USER_SYSTEM) { 16708 // If gids changed for this user, kill all affected packages. 16709 mHandler.post(new Runnable() { 16710 @Override 16711 public void run() { 16712 // This has to happen with no lock held. 16713 killApplication(deletedPs.name, deletedPs.appId, 16714 KILL_APP_REASON_GIDS_CHANGED); 16715 } 16716 }); 16717 break; 16718 } 16719 } 16720 } 16721 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16722 } 16723 // make sure to preserve per-user disabled state if this removal was just 16724 // a downgrade of a system app to the factory package 16725 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16726 if (DEBUG_REMOVE) { 16727 Slog.d(TAG, "Propagating install state across downgrade"); 16728 } 16729 for (int userId : allUserHandles) { 16730 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16731 if (DEBUG_REMOVE) { 16732 Slog.d(TAG, " user " + userId + " => " + installed); 16733 } 16734 ps.setInstalled(installed, userId); 16735 } 16736 } 16737 } 16738 // can downgrade to reader 16739 if (writeSettings) { 16740 // Save settings now 16741 mSettings.writeLPr(); 16742 } 16743 } 16744 if (outInfo != null) { 16745 // A user ID was deleted here. Go through all users and remove it 16746 // from KeyStore. 16747 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16748 } 16749 } 16750 16751 static boolean locationIsPrivileged(File path) { 16752 try { 16753 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16754 .getCanonicalPath(); 16755 return path.getCanonicalPath().startsWith(privilegedAppDir); 16756 } catch (IOException e) { 16757 Slog.e(TAG, "Unable to access code path " + path); 16758 } 16759 return false; 16760 } 16761 16762 /* 16763 * Tries to delete system package. 16764 */ 16765 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16766 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16767 boolean writeSettings) { 16768 if (deletedPs.parentPackageName != null) { 16769 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16770 return false; 16771 } 16772 16773 final boolean applyUserRestrictions 16774 = (allUserHandles != null) && (outInfo.origUsers != null); 16775 final PackageSetting disabledPs; 16776 // Confirm if the system package has been updated 16777 // An updated system app can be deleted. This will also have to restore 16778 // the system pkg from system partition 16779 // reader 16780 synchronized (mPackages) { 16781 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16782 } 16783 16784 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16785 + " disabledPs=" + disabledPs); 16786 16787 if (disabledPs == null) { 16788 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16789 return false; 16790 } else if (DEBUG_REMOVE) { 16791 Slog.d(TAG, "Deleting system pkg from data partition"); 16792 } 16793 16794 if (DEBUG_REMOVE) { 16795 if (applyUserRestrictions) { 16796 Slog.d(TAG, "Remembering install states:"); 16797 for (int userId : allUserHandles) { 16798 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16799 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16800 } 16801 } 16802 } 16803 16804 // Delete the updated package 16805 outInfo.isRemovedPackageSystemUpdate = true; 16806 if (outInfo.removedChildPackages != null) { 16807 final int childCount = (deletedPs.childPackageNames != null) 16808 ? deletedPs.childPackageNames.size() : 0; 16809 for (int i = 0; i < childCount; i++) { 16810 String childPackageName = deletedPs.childPackageNames.get(i); 16811 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16812 .contains(childPackageName)) { 16813 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16814 childPackageName); 16815 if (childInfo != null) { 16816 childInfo.isRemovedPackageSystemUpdate = true; 16817 } 16818 } 16819 } 16820 } 16821 16822 if (disabledPs.versionCode < deletedPs.versionCode) { 16823 // Delete data for downgrades 16824 flags &= ~PackageManager.DELETE_KEEP_DATA; 16825 } else { 16826 // Preserve data by setting flag 16827 flags |= PackageManager.DELETE_KEEP_DATA; 16828 } 16829 16830 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16831 outInfo, writeSettings, disabledPs.pkg); 16832 if (!ret) { 16833 return false; 16834 } 16835 16836 // writer 16837 synchronized (mPackages) { 16838 // Reinstate the old system package 16839 enableSystemPackageLPw(disabledPs.pkg); 16840 // Remove any native libraries from the upgraded package. 16841 removeNativeBinariesLI(deletedPs); 16842 } 16843 16844 // Install the system package 16845 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16846 int parseFlags = mDefParseFlags 16847 | PackageParser.PARSE_MUST_BE_APK 16848 | PackageParser.PARSE_IS_SYSTEM 16849 | PackageParser.PARSE_IS_SYSTEM_DIR; 16850 if (locationIsPrivileged(disabledPs.codePath)) { 16851 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16852 } 16853 16854 final PackageParser.Package newPkg; 16855 try { 16856 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16857 0 /* currentTime */, null); 16858 } catch (PackageManagerException e) { 16859 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16860 + e.getMessage()); 16861 return false; 16862 } 16863 try { 16864 // update shared libraries for the newly re-installed system package 16865 updateSharedLibrariesLPr(newPkg, null); 16866 } catch (PackageManagerException e) { 16867 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16868 } 16869 16870 prepareAppDataAfterInstallLIF(newPkg); 16871 16872 // writer 16873 synchronized (mPackages) { 16874 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16875 16876 // Propagate the permissions state as we do not want to drop on the floor 16877 // runtime permissions. The update permissions method below will take 16878 // care of removing obsolete permissions and grant install permissions. 16879 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16880 updatePermissionsLPw(newPkg.packageName, newPkg, 16881 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16882 16883 if (applyUserRestrictions) { 16884 if (DEBUG_REMOVE) { 16885 Slog.d(TAG, "Propagating install state across reinstall"); 16886 } 16887 for (int userId : allUserHandles) { 16888 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16889 if (DEBUG_REMOVE) { 16890 Slog.d(TAG, " user " + userId + " => " + installed); 16891 } 16892 ps.setInstalled(installed, userId); 16893 16894 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16895 } 16896 // Regardless of writeSettings we need to ensure that this restriction 16897 // state propagation is persisted 16898 mSettings.writeAllUsersPackageRestrictionsLPr(); 16899 } 16900 // can downgrade to reader here 16901 if (writeSettings) { 16902 mSettings.writeLPr(); 16903 } 16904 } 16905 return true; 16906 } 16907 16908 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16909 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16910 PackageRemovedInfo outInfo, boolean writeSettings, 16911 PackageParser.Package replacingPackage) { 16912 synchronized (mPackages) { 16913 if (outInfo != null) { 16914 outInfo.uid = ps.appId; 16915 } 16916 16917 if (outInfo != null && outInfo.removedChildPackages != null) { 16918 final int childCount = (ps.childPackageNames != null) 16919 ? ps.childPackageNames.size() : 0; 16920 for (int i = 0; i < childCount; i++) { 16921 String childPackageName = ps.childPackageNames.get(i); 16922 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16923 if (childPs == null) { 16924 return false; 16925 } 16926 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16927 childPackageName); 16928 if (childInfo != null) { 16929 childInfo.uid = childPs.appId; 16930 } 16931 } 16932 } 16933 } 16934 16935 // Delete package data from internal structures and also remove data if flag is set 16936 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16937 16938 // Delete the child packages data 16939 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16940 for (int i = 0; i < childCount; i++) { 16941 PackageSetting childPs; 16942 synchronized (mPackages) { 16943 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16944 } 16945 if (childPs != null) { 16946 PackageRemovedInfo childOutInfo = (outInfo != null 16947 && outInfo.removedChildPackages != null) 16948 ? outInfo.removedChildPackages.get(childPs.name) : null; 16949 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16950 && (replacingPackage != null 16951 && !replacingPackage.hasChildPackage(childPs.name)) 16952 ? flags & ~DELETE_KEEP_DATA : flags; 16953 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16954 deleteFlags, writeSettings); 16955 } 16956 } 16957 16958 // Delete application code and resources only for parent packages 16959 if (ps.parentPackageName == null) { 16960 if (deleteCodeAndResources && (outInfo != null)) { 16961 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16962 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16963 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16964 } 16965 } 16966 16967 return true; 16968 } 16969 16970 @Override 16971 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16972 int userId) { 16973 mContext.enforceCallingOrSelfPermission( 16974 android.Manifest.permission.DELETE_PACKAGES, null); 16975 synchronized (mPackages) { 16976 PackageSetting ps = mSettings.mPackages.get(packageName); 16977 if (ps == null) { 16978 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16979 return false; 16980 } 16981 if (!ps.getInstalled(userId)) { 16982 // Can't block uninstall for an app that is not installed or enabled. 16983 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16984 return false; 16985 } 16986 ps.setBlockUninstall(blockUninstall, userId); 16987 mSettings.writePackageRestrictionsLPr(userId); 16988 } 16989 return true; 16990 } 16991 16992 @Override 16993 public boolean getBlockUninstallForUser(String packageName, int userId) { 16994 synchronized (mPackages) { 16995 PackageSetting ps = mSettings.mPackages.get(packageName); 16996 if (ps == null) { 16997 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16998 return false; 16999 } 17000 return ps.getBlockUninstall(userId); 17001 } 17002 } 17003 17004 @Override 17005 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 17006 int callingUid = Binder.getCallingUid(); 17007 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 17008 throw new SecurityException( 17009 "setRequiredForSystemUser can only be run by the system or root"); 17010 } 17011 synchronized (mPackages) { 17012 PackageSetting ps = mSettings.mPackages.get(packageName); 17013 if (ps == null) { 17014 Log.w(TAG, "Package doesn't exist: " + packageName); 17015 return false; 17016 } 17017 if (systemUserApp) { 17018 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17019 } else { 17020 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 17021 } 17022 mSettings.writeLPr(); 17023 } 17024 return true; 17025 } 17026 17027 /* 17028 * This method handles package deletion in general 17029 */ 17030 private boolean deletePackageLIF(String packageName, UserHandle user, 17031 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 17032 PackageRemovedInfo outInfo, boolean writeSettings, 17033 PackageParser.Package replacingPackage) { 17034 if (packageName == null) { 17035 Slog.w(TAG, "Attempt to delete null packageName."); 17036 return false; 17037 } 17038 17039 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 17040 17041 PackageSetting ps; 17042 17043 synchronized (mPackages) { 17044 ps = mSettings.mPackages.get(packageName); 17045 if (ps == null) { 17046 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17047 return false; 17048 } 17049 17050 if (ps.parentPackageName != null && (!isSystemApp(ps) 17051 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 17052 if (DEBUG_REMOVE) { 17053 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 17054 + ((user == null) ? UserHandle.USER_ALL : user)); 17055 } 17056 final int removedUserId = (user != null) ? user.getIdentifier() 17057 : UserHandle.USER_ALL; 17058 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 17059 return false; 17060 } 17061 markPackageUninstalledForUserLPw(ps, user); 17062 scheduleWritePackageRestrictionsLocked(user); 17063 return true; 17064 } 17065 } 17066 17067 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 17068 && user.getIdentifier() != UserHandle.USER_ALL)) { 17069 // The caller is asking that the package only be deleted for a single 17070 // user. To do this, we just mark its uninstalled state and delete 17071 // its data. If this is a system app, we only allow this to happen if 17072 // they have set the special DELETE_SYSTEM_APP which requests different 17073 // semantics than normal for uninstalling system apps. 17074 markPackageUninstalledForUserLPw(ps, user); 17075 17076 if (!isSystemApp(ps)) { 17077 // Do not uninstall the APK if an app should be cached 17078 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 17079 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 17080 // Other user still have this package installed, so all 17081 // we need to do is clear this user's data and save that 17082 // it is uninstalled. 17083 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 17084 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17085 return false; 17086 } 17087 scheduleWritePackageRestrictionsLocked(user); 17088 return true; 17089 } else { 17090 // We need to set it back to 'installed' so the uninstall 17091 // broadcasts will be sent correctly. 17092 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 17093 ps.setInstalled(true, user.getIdentifier()); 17094 } 17095 } else { 17096 // This is a system app, so we assume that the 17097 // other users still have this package installed, so all 17098 // we need to do is clear this user's data and save that 17099 // it is uninstalled. 17100 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 17101 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 17102 return false; 17103 } 17104 scheduleWritePackageRestrictionsLocked(user); 17105 return true; 17106 } 17107 } 17108 17109 // If we are deleting a composite package for all users, keep track 17110 // of result for each child. 17111 if (ps.childPackageNames != null && outInfo != null) { 17112 synchronized (mPackages) { 17113 final int childCount = ps.childPackageNames.size(); 17114 outInfo.removedChildPackages = new ArrayMap<>(childCount); 17115 for (int i = 0; i < childCount; i++) { 17116 String childPackageName = ps.childPackageNames.get(i); 17117 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 17118 childInfo.removedPackage = childPackageName; 17119 outInfo.removedChildPackages.put(childPackageName, childInfo); 17120 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 17121 if (childPs != null) { 17122 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 17123 } 17124 } 17125 } 17126 } 17127 17128 boolean ret = false; 17129 if (isSystemApp(ps)) { 17130 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 17131 // When an updated system application is deleted we delete the existing resources 17132 // as well and fall back to existing code in system partition 17133 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 17134 } else { 17135 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 17136 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 17137 outInfo, writeSettings, replacingPackage); 17138 } 17139 17140 // Take a note whether we deleted the package for all users 17141 if (outInfo != null) { 17142 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17143 if (outInfo.removedChildPackages != null) { 17144 synchronized (mPackages) { 17145 final int childCount = outInfo.removedChildPackages.size(); 17146 for (int i = 0; i < childCount; i++) { 17147 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 17148 if (childInfo != null) { 17149 childInfo.removedForAllUsers = mPackages.get( 17150 childInfo.removedPackage) == null; 17151 } 17152 } 17153 } 17154 } 17155 // If we uninstalled an update to a system app there may be some 17156 // child packages that appeared as they are declared in the system 17157 // app but were not declared in the update. 17158 if (isSystemApp(ps)) { 17159 synchronized (mPackages) { 17160 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 17161 final int childCount = (updatedPs.childPackageNames != null) 17162 ? updatedPs.childPackageNames.size() : 0; 17163 for (int i = 0; i < childCount; i++) { 17164 String childPackageName = updatedPs.childPackageNames.get(i); 17165 if (outInfo.removedChildPackages == null 17166 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 17167 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 17168 if (childPs == null) { 17169 continue; 17170 } 17171 PackageInstalledInfo installRes = new PackageInstalledInfo(); 17172 installRes.name = childPackageName; 17173 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 17174 installRes.pkg = mPackages.get(childPackageName); 17175 installRes.uid = childPs.pkg.applicationInfo.uid; 17176 if (outInfo.appearedChildPackages == null) { 17177 outInfo.appearedChildPackages = new ArrayMap<>(); 17178 } 17179 outInfo.appearedChildPackages.put(childPackageName, installRes); 17180 } 17181 } 17182 } 17183 } 17184 } 17185 17186 return ret; 17187 } 17188 17189 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 17190 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 17191 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 17192 for (int nextUserId : userIds) { 17193 if (DEBUG_REMOVE) { 17194 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 17195 } 17196 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 17197 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 17198 false /*hidden*/, false /*suspended*/, null, null, null, 17199 false /*blockUninstall*/, 17200 ps.readUserState(nextUserId).domainVerificationStatus, 0, 17201 PackageManager.INSTALL_REASON_UNKNOWN); 17202 } 17203 } 17204 17205 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 17206 PackageRemovedInfo outInfo) { 17207 final PackageParser.Package pkg; 17208 synchronized (mPackages) { 17209 pkg = mPackages.get(ps.name); 17210 } 17211 17212 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 17213 : new int[] {userId}; 17214 for (int nextUserId : userIds) { 17215 if (DEBUG_REMOVE) { 17216 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 17217 + nextUserId); 17218 } 17219 17220 destroyAppDataLIF(pkg, userId, 17221 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17222 destroyAppProfilesLIF(pkg, userId); 17223 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 17224 schedulePackageCleaning(ps.name, nextUserId, false); 17225 synchronized (mPackages) { 17226 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 17227 scheduleWritePackageRestrictionsLocked(nextUserId); 17228 } 17229 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 17230 } 17231 } 17232 17233 if (outInfo != null) { 17234 outInfo.removedPackage = ps.name; 17235 outInfo.removedAppId = ps.appId; 17236 outInfo.removedUsers = userIds; 17237 } 17238 17239 return true; 17240 } 17241 17242 private final class ClearStorageConnection implements ServiceConnection { 17243 IMediaContainerService mContainerService; 17244 17245 @Override 17246 public void onServiceConnected(ComponentName name, IBinder service) { 17247 synchronized (this) { 17248 mContainerService = IMediaContainerService.Stub 17249 .asInterface(Binder.allowBlocking(service)); 17250 notifyAll(); 17251 } 17252 } 17253 17254 @Override 17255 public void onServiceDisconnected(ComponentName name) { 17256 } 17257 } 17258 17259 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 17260 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 17261 17262 final boolean mounted; 17263 if (Environment.isExternalStorageEmulated()) { 17264 mounted = true; 17265 } else { 17266 final String status = Environment.getExternalStorageState(); 17267 17268 mounted = status.equals(Environment.MEDIA_MOUNTED) 17269 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 17270 } 17271 17272 if (!mounted) { 17273 return; 17274 } 17275 17276 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 17277 int[] users; 17278 if (userId == UserHandle.USER_ALL) { 17279 users = sUserManager.getUserIds(); 17280 } else { 17281 users = new int[] { userId }; 17282 } 17283 final ClearStorageConnection conn = new ClearStorageConnection(); 17284 if (mContext.bindServiceAsUser( 17285 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 17286 try { 17287 for (int curUser : users) { 17288 long timeout = SystemClock.uptimeMillis() + 5000; 17289 synchronized (conn) { 17290 long now; 17291 while (conn.mContainerService == null && 17292 (now = SystemClock.uptimeMillis()) < timeout) { 17293 try { 17294 conn.wait(timeout - now); 17295 } catch (InterruptedException e) { 17296 } 17297 } 17298 } 17299 if (conn.mContainerService == null) { 17300 return; 17301 } 17302 17303 final UserEnvironment userEnv = new UserEnvironment(curUser); 17304 clearDirectory(conn.mContainerService, 17305 userEnv.buildExternalStorageAppCacheDirs(packageName)); 17306 if (allData) { 17307 clearDirectory(conn.mContainerService, 17308 userEnv.buildExternalStorageAppDataDirs(packageName)); 17309 clearDirectory(conn.mContainerService, 17310 userEnv.buildExternalStorageAppMediaDirs(packageName)); 17311 } 17312 } 17313 } finally { 17314 mContext.unbindService(conn); 17315 } 17316 } 17317 } 17318 17319 @Override 17320 public void clearApplicationProfileData(String packageName) { 17321 enforceSystemOrRoot("Only the system can clear all profile data"); 17322 17323 final PackageParser.Package pkg; 17324 synchronized (mPackages) { 17325 pkg = mPackages.get(packageName); 17326 } 17327 17328 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 17329 synchronized (mInstallLock) { 17330 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 17331 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 17332 true /* removeBaseMarker */); 17333 } 17334 } 17335 } 17336 17337 @Override 17338 public void clearApplicationUserData(final String packageName, 17339 final IPackageDataObserver observer, final int userId) { 17340 mContext.enforceCallingOrSelfPermission( 17341 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 17342 17343 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17344 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 17345 17346 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 17347 throw new SecurityException("Cannot clear data for a protected package: " 17348 + packageName); 17349 } 17350 // Queue up an async operation since the package deletion may take a little while. 17351 mHandler.post(new Runnable() { 17352 public void run() { 17353 mHandler.removeCallbacks(this); 17354 final boolean succeeded; 17355 try (PackageFreezer freezer = freezePackage(packageName, 17356 "clearApplicationUserData")) { 17357 synchronized (mInstallLock) { 17358 succeeded = clearApplicationUserDataLIF(packageName, userId); 17359 } 17360 clearExternalStorageDataSync(packageName, userId, true); 17361 } 17362 if (succeeded) { 17363 // invoke DeviceStorageMonitor's update method to clear any notifications 17364 DeviceStorageMonitorInternal dsm = LocalServices 17365 .getService(DeviceStorageMonitorInternal.class); 17366 if (dsm != null) { 17367 dsm.checkMemory(); 17368 } 17369 } 17370 if(observer != null) { 17371 try { 17372 observer.onRemoveCompleted(packageName, succeeded); 17373 } catch (RemoteException e) { 17374 Log.i(TAG, "Observer no longer exists."); 17375 } 17376 } //end if observer 17377 } //end run 17378 }); 17379 } 17380 17381 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 17382 if (packageName == null) { 17383 Slog.w(TAG, "Attempt to delete null packageName."); 17384 return false; 17385 } 17386 17387 // Try finding details about the requested package 17388 PackageParser.Package pkg; 17389 synchronized (mPackages) { 17390 pkg = mPackages.get(packageName); 17391 if (pkg == null) { 17392 final PackageSetting ps = mSettings.mPackages.get(packageName); 17393 if (ps != null) { 17394 pkg = ps.pkg; 17395 } 17396 } 17397 17398 if (pkg == null) { 17399 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17400 return false; 17401 } 17402 17403 PackageSetting ps = (PackageSetting) pkg.mExtras; 17404 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17405 } 17406 17407 clearAppDataLIF(pkg, userId, 17408 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17409 17410 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17411 removeKeystoreDataIfNeeded(userId, appId); 17412 17413 UserManagerInternal umInternal = getUserManagerInternal(); 17414 final int flags; 17415 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17416 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17417 } else if (umInternal.isUserRunning(userId)) { 17418 flags = StorageManager.FLAG_STORAGE_DE; 17419 } else { 17420 flags = 0; 17421 } 17422 prepareAppDataContentsLIF(pkg, userId, flags); 17423 17424 return true; 17425 } 17426 17427 /** 17428 * Reverts user permission state changes (permissions and flags) in 17429 * all packages for a given user. 17430 * 17431 * @param userId The device user for which to do a reset. 17432 */ 17433 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17434 final int packageCount = mPackages.size(); 17435 for (int i = 0; i < packageCount; i++) { 17436 PackageParser.Package pkg = mPackages.valueAt(i); 17437 PackageSetting ps = (PackageSetting) pkg.mExtras; 17438 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17439 } 17440 } 17441 17442 private void resetNetworkPolicies(int userId) { 17443 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17444 } 17445 17446 /** 17447 * Reverts user permission state changes (permissions and flags). 17448 * 17449 * @param ps The package for which to reset. 17450 * @param userId The device user for which to do a reset. 17451 */ 17452 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17453 final PackageSetting ps, final int userId) { 17454 if (ps.pkg == null) { 17455 return; 17456 } 17457 17458 // These are flags that can change base on user actions. 17459 final int userSettableMask = FLAG_PERMISSION_USER_SET 17460 | FLAG_PERMISSION_USER_FIXED 17461 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17462 | FLAG_PERMISSION_REVIEW_REQUIRED; 17463 17464 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17465 | FLAG_PERMISSION_POLICY_FIXED; 17466 17467 boolean writeInstallPermissions = false; 17468 boolean writeRuntimePermissions = false; 17469 17470 final int permissionCount = ps.pkg.requestedPermissions.size(); 17471 for (int i = 0; i < permissionCount; i++) { 17472 String permission = ps.pkg.requestedPermissions.get(i); 17473 17474 BasePermission bp = mSettings.mPermissions.get(permission); 17475 if (bp == null) { 17476 continue; 17477 } 17478 17479 // If shared user we just reset the state to which only this app contributed. 17480 if (ps.sharedUser != null) { 17481 boolean used = false; 17482 final int packageCount = ps.sharedUser.packages.size(); 17483 for (int j = 0; j < packageCount; j++) { 17484 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17485 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17486 && pkg.pkg.requestedPermissions.contains(permission)) { 17487 used = true; 17488 break; 17489 } 17490 } 17491 if (used) { 17492 continue; 17493 } 17494 } 17495 17496 PermissionsState permissionsState = ps.getPermissionsState(); 17497 17498 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17499 17500 // Always clear the user settable flags. 17501 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17502 bp.name) != null; 17503 // If permission review is enabled and this is a legacy app, mark the 17504 // permission as requiring a review as this is the initial state. 17505 int flags = 0; 17506 if (mPermissionReviewRequired 17507 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17508 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17509 } 17510 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17511 if (hasInstallState) { 17512 writeInstallPermissions = true; 17513 } else { 17514 writeRuntimePermissions = true; 17515 } 17516 } 17517 17518 // Below is only runtime permission handling. 17519 if (!bp.isRuntime()) { 17520 continue; 17521 } 17522 17523 // Never clobber system or policy. 17524 if ((oldFlags & policyOrSystemFlags) != 0) { 17525 continue; 17526 } 17527 17528 // If this permission was granted by default, make sure it is. 17529 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17530 if (permissionsState.grantRuntimePermission(bp, userId) 17531 != PERMISSION_OPERATION_FAILURE) { 17532 writeRuntimePermissions = true; 17533 } 17534 // If permission review is enabled the permissions for a legacy apps 17535 // are represented as constantly granted runtime ones, so don't revoke. 17536 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17537 // Otherwise, reset the permission. 17538 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17539 switch (revokeResult) { 17540 case PERMISSION_OPERATION_SUCCESS: 17541 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17542 writeRuntimePermissions = true; 17543 final int appId = ps.appId; 17544 mHandler.post(new Runnable() { 17545 @Override 17546 public void run() { 17547 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17548 } 17549 }); 17550 } break; 17551 } 17552 } 17553 } 17554 17555 // Synchronously write as we are taking permissions away. 17556 if (writeRuntimePermissions) { 17557 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17558 } 17559 17560 // Synchronously write as we are taking permissions away. 17561 if (writeInstallPermissions) { 17562 mSettings.writeLPr(); 17563 } 17564 } 17565 17566 /** 17567 * Remove entries from the keystore daemon. Will only remove it if the 17568 * {@code appId} is valid. 17569 */ 17570 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17571 if (appId < 0) { 17572 return; 17573 } 17574 17575 final KeyStore keyStore = KeyStore.getInstance(); 17576 if (keyStore != null) { 17577 if (userId == UserHandle.USER_ALL) { 17578 for (final int individual : sUserManager.getUserIds()) { 17579 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17580 } 17581 } else { 17582 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17583 } 17584 } else { 17585 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17586 } 17587 } 17588 17589 @Override 17590 public void deleteApplicationCacheFiles(final String packageName, 17591 final IPackageDataObserver observer) { 17592 final int userId = UserHandle.getCallingUserId(); 17593 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17594 } 17595 17596 @Override 17597 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17598 final IPackageDataObserver observer) { 17599 mContext.enforceCallingOrSelfPermission( 17600 android.Manifest.permission.DELETE_CACHE_FILES, null); 17601 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17602 /* requireFullPermission= */ true, /* checkShell= */ false, 17603 "delete application cache files"); 17604 17605 final PackageParser.Package pkg; 17606 synchronized (mPackages) { 17607 pkg = mPackages.get(packageName); 17608 } 17609 17610 // Queue up an async operation since the package deletion may take a little while. 17611 mHandler.post(new Runnable() { 17612 public void run() { 17613 synchronized (mInstallLock) { 17614 final int flags = StorageManager.FLAG_STORAGE_DE 17615 | StorageManager.FLAG_STORAGE_CE; 17616 // We're only clearing cache files, so we don't care if the 17617 // app is unfrozen and still able to run 17618 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17619 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17620 } 17621 clearExternalStorageDataSync(packageName, userId, false); 17622 if (observer != null) { 17623 try { 17624 observer.onRemoveCompleted(packageName, true); 17625 } catch (RemoteException e) { 17626 Log.i(TAG, "Observer no longer exists."); 17627 } 17628 } 17629 } 17630 }); 17631 } 17632 17633 @Override 17634 public void getPackageSizeInfo(final String packageName, int userHandle, 17635 final IPackageStatsObserver observer) { 17636 mContext.enforceCallingOrSelfPermission( 17637 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17638 if (packageName == null) { 17639 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17640 } 17641 17642 PackageStats stats = new PackageStats(packageName, userHandle); 17643 17644 /* 17645 * Queue up an async operation since the package measurement may take a 17646 * little while. 17647 */ 17648 Message msg = mHandler.obtainMessage(INIT_COPY); 17649 msg.obj = new MeasureParams(stats, observer); 17650 mHandler.sendMessage(msg); 17651 } 17652 17653 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17654 final PackageSetting ps; 17655 synchronized (mPackages) { 17656 ps = mSettings.mPackages.get(packageName); 17657 if (ps == null) { 17658 Slog.w(TAG, "Failed to find settings for " + packageName); 17659 return false; 17660 } 17661 } 17662 17663 final String[] packageNames = { packageName }; 17664 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 17665 final String[] codePaths = { ps.codePathString }; 17666 17667 try { 17668 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 17669 ps.appId, ceDataInodes, codePaths, stats); 17670 17671 // For now, ignore code size of packages on system partition 17672 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17673 stats.codeSize = 0; 17674 } 17675 17676 // External clients expect these to be tracked separately 17677 stats.dataSize -= stats.cacheSize; 17678 17679 } catch (InstallerException e) { 17680 Slog.w(TAG, String.valueOf(e)); 17681 return false; 17682 } 17683 17684 return true; 17685 } 17686 17687 private int getUidTargetSdkVersionLockedLPr(int uid) { 17688 Object obj = mSettings.getUserIdLPr(uid); 17689 if (obj instanceof SharedUserSetting) { 17690 final SharedUserSetting sus = (SharedUserSetting) obj; 17691 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17692 final Iterator<PackageSetting> it = sus.packages.iterator(); 17693 while (it.hasNext()) { 17694 final PackageSetting ps = it.next(); 17695 if (ps.pkg != null) { 17696 int v = ps.pkg.applicationInfo.targetSdkVersion; 17697 if (v < vers) vers = v; 17698 } 17699 } 17700 return vers; 17701 } else if (obj instanceof PackageSetting) { 17702 final PackageSetting ps = (PackageSetting) obj; 17703 if (ps.pkg != null) { 17704 return ps.pkg.applicationInfo.targetSdkVersion; 17705 } 17706 } 17707 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17708 } 17709 17710 @Override 17711 public void addPreferredActivity(IntentFilter filter, int match, 17712 ComponentName[] set, ComponentName activity, int userId) { 17713 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17714 "Adding preferred"); 17715 } 17716 17717 private void addPreferredActivityInternal(IntentFilter filter, int match, 17718 ComponentName[] set, ComponentName activity, boolean always, int userId, 17719 String opname) { 17720 // writer 17721 int callingUid = Binder.getCallingUid(); 17722 enforceCrossUserPermission(callingUid, userId, 17723 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17724 if (filter.countActions() == 0) { 17725 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17726 return; 17727 } 17728 synchronized (mPackages) { 17729 if (mContext.checkCallingOrSelfPermission( 17730 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17731 != PackageManager.PERMISSION_GRANTED) { 17732 if (getUidTargetSdkVersionLockedLPr(callingUid) 17733 < Build.VERSION_CODES.FROYO) { 17734 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17735 + callingUid); 17736 return; 17737 } 17738 mContext.enforceCallingOrSelfPermission( 17739 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17740 } 17741 17742 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17743 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17744 + userId + ":"); 17745 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17746 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17747 scheduleWritePackageRestrictionsLocked(userId); 17748 postPreferredActivityChangedBroadcast(userId); 17749 } 17750 } 17751 17752 private void postPreferredActivityChangedBroadcast(int userId) { 17753 mHandler.post(() -> { 17754 final IActivityManager am = ActivityManager.getService(); 17755 if (am == null) { 17756 return; 17757 } 17758 17759 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17760 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17761 try { 17762 am.broadcastIntent(null, intent, null, null, 17763 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17764 null, false, false, userId); 17765 } catch (RemoteException e) { 17766 } 17767 }); 17768 } 17769 17770 @Override 17771 public void replacePreferredActivity(IntentFilter filter, int match, 17772 ComponentName[] set, ComponentName activity, int userId) { 17773 if (filter.countActions() != 1) { 17774 throw new IllegalArgumentException( 17775 "replacePreferredActivity expects filter to have only 1 action."); 17776 } 17777 if (filter.countDataAuthorities() != 0 17778 || filter.countDataPaths() != 0 17779 || filter.countDataSchemes() > 1 17780 || filter.countDataTypes() != 0) { 17781 throw new IllegalArgumentException( 17782 "replacePreferredActivity expects filter to have no data authorities, " + 17783 "paths, or types; and at most one scheme."); 17784 } 17785 17786 final int callingUid = Binder.getCallingUid(); 17787 enforceCrossUserPermission(callingUid, userId, 17788 true /* requireFullPermission */, false /* checkShell */, 17789 "replace preferred activity"); 17790 synchronized (mPackages) { 17791 if (mContext.checkCallingOrSelfPermission( 17792 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17793 != PackageManager.PERMISSION_GRANTED) { 17794 if (getUidTargetSdkVersionLockedLPr(callingUid) 17795 < Build.VERSION_CODES.FROYO) { 17796 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17797 + Binder.getCallingUid()); 17798 return; 17799 } 17800 mContext.enforceCallingOrSelfPermission( 17801 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17802 } 17803 17804 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17805 if (pir != null) { 17806 // Get all of the existing entries that exactly match this filter. 17807 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17808 if (existing != null && existing.size() == 1) { 17809 PreferredActivity cur = existing.get(0); 17810 if (DEBUG_PREFERRED) { 17811 Slog.i(TAG, "Checking replace of preferred:"); 17812 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17813 if (!cur.mPref.mAlways) { 17814 Slog.i(TAG, " -- CUR; not mAlways!"); 17815 } else { 17816 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17817 Slog.i(TAG, " -- CUR: mSet=" 17818 + Arrays.toString(cur.mPref.mSetComponents)); 17819 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17820 Slog.i(TAG, " -- NEW: mMatch=" 17821 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17822 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17823 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17824 } 17825 } 17826 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17827 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17828 && cur.mPref.sameSet(set)) { 17829 // Setting the preferred activity to what it happens to be already 17830 if (DEBUG_PREFERRED) { 17831 Slog.i(TAG, "Replacing with same preferred activity " 17832 + cur.mPref.mShortComponent + " for user " 17833 + userId + ":"); 17834 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17835 } 17836 return; 17837 } 17838 } 17839 17840 if (existing != null) { 17841 if (DEBUG_PREFERRED) { 17842 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17843 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17844 } 17845 for (int i = 0; i < existing.size(); i++) { 17846 PreferredActivity pa = existing.get(i); 17847 if (DEBUG_PREFERRED) { 17848 Slog.i(TAG, "Removing existing preferred activity " 17849 + pa.mPref.mComponent + ":"); 17850 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17851 } 17852 pir.removeFilter(pa); 17853 } 17854 } 17855 } 17856 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17857 "Replacing preferred"); 17858 } 17859 } 17860 17861 @Override 17862 public void clearPackagePreferredActivities(String packageName) { 17863 final int uid = Binder.getCallingUid(); 17864 // writer 17865 synchronized (mPackages) { 17866 PackageParser.Package pkg = mPackages.get(packageName); 17867 if (pkg == null || pkg.applicationInfo.uid != uid) { 17868 if (mContext.checkCallingOrSelfPermission( 17869 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17870 != PackageManager.PERMISSION_GRANTED) { 17871 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17872 < Build.VERSION_CODES.FROYO) { 17873 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17874 + Binder.getCallingUid()); 17875 return; 17876 } 17877 mContext.enforceCallingOrSelfPermission( 17878 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17879 } 17880 } 17881 17882 int user = UserHandle.getCallingUserId(); 17883 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17884 scheduleWritePackageRestrictionsLocked(user); 17885 } 17886 } 17887 } 17888 17889 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17890 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17891 ArrayList<PreferredActivity> removed = null; 17892 boolean changed = false; 17893 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17894 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17895 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17896 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17897 continue; 17898 } 17899 Iterator<PreferredActivity> it = pir.filterIterator(); 17900 while (it.hasNext()) { 17901 PreferredActivity pa = it.next(); 17902 // Mark entry for removal only if it matches the package name 17903 // and the entry is of type "always". 17904 if (packageName == null || 17905 (pa.mPref.mComponent.getPackageName().equals(packageName) 17906 && pa.mPref.mAlways)) { 17907 if (removed == null) { 17908 removed = new ArrayList<PreferredActivity>(); 17909 } 17910 removed.add(pa); 17911 } 17912 } 17913 if (removed != null) { 17914 for (int j=0; j<removed.size(); j++) { 17915 PreferredActivity pa = removed.get(j); 17916 pir.removeFilter(pa); 17917 } 17918 changed = true; 17919 } 17920 } 17921 if (changed) { 17922 postPreferredActivityChangedBroadcast(userId); 17923 } 17924 return changed; 17925 } 17926 17927 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17928 private void clearIntentFilterVerificationsLPw(int userId) { 17929 final int packageCount = mPackages.size(); 17930 for (int i = 0; i < packageCount; i++) { 17931 PackageParser.Package pkg = mPackages.valueAt(i); 17932 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17933 } 17934 } 17935 17936 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17937 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17938 if (userId == UserHandle.USER_ALL) { 17939 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17940 sUserManager.getUserIds())) { 17941 for (int oneUserId : sUserManager.getUserIds()) { 17942 scheduleWritePackageRestrictionsLocked(oneUserId); 17943 } 17944 } 17945 } else { 17946 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17947 scheduleWritePackageRestrictionsLocked(userId); 17948 } 17949 } 17950 } 17951 17952 void clearDefaultBrowserIfNeeded(String packageName) { 17953 for (int oneUserId : sUserManager.getUserIds()) { 17954 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17955 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17956 if (packageName.equals(defaultBrowserPackageName)) { 17957 setDefaultBrowserPackageName(null, oneUserId); 17958 } 17959 } 17960 } 17961 17962 @Override 17963 public void resetApplicationPreferences(int userId) { 17964 mContext.enforceCallingOrSelfPermission( 17965 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17966 final long identity = Binder.clearCallingIdentity(); 17967 // writer 17968 try { 17969 synchronized (mPackages) { 17970 clearPackagePreferredActivitiesLPw(null, userId); 17971 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17972 // TODO: We have to reset the default SMS and Phone. This requires 17973 // significant refactoring to keep all default apps in the package 17974 // manager (cleaner but more work) or have the services provide 17975 // callbacks to the package manager to request a default app reset. 17976 applyFactoryDefaultBrowserLPw(userId); 17977 clearIntentFilterVerificationsLPw(userId); 17978 primeDomainVerificationsLPw(userId); 17979 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17980 scheduleWritePackageRestrictionsLocked(userId); 17981 } 17982 resetNetworkPolicies(userId); 17983 } finally { 17984 Binder.restoreCallingIdentity(identity); 17985 } 17986 } 17987 17988 @Override 17989 public int getPreferredActivities(List<IntentFilter> outFilters, 17990 List<ComponentName> outActivities, String packageName) { 17991 17992 int num = 0; 17993 final int userId = UserHandle.getCallingUserId(); 17994 // reader 17995 synchronized (mPackages) { 17996 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17997 if (pir != null) { 17998 final Iterator<PreferredActivity> it = pir.filterIterator(); 17999 while (it.hasNext()) { 18000 final PreferredActivity pa = it.next(); 18001 if (packageName == null 18002 || (pa.mPref.mComponent.getPackageName().equals(packageName) 18003 && pa.mPref.mAlways)) { 18004 if (outFilters != null) { 18005 outFilters.add(new IntentFilter(pa)); 18006 } 18007 if (outActivities != null) { 18008 outActivities.add(pa.mPref.mComponent); 18009 } 18010 } 18011 } 18012 } 18013 } 18014 18015 return num; 18016 } 18017 18018 @Override 18019 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 18020 int userId) { 18021 int callingUid = Binder.getCallingUid(); 18022 if (callingUid != Process.SYSTEM_UID) { 18023 throw new SecurityException( 18024 "addPersistentPreferredActivity can only be run by the system"); 18025 } 18026 if (filter.countActions() == 0) { 18027 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18028 return; 18029 } 18030 synchronized (mPackages) { 18031 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 18032 ":"); 18033 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18034 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 18035 new PersistentPreferredActivity(filter, activity)); 18036 scheduleWritePackageRestrictionsLocked(userId); 18037 postPreferredActivityChangedBroadcast(userId); 18038 } 18039 } 18040 18041 @Override 18042 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 18043 int callingUid = Binder.getCallingUid(); 18044 if (callingUid != Process.SYSTEM_UID) { 18045 throw new SecurityException( 18046 "clearPackagePersistentPreferredActivities can only be run by the system"); 18047 } 18048 ArrayList<PersistentPreferredActivity> removed = null; 18049 boolean changed = false; 18050 synchronized (mPackages) { 18051 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 18052 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 18053 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 18054 .valueAt(i); 18055 if (userId != thisUserId) { 18056 continue; 18057 } 18058 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 18059 while (it.hasNext()) { 18060 PersistentPreferredActivity ppa = it.next(); 18061 // Mark entry for removal only if it matches the package name. 18062 if (ppa.mComponent.getPackageName().equals(packageName)) { 18063 if (removed == null) { 18064 removed = new ArrayList<PersistentPreferredActivity>(); 18065 } 18066 removed.add(ppa); 18067 } 18068 } 18069 if (removed != null) { 18070 for (int j=0; j<removed.size(); j++) { 18071 PersistentPreferredActivity ppa = removed.get(j); 18072 ppir.removeFilter(ppa); 18073 } 18074 changed = true; 18075 } 18076 } 18077 18078 if (changed) { 18079 scheduleWritePackageRestrictionsLocked(userId); 18080 postPreferredActivityChangedBroadcast(userId); 18081 } 18082 } 18083 } 18084 18085 /** 18086 * Common machinery for picking apart a restored XML blob and passing 18087 * it to a caller-supplied functor to be applied to the running system. 18088 */ 18089 private void restoreFromXml(XmlPullParser parser, int userId, 18090 String expectedStartTag, BlobXmlRestorer functor) 18091 throws IOException, XmlPullParserException { 18092 int type; 18093 while ((type = parser.next()) != XmlPullParser.START_TAG 18094 && type != XmlPullParser.END_DOCUMENT) { 18095 } 18096 if (type != XmlPullParser.START_TAG) { 18097 // oops didn't find a start tag?! 18098 if (DEBUG_BACKUP) { 18099 Slog.e(TAG, "Didn't find start tag during restore"); 18100 } 18101 return; 18102 } 18103Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 18104 // this is supposed to be TAG_PREFERRED_BACKUP 18105 if (!expectedStartTag.equals(parser.getName())) { 18106 if (DEBUG_BACKUP) { 18107 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 18108 } 18109 return; 18110 } 18111 18112 // skip interfering stuff, then we're aligned with the backing implementation 18113 while ((type = parser.next()) == XmlPullParser.TEXT) { } 18114Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 18115 functor.apply(parser, userId); 18116 } 18117 18118 private interface BlobXmlRestorer { 18119 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 18120 } 18121 18122 /** 18123 * Non-Binder method, support for the backup/restore mechanism: write the 18124 * full set of preferred activities in its canonical XML format. Returns the 18125 * XML output as a byte array, or null if there is none. 18126 */ 18127 @Override 18128 public byte[] getPreferredActivityBackup(int userId) { 18129 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18130 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 18131 } 18132 18133 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18134 try { 18135 final XmlSerializer serializer = new FastXmlSerializer(); 18136 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18137 serializer.startDocument(null, true); 18138 serializer.startTag(null, TAG_PREFERRED_BACKUP); 18139 18140 synchronized (mPackages) { 18141 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 18142 } 18143 18144 serializer.endTag(null, TAG_PREFERRED_BACKUP); 18145 serializer.endDocument(); 18146 serializer.flush(); 18147 } catch (Exception e) { 18148 if (DEBUG_BACKUP) { 18149 Slog.e(TAG, "Unable to write preferred activities for backup", e); 18150 } 18151 return null; 18152 } 18153 18154 return dataStream.toByteArray(); 18155 } 18156 18157 @Override 18158 public void restorePreferredActivities(byte[] backup, int userId) { 18159 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18160 throw new SecurityException("Only the system may call restorePreferredActivities()"); 18161 } 18162 18163 try { 18164 final XmlPullParser parser = Xml.newPullParser(); 18165 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18166 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 18167 new BlobXmlRestorer() { 18168 @Override 18169 public void apply(XmlPullParser parser, int userId) 18170 throws XmlPullParserException, IOException { 18171 synchronized (mPackages) { 18172 mSettings.readPreferredActivitiesLPw(parser, userId); 18173 } 18174 } 18175 } ); 18176 } catch (Exception e) { 18177 if (DEBUG_BACKUP) { 18178 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18179 } 18180 } 18181 } 18182 18183 /** 18184 * Non-Binder method, support for the backup/restore mechanism: write the 18185 * default browser (etc) settings in its canonical XML format. Returns the default 18186 * browser XML representation as a byte array, or null if there is none. 18187 */ 18188 @Override 18189 public byte[] getDefaultAppsBackup(int userId) { 18190 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18191 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 18192 } 18193 18194 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18195 try { 18196 final XmlSerializer serializer = new FastXmlSerializer(); 18197 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18198 serializer.startDocument(null, true); 18199 serializer.startTag(null, TAG_DEFAULT_APPS); 18200 18201 synchronized (mPackages) { 18202 mSettings.writeDefaultAppsLPr(serializer, userId); 18203 } 18204 18205 serializer.endTag(null, TAG_DEFAULT_APPS); 18206 serializer.endDocument(); 18207 serializer.flush(); 18208 } catch (Exception e) { 18209 if (DEBUG_BACKUP) { 18210 Slog.e(TAG, "Unable to write default apps for backup", e); 18211 } 18212 return null; 18213 } 18214 18215 return dataStream.toByteArray(); 18216 } 18217 18218 @Override 18219 public void restoreDefaultApps(byte[] backup, int userId) { 18220 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18221 throw new SecurityException("Only the system may call restoreDefaultApps()"); 18222 } 18223 18224 try { 18225 final XmlPullParser parser = Xml.newPullParser(); 18226 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18227 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 18228 new BlobXmlRestorer() { 18229 @Override 18230 public void apply(XmlPullParser parser, int userId) 18231 throws XmlPullParserException, IOException { 18232 synchronized (mPackages) { 18233 mSettings.readDefaultAppsLPw(parser, userId); 18234 } 18235 } 18236 } ); 18237 } catch (Exception e) { 18238 if (DEBUG_BACKUP) { 18239 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 18240 } 18241 } 18242 } 18243 18244 @Override 18245 public byte[] getIntentFilterVerificationBackup(int userId) { 18246 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18247 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 18248 } 18249 18250 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18251 try { 18252 final XmlSerializer serializer = new FastXmlSerializer(); 18253 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18254 serializer.startDocument(null, true); 18255 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 18256 18257 synchronized (mPackages) { 18258 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 18259 } 18260 18261 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 18262 serializer.endDocument(); 18263 serializer.flush(); 18264 } catch (Exception e) { 18265 if (DEBUG_BACKUP) { 18266 Slog.e(TAG, "Unable to write default apps for backup", e); 18267 } 18268 return null; 18269 } 18270 18271 return dataStream.toByteArray(); 18272 } 18273 18274 @Override 18275 public void restoreIntentFilterVerification(byte[] backup, int userId) { 18276 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18277 throw new SecurityException("Only the system may call restorePreferredActivities()"); 18278 } 18279 18280 try { 18281 final XmlPullParser parser = Xml.newPullParser(); 18282 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18283 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 18284 new BlobXmlRestorer() { 18285 @Override 18286 public void apply(XmlPullParser parser, int userId) 18287 throws XmlPullParserException, IOException { 18288 synchronized (mPackages) { 18289 mSettings.readAllDomainVerificationsLPr(parser, userId); 18290 mSettings.writeLPr(); 18291 } 18292 } 18293 } ); 18294 } catch (Exception e) { 18295 if (DEBUG_BACKUP) { 18296 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18297 } 18298 } 18299 } 18300 18301 @Override 18302 public byte[] getPermissionGrantBackup(int userId) { 18303 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18304 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 18305 } 18306 18307 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18308 try { 18309 final XmlSerializer serializer = new FastXmlSerializer(); 18310 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18311 serializer.startDocument(null, true); 18312 serializer.startTag(null, TAG_PERMISSION_BACKUP); 18313 18314 synchronized (mPackages) { 18315 serializeRuntimePermissionGrantsLPr(serializer, userId); 18316 } 18317 18318 serializer.endTag(null, TAG_PERMISSION_BACKUP); 18319 serializer.endDocument(); 18320 serializer.flush(); 18321 } catch (Exception e) { 18322 if (DEBUG_BACKUP) { 18323 Slog.e(TAG, "Unable to write default apps for backup", e); 18324 } 18325 return null; 18326 } 18327 18328 return dataStream.toByteArray(); 18329 } 18330 18331 @Override 18332 public void restorePermissionGrants(byte[] backup, int userId) { 18333 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18334 throw new SecurityException("Only the system may call restorePermissionGrants()"); 18335 } 18336 18337 try { 18338 final XmlPullParser parser = Xml.newPullParser(); 18339 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18340 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 18341 new BlobXmlRestorer() { 18342 @Override 18343 public void apply(XmlPullParser parser, int userId) 18344 throws XmlPullParserException, IOException { 18345 synchronized (mPackages) { 18346 processRestoredPermissionGrantsLPr(parser, userId); 18347 } 18348 } 18349 } ); 18350 } catch (Exception e) { 18351 if (DEBUG_BACKUP) { 18352 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18353 } 18354 } 18355 } 18356 18357 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 18358 throws IOException { 18359 serializer.startTag(null, TAG_ALL_GRANTS); 18360 18361 final int N = mSettings.mPackages.size(); 18362 for (int i = 0; i < N; i++) { 18363 final PackageSetting ps = mSettings.mPackages.valueAt(i); 18364 boolean pkgGrantsKnown = false; 18365 18366 PermissionsState packagePerms = ps.getPermissionsState(); 18367 18368 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 18369 final int grantFlags = state.getFlags(); 18370 // only look at grants that are not system/policy fixed 18371 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 18372 final boolean isGranted = state.isGranted(); 18373 // And only back up the user-twiddled state bits 18374 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 18375 final String packageName = mSettings.mPackages.keyAt(i); 18376 if (!pkgGrantsKnown) { 18377 serializer.startTag(null, TAG_GRANT); 18378 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 18379 pkgGrantsKnown = true; 18380 } 18381 18382 final boolean userSet = 18383 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 18384 final boolean userFixed = 18385 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 18386 final boolean revoke = 18387 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 18388 18389 serializer.startTag(null, TAG_PERMISSION); 18390 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 18391 if (isGranted) { 18392 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 18393 } 18394 if (userSet) { 18395 serializer.attribute(null, ATTR_USER_SET, "true"); 18396 } 18397 if (userFixed) { 18398 serializer.attribute(null, ATTR_USER_FIXED, "true"); 18399 } 18400 if (revoke) { 18401 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 18402 } 18403 serializer.endTag(null, TAG_PERMISSION); 18404 } 18405 } 18406 } 18407 18408 if (pkgGrantsKnown) { 18409 serializer.endTag(null, TAG_GRANT); 18410 } 18411 } 18412 18413 serializer.endTag(null, TAG_ALL_GRANTS); 18414 } 18415 18416 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 18417 throws XmlPullParserException, IOException { 18418 String pkgName = null; 18419 int outerDepth = parser.getDepth(); 18420 int type; 18421 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 18422 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 18423 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18424 continue; 18425 } 18426 18427 final String tagName = parser.getName(); 18428 if (tagName.equals(TAG_GRANT)) { 18429 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18430 if (DEBUG_BACKUP) { 18431 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18432 } 18433 } else if (tagName.equals(TAG_PERMISSION)) { 18434 18435 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18436 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18437 18438 int newFlagSet = 0; 18439 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18440 newFlagSet |= FLAG_PERMISSION_USER_SET; 18441 } 18442 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18443 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18444 } 18445 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18446 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18447 } 18448 if (DEBUG_BACKUP) { 18449 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18450 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18451 } 18452 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18453 if (ps != null) { 18454 // Already installed so we apply the grant immediately 18455 if (DEBUG_BACKUP) { 18456 Slog.v(TAG, " + already installed; applying"); 18457 } 18458 PermissionsState perms = ps.getPermissionsState(); 18459 BasePermission bp = mSettings.mPermissions.get(permName); 18460 if (bp != null) { 18461 if (isGranted) { 18462 perms.grantRuntimePermission(bp, userId); 18463 } 18464 if (newFlagSet != 0) { 18465 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18466 } 18467 } 18468 } else { 18469 // Need to wait for post-restore install to apply the grant 18470 if (DEBUG_BACKUP) { 18471 Slog.v(TAG, " - not yet installed; saving for later"); 18472 } 18473 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18474 isGranted, newFlagSet, userId); 18475 } 18476 } else { 18477 PackageManagerService.reportSettingsProblem(Log.WARN, 18478 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18479 XmlUtils.skipCurrentTag(parser); 18480 } 18481 } 18482 18483 scheduleWriteSettingsLocked(); 18484 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18485 } 18486 18487 @Override 18488 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18489 int sourceUserId, int targetUserId, int flags) { 18490 mContext.enforceCallingOrSelfPermission( 18491 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18492 int callingUid = Binder.getCallingUid(); 18493 enforceOwnerRights(ownerPackage, callingUid); 18494 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18495 if (intentFilter.countActions() == 0) { 18496 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18497 return; 18498 } 18499 synchronized (mPackages) { 18500 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18501 ownerPackage, targetUserId, flags); 18502 CrossProfileIntentResolver resolver = 18503 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18504 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18505 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18506 if (existing != null) { 18507 int size = existing.size(); 18508 for (int i = 0; i < size; i++) { 18509 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18510 return; 18511 } 18512 } 18513 } 18514 resolver.addFilter(newFilter); 18515 scheduleWritePackageRestrictionsLocked(sourceUserId); 18516 } 18517 } 18518 18519 @Override 18520 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18521 mContext.enforceCallingOrSelfPermission( 18522 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18523 int callingUid = Binder.getCallingUid(); 18524 enforceOwnerRights(ownerPackage, callingUid); 18525 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18526 synchronized (mPackages) { 18527 CrossProfileIntentResolver resolver = 18528 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18529 ArraySet<CrossProfileIntentFilter> set = 18530 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18531 for (CrossProfileIntentFilter filter : set) { 18532 if (filter.getOwnerPackage().equals(ownerPackage)) { 18533 resolver.removeFilter(filter); 18534 } 18535 } 18536 scheduleWritePackageRestrictionsLocked(sourceUserId); 18537 } 18538 } 18539 18540 // Enforcing that callingUid is owning pkg on userId 18541 private void enforceOwnerRights(String pkg, int callingUid) { 18542 // The system owns everything. 18543 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18544 return; 18545 } 18546 int callingUserId = UserHandle.getUserId(callingUid); 18547 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18548 if (pi == null) { 18549 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18550 + callingUserId); 18551 } 18552 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18553 throw new SecurityException("Calling uid " + callingUid 18554 + " does not own package " + pkg); 18555 } 18556 } 18557 18558 @Override 18559 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18560 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18561 } 18562 18563 private Intent getHomeIntent() { 18564 Intent intent = new Intent(Intent.ACTION_MAIN); 18565 intent.addCategory(Intent.CATEGORY_HOME); 18566 intent.addCategory(Intent.CATEGORY_DEFAULT); 18567 return intent; 18568 } 18569 18570 private IntentFilter getHomeFilter() { 18571 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18572 filter.addCategory(Intent.CATEGORY_HOME); 18573 filter.addCategory(Intent.CATEGORY_DEFAULT); 18574 return filter; 18575 } 18576 18577 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18578 int userId) { 18579 Intent intent = getHomeIntent(); 18580 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18581 PackageManager.GET_META_DATA, userId); 18582 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18583 true, false, false, userId); 18584 18585 allHomeCandidates.clear(); 18586 if (list != null) { 18587 for (ResolveInfo ri : list) { 18588 allHomeCandidates.add(ri); 18589 } 18590 } 18591 return (preferred == null || preferred.activityInfo == null) 18592 ? null 18593 : new ComponentName(preferred.activityInfo.packageName, 18594 preferred.activityInfo.name); 18595 } 18596 18597 @Override 18598 public void setHomeActivity(ComponentName comp, int userId) { 18599 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18600 getHomeActivitiesAsUser(homeActivities, userId); 18601 18602 boolean found = false; 18603 18604 final int size = homeActivities.size(); 18605 final ComponentName[] set = new ComponentName[size]; 18606 for (int i = 0; i < size; i++) { 18607 final ResolveInfo candidate = homeActivities.get(i); 18608 final ActivityInfo info = candidate.activityInfo; 18609 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18610 set[i] = activityName; 18611 if (!found && activityName.equals(comp)) { 18612 found = true; 18613 } 18614 } 18615 if (!found) { 18616 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18617 + userId); 18618 } 18619 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18620 set, comp, userId); 18621 } 18622 18623 private @Nullable String getSetupWizardPackageName() { 18624 final Intent intent = new Intent(Intent.ACTION_MAIN); 18625 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18626 18627 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18628 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18629 | MATCH_DISABLED_COMPONENTS, 18630 UserHandle.myUserId()); 18631 if (matches.size() == 1) { 18632 return matches.get(0).getComponentInfo().packageName; 18633 } else { 18634 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18635 + ": matches=" + matches); 18636 return null; 18637 } 18638 } 18639 18640 private @Nullable String getStorageManagerPackageName() { 18641 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18642 18643 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18644 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18645 | MATCH_DISABLED_COMPONENTS, 18646 UserHandle.myUserId()); 18647 if (matches.size() == 1) { 18648 return matches.get(0).getComponentInfo().packageName; 18649 } else { 18650 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18651 + matches.size() + ": matches=" + matches); 18652 return null; 18653 } 18654 } 18655 18656 @Override 18657 public void setApplicationEnabledSetting(String appPackageName, 18658 int newState, int flags, int userId, String callingPackage) { 18659 if (!sUserManager.exists(userId)) return; 18660 if (callingPackage == null) { 18661 callingPackage = Integer.toString(Binder.getCallingUid()); 18662 } 18663 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18664 } 18665 18666 @Override 18667 public void setComponentEnabledSetting(ComponentName componentName, 18668 int newState, int flags, int userId) { 18669 if (!sUserManager.exists(userId)) return; 18670 setEnabledSetting(componentName.getPackageName(), 18671 componentName.getClassName(), newState, flags, userId, null); 18672 } 18673 18674 private void setEnabledSetting(final String packageName, String className, int newState, 18675 final int flags, int userId, String callingPackage) { 18676 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18677 || newState == COMPONENT_ENABLED_STATE_ENABLED 18678 || newState == COMPONENT_ENABLED_STATE_DISABLED 18679 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18680 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18681 throw new IllegalArgumentException("Invalid new component state: " 18682 + newState); 18683 } 18684 PackageSetting pkgSetting; 18685 final int uid = Binder.getCallingUid(); 18686 final int permission; 18687 if (uid == Process.SYSTEM_UID) { 18688 permission = PackageManager.PERMISSION_GRANTED; 18689 } else { 18690 permission = mContext.checkCallingOrSelfPermission( 18691 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18692 } 18693 enforceCrossUserPermission(uid, userId, 18694 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18695 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18696 boolean sendNow = false; 18697 boolean isApp = (className == null); 18698 String componentName = isApp ? packageName : className; 18699 int packageUid = -1; 18700 ArrayList<String> components; 18701 18702 // writer 18703 synchronized (mPackages) { 18704 pkgSetting = mSettings.mPackages.get(packageName); 18705 if (pkgSetting == null) { 18706 if (className == null) { 18707 throw new IllegalArgumentException("Unknown package: " + packageName); 18708 } 18709 throw new IllegalArgumentException( 18710 "Unknown component: " + packageName + "/" + className); 18711 } 18712 } 18713 18714 // Limit who can change which apps 18715 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18716 // Don't allow apps that don't have permission to modify other apps 18717 if (!allowedByPermission) { 18718 throw new SecurityException( 18719 "Permission Denial: attempt to change component state from pid=" 18720 + Binder.getCallingPid() 18721 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18722 } 18723 // Don't allow changing protected packages. 18724 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18725 throw new SecurityException("Cannot disable a protected package: " + packageName); 18726 } 18727 } 18728 18729 synchronized (mPackages) { 18730 if (uid == Process.SHELL_UID 18731 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18732 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18733 // unless it is a test package. 18734 int oldState = pkgSetting.getEnabled(userId); 18735 if (className == null 18736 && 18737 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18738 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18739 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18740 && 18741 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18742 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18743 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18744 // ok 18745 } else { 18746 throw new SecurityException( 18747 "Shell cannot change component state for " + packageName + "/" 18748 + className + " to " + newState); 18749 } 18750 } 18751 if (className == null) { 18752 // We're dealing with an application/package level state change 18753 if (pkgSetting.getEnabled(userId) == newState) { 18754 // Nothing to do 18755 return; 18756 } 18757 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18758 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18759 // Don't care about who enables an app. 18760 callingPackage = null; 18761 } 18762 pkgSetting.setEnabled(newState, userId, callingPackage); 18763 // pkgSetting.pkg.mSetEnabled = newState; 18764 } else { 18765 // We're dealing with a component level state change 18766 // First, verify that this is a valid class name. 18767 PackageParser.Package pkg = pkgSetting.pkg; 18768 if (pkg == null || !pkg.hasComponentClassName(className)) { 18769 if (pkg != null && 18770 pkg.applicationInfo.targetSdkVersion >= 18771 Build.VERSION_CODES.JELLY_BEAN) { 18772 throw new IllegalArgumentException("Component class " + className 18773 + " does not exist in " + packageName); 18774 } else { 18775 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18776 + className + " does not exist in " + packageName); 18777 } 18778 } 18779 switch (newState) { 18780 case COMPONENT_ENABLED_STATE_ENABLED: 18781 if (!pkgSetting.enableComponentLPw(className, userId)) { 18782 return; 18783 } 18784 break; 18785 case COMPONENT_ENABLED_STATE_DISABLED: 18786 if (!pkgSetting.disableComponentLPw(className, userId)) { 18787 return; 18788 } 18789 break; 18790 case COMPONENT_ENABLED_STATE_DEFAULT: 18791 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18792 return; 18793 } 18794 break; 18795 default: 18796 Slog.e(TAG, "Invalid new component state: " + newState); 18797 return; 18798 } 18799 } 18800 scheduleWritePackageRestrictionsLocked(userId); 18801 components = mPendingBroadcasts.get(userId, packageName); 18802 final boolean newPackage = components == null; 18803 if (newPackage) { 18804 components = new ArrayList<String>(); 18805 } 18806 if (!components.contains(componentName)) { 18807 components.add(componentName); 18808 } 18809 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18810 sendNow = true; 18811 // Purge entry from pending broadcast list if another one exists already 18812 // since we are sending one right away. 18813 mPendingBroadcasts.remove(userId, packageName); 18814 } else { 18815 if (newPackage) { 18816 mPendingBroadcasts.put(userId, packageName, components); 18817 } 18818 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18819 // Schedule a message 18820 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18821 } 18822 } 18823 } 18824 18825 long callingId = Binder.clearCallingIdentity(); 18826 try { 18827 if (sendNow) { 18828 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18829 sendPackageChangedBroadcast(packageName, 18830 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18831 } 18832 } finally { 18833 Binder.restoreCallingIdentity(callingId); 18834 } 18835 } 18836 18837 @Override 18838 public void flushPackageRestrictionsAsUser(int userId) { 18839 if (!sUserManager.exists(userId)) { 18840 return; 18841 } 18842 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18843 false /* checkShell */, "flushPackageRestrictions"); 18844 synchronized (mPackages) { 18845 mSettings.writePackageRestrictionsLPr(userId); 18846 mDirtyUsers.remove(userId); 18847 if (mDirtyUsers.isEmpty()) { 18848 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18849 } 18850 } 18851 } 18852 18853 private void sendPackageChangedBroadcast(String packageName, 18854 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18855 if (DEBUG_INSTALL) 18856 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18857 + componentNames); 18858 Bundle extras = new Bundle(4); 18859 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18860 String nameList[] = new String[componentNames.size()]; 18861 componentNames.toArray(nameList); 18862 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18863 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18864 extras.putInt(Intent.EXTRA_UID, packageUid); 18865 // If this is not reporting a change of the overall package, then only send it 18866 // to registered receivers. We don't want to launch a swath of apps for every 18867 // little component state change. 18868 final int flags = !componentNames.contains(packageName) 18869 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18870 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18871 new int[] {UserHandle.getUserId(packageUid)}); 18872 } 18873 18874 @Override 18875 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18876 if (!sUserManager.exists(userId)) return; 18877 final int uid = Binder.getCallingUid(); 18878 final int permission = mContext.checkCallingOrSelfPermission( 18879 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18880 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18881 enforceCrossUserPermission(uid, userId, 18882 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18883 // writer 18884 synchronized (mPackages) { 18885 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18886 allowedByPermission, uid, userId)) { 18887 scheduleWritePackageRestrictionsLocked(userId); 18888 } 18889 } 18890 } 18891 18892 @Override 18893 public String getInstallerPackageName(String packageName) { 18894 // reader 18895 synchronized (mPackages) { 18896 return mSettings.getInstallerPackageNameLPr(packageName); 18897 } 18898 } 18899 18900 public boolean isOrphaned(String packageName) { 18901 // reader 18902 synchronized (mPackages) { 18903 return mSettings.isOrphaned(packageName); 18904 } 18905 } 18906 18907 @Override 18908 public int getApplicationEnabledSetting(String packageName, int userId) { 18909 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18910 int uid = Binder.getCallingUid(); 18911 enforceCrossUserPermission(uid, userId, 18912 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18913 // reader 18914 synchronized (mPackages) { 18915 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18916 } 18917 } 18918 18919 @Override 18920 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18921 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18922 int uid = Binder.getCallingUid(); 18923 enforceCrossUserPermission(uid, userId, 18924 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18925 // reader 18926 synchronized (mPackages) { 18927 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18928 } 18929 } 18930 18931 @Override 18932 public void enterSafeMode() { 18933 enforceSystemOrRoot("Only the system can request entering safe mode"); 18934 18935 if (!mSystemReady) { 18936 mSafeMode = true; 18937 } 18938 } 18939 18940 @Override 18941 public void systemReady() { 18942 mSystemReady = true; 18943 18944 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18945 // disabled after already being started. 18946 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18947 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18948 18949 // Read the compatibilty setting when the system is ready. 18950 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18951 mContext.getContentResolver(), 18952 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18953 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18954 if (DEBUG_SETTINGS) { 18955 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18956 } 18957 18958 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18959 18960 synchronized (mPackages) { 18961 // Verify that all of the preferred activity components actually 18962 // exist. It is possible for applications to be updated and at 18963 // that point remove a previously declared activity component that 18964 // had been set as a preferred activity. We try to clean this up 18965 // the next time we encounter that preferred activity, but it is 18966 // possible for the user flow to never be able to return to that 18967 // situation so here we do a sanity check to make sure we haven't 18968 // left any junk around. 18969 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18970 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18971 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18972 removed.clear(); 18973 for (PreferredActivity pa : pir.filterSet()) { 18974 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18975 removed.add(pa); 18976 } 18977 } 18978 if (removed.size() > 0) { 18979 for (int r=0; r<removed.size(); r++) { 18980 PreferredActivity pa = removed.get(r); 18981 Slog.w(TAG, "Removing dangling preferred activity: " 18982 + pa.mPref.mComponent); 18983 pir.removeFilter(pa); 18984 } 18985 mSettings.writePackageRestrictionsLPr( 18986 mSettings.mPreferredActivities.keyAt(i)); 18987 } 18988 } 18989 18990 for (int userId : UserManagerService.getInstance().getUserIds()) { 18991 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18992 grantPermissionsUserIds = ArrayUtils.appendInt( 18993 grantPermissionsUserIds, userId); 18994 } 18995 } 18996 } 18997 sUserManager.systemReady(); 18998 18999 // If we upgraded grant all default permissions before kicking off. 19000 for (int userId : grantPermissionsUserIds) { 19001 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 19002 } 19003 19004 // If we did not grant default permissions, we preload from this the 19005 // default permission exceptions lazily to ensure we don't hit the 19006 // disk on a new user creation. 19007 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 19008 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 19009 } 19010 19011 // Kick off any messages waiting for system ready 19012 if (mPostSystemReadyMessages != null) { 19013 for (Message msg : mPostSystemReadyMessages) { 19014 msg.sendToTarget(); 19015 } 19016 mPostSystemReadyMessages = null; 19017 } 19018 19019 // Watch for external volumes that come and go over time 19020 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19021 storage.registerListener(mStorageListener); 19022 19023 mInstallerService.systemReady(); 19024 mPackageDexOptimizer.systemReady(); 19025 19026 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 19027 StorageManagerInternal.class); 19028 StorageManagerInternal.addExternalStoragePolicy( 19029 new StorageManagerInternal.ExternalStorageMountPolicy() { 19030 @Override 19031 public int getMountMode(int uid, String packageName) { 19032 if (Process.isIsolated(uid)) { 19033 return Zygote.MOUNT_EXTERNAL_NONE; 19034 } 19035 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 19036 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19037 } 19038 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 19039 return Zygote.MOUNT_EXTERNAL_DEFAULT; 19040 } 19041 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 19042 return Zygote.MOUNT_EXTERNAL_READ; 19043 } 19044 return Zygote.MOUNT_EXTERNAL_WRITE; 19045 } 19046 19047 @Override 19048 public boolean hasExternalStorage(int uid, String packageName) { 19049 return true; 19050 } 19051 }); 19052 19053 // Now that we're mostly running, clean up stale users and apps 19054 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 19055 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 19056 } 19057 19058 @Override 19059 public boolean isSafeMode() { 19060 return mSafeMode; 19061 } 19062 19063 @Override 19064 public boolean hasSystemUidErrors() { 19065 return mHasSystemUidErrors; 19066 } 19067 19068 static String arrayToString(int[] array) { 19069 StringBuffer buf = new StringBuffer(128); 19070 buf.append('['); 19071 if (array != null) { 19072 for (int i=0; i<array.length; i++) { 19073 if (i > 0) buf.append(", "); 19074 buf.append(array[i]); 19075 } 19076 } 19077 buf.append(']'); 19078 return buf.toString(); 19079 } 19080 19081 static class DumpState { 19082 public static final int DUMP_LIBS = 1 << 0; 19083 public static final int DUMP_FEATURES = 1 << 1; 19084 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 19085 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 19086 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 19087 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 19088 public static final int DUMP_PERMISSIONS = 1 << 6; 19089 public static final int DUMP_PACKAGES = 1 << 7; 19090 public static final int DUMP_SHARED_USERS = 1 << 8; 19091 public static final int DUMP_MESSAGES = 1 << 9; 19092 public static final int DUMP_PROVIDERS = 1 << 10; 19093 public static final int DUMP_VERIFIERS = 1 << 11; 19094 public static final int DUMP_PREFERRED = 1 << 12; 19095 public static final int DUMP_PREFERRED_XML = 1 << 13; 19096 public static final int DUMP_KEYSETS = 1 << 14; 19097 public static final int DUMP_VERSION = 1 << 15; 19098 public static final int DUMP_INSTALLS = 1 << 16; 19099 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 19100 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 19101 public static final int DUMP_FROZEN = 1 << 19; 19102 public static final int DUMP_DEXOPT = 1 << 20; 19103 public static final int DUMP_COMPILER_STATS = 1 << 21; 19104 19105 public static final int OPTION_SHOW_FILTERS = 1 << 0; 19106 19107 private int mTypes; 19108 19109 private int mOptions; 19110 19111 private boolean mTitlePrinted; 19112 19113 private SharedUserSetting mSharedUser; 19114 19115 public boolean isDumping(int type) { 19116 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 19117 return true; 19118 } 19119 19120 return (mTypes & type) != 0; 19121 } 19122 19123 public void setDump(int type) { 19124 mTypes |= type; 19125 } 19126 19127 public boolean isOptionEnabled(int option) { 19128 return (mOptions & option) != 0; 19129 } 19130 19131 public void setOptionEnabled(int option) { 19132 mOptions |= option; 19133 } 19134 19135 public boolean onTitlePrinted() { 19136 final boolean printed = mTitlePrinted; 19137 mTitlePrinted = true; 19138 return printed; 19139 } 19140 19141 public boolean getTitlePrinted() { 19142 return mTitlePrinted; 19143 } 19144 19145 public void setTitlePrinted(boolean enabled) { 19146 mTitlePrinted = enabled; 19147 } 19148 19149 public SharedUserSetting getSharedUser() { 19150 return mSharedUser; 19151 } 19152 19153 public void setSharedUser(SharedUserSetting user) { 19154 mSharedUser = user; 19155 } 19156 } 19157 19158 @Override 19159 public void onShellCommand(FileDescriptor in, FileDescriptor out, 19160 FileDescriptor err, String[] args, ShellCallback callback, 19161 ResultReceiver resultReceiver) { 19162 (new PackageManagerShellCommand(this)).exec( 19163 this, in, out, err, args, callback, resultReceiver); 19164 } 19165 19166 @Override 19167 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 19168 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 19169 != PackageManager.PERMISSION_GRANTED) { 19170 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 19171 + Binder.getCallingPid() 19172 + ", uid=" + Binder.getCallingUid() 19173 + " without permission " 19174 + android.Manifest.permission.DUMP); 19175 return; 19176 } 19177 19178 DumpState dumpState = new DumpState(); 19179 boolean fullPreferred = false; 19180 boolean checkin = false; 19181 19182 String packageName = null; 19183 ArraySet<String> permissionNames = null; 19184 19185 int opti = 0; 19186 while (opti < args.length) { 19187 String opt = args[opti]; 19188 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 19189 break; 19190 } 19191 opti++; 19192 19193 if ("-a".equals(opt)) { 19194 // Right now we only know how to print all. 19195 } else if ("-h".equals(opt)) { 19196 pw.println("Package manager dump options:"); 19197 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 19198 pw.println(" --checkin: dump for a checkin"); 19199 pw.println(" -f: print details of intent filters"); 19200 pw.println(" -h: print this help"); 19201 pw.println(" cmd may be one of:"); 19202 pw.println(" l[ibraries]: list known shared libraries"); 19203 pw.println(" f[eatures]: list device features"); 19204 pw.println(" k[eysets]: print known keysets"); 19205 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 19206 pw.println(" perm[issions]: dump permissions"); 19207 pw.println(" permission [name ...]: dump declaration and use of given permission"); 19208 pw.println(" pref[erred]: print preferred package settings"); 19209 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 19210 pw.println(" prov[iders]: dump content providers"); 19211 pw.println(" p[ackages]: dump installed packages"); 19212 pw.println(" s[hared-users]: dump shared user IDs"); 19213 pw.println(" m[essages]: print collected runtime messages"); 19214 pw.println(" v[erifiers]: print package verifier info"); 19215 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 19216 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 19217 pw.println(" version: print database version info"); 19218 pw.println(" write: write current settings now"); 19219 pw.println(" installs: details about install sessions"); 19220 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 19221 pw.println(" dexopt: dump dexopt state"); 19222 pw.println(" compiler-stats: dump compiler statistics"); 19223 pw.println(" <package.name>: info about given package"); 19224 return; 19225 } else if ("--checkin".equals(opt)) { 19226 checkin = true; 19227 } else if ("-f".equals(opt)) { 19228 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19229 } else { 19230 pw.println("Unknown argument: " + opt + "; use -h for help"); 19231 } 19232 } 19233 19234 // Is the caller requesting to dump a particular piece of data? 19235 if (opti < args.length) { 19236 String cmd = args[opti]; 19237 opti++; 19238 // Is this a package name? 19239 if ("android".equals(cmd) || cmd.contains(".")) { 19240 packageName = cmd; 19241 // When dumping a single package, we always dump all of its 19242 // filter information since the amount of data will be reasonable. 19243 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19244 } else if ("check-permission".equals(cmd)) { 19245 if (opti >= args.length) { 19246 pw.println("Error: check-permission missing permission argument"); 19247 return; 19248 } 19249 String perm = args[opti]; 19250 opti++; 19251 if (opti >= args.length) { 19252 pw.println("Error: check-permission missing package argument"); 19253 return; 19254 } 19255 String pkg = args[opti]; 19256 opti++; 19257 int user = UserHandle.getUserId(Binder.getCallingUid()); 19258 if (opti < args.length) { 19259 try { 19260 user = Integer.parseInt(args[opti]); 19261 } catch (NumberFormatException e) { 19262 pw.println("Error: check-permission user argument is not a number: " 19263 + args[opti]); 19264 return; 19265 } 19266 } 19267 pw.println(checkPermission(perm, pkg, user)); 19268 return; 19269 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 19270 dumpState.setDump(DumpState.DUMP_LIBS); 19271 } else if ("f".equals(cmd) || "features".equals(cmd)) { 19272 dumpState.setDump(DumpState.DUMP_FEATURES); 19273 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 19274 if (opti >= args.length) { 19275 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 19276 | DumpState.DUMP_SERVICE_RESOLVERS 19277 | DumpState.DUMP_RECEIVER_RESOLVERS 19278 | DumpState.DUMP_CONTENT_RESOLVERS); 19279 } else { 19280 while (opti < args.length) { 19281 String name = args[opti]; 19282 if ("a".equals(name) || "activity".equals(name)) { 19283 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 19284 } else if ("s".equals(name) || "service".equals(name)) { 19285 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 19286 } else if ("r".equals(name) || "receiver".equals(name)) { 19287 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 19288 } else if ("c".equals(name) || "content".equals(name)) { 19289 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 19290 } else { 19291 pw.println("Error: unknown resolver table type: " + name); 19292 return; 19293 } 19294 opti++; 19295 } 19296 } 19297 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 19298 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 19299 } else if ("permission".equals(cmd)) { 19300 if (opti >= args.length) { 19301 pw.println("Error: permission requires permission name"); 19302 return; 19303 } 19304 permissionNames = new ArraySet<>(); 19305 while (opti < args.length) { 19306 permissionNames.add(args[opti]); 19307 opti++; 19308 } 19309 dumpState.setDump(DumpState.DUMP_PERMISSIONS 19310 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 19311 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 19312 dumpState.setDump(DumpState.DUMP_PREFERRED); 19313 } else if ("preferred-xml".equals(cmd)) { 19314 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 19315 if (opti < args.length && "--full".equals(args[opti])) { 19316 fullPreferred = true; 19317 opti++; 19318 } 19319 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 19320 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 19321 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 19322 dumpState.setDump(DumpState.DUMP_PACKAGES); 19323 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 19324 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 19325 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 19326 dumpState.setDump(DumpState.DUMP_PROVIDERS); 19327 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 19328 dumpState.setDump(DumpState.DUMP_MESSAGES); 19329 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 19330 dumpState.setDump(DumpState.DUMP_VERIFIERS); 19331 } else if ("i".equals(cmd) || "ifv".equals(cmd) 19332 || "intent-filter-verifiers".equals(cmd)) { 19333 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 19334 } else if ("version".equals(cmd)) { 19335 dumpState.setDump(DumpState.DUMP_VERSION); 19336 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 19337 dumpState.setDump(DumpState.DUMP_KEYSETS); 19338 } else if ("installs".equals(cmd)) { 19339 dumpState.setDump(DumpState.DUMP_INSTALLS); 19340 } else if ("frozen".equals(cmd)) { 19341 dumpState.setDump(DumpState.DUMP_FROZEN); 19342 } else if ("dexopt".equals(cmd)) { 19343 dumpState.setDump(DumpState.DUMP_DEXOPT); 19344 } else if ("compiler-stats".equals(cmd)) { 19345 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 19346 } else if ("write".equals(cmd)) { 19347 synchronized (mPackages) { 19348 mSettings.writeLPr(); 19349 pw.println("Settings written."); 19350 return; 19351 } 19352 } 19353 } 19354 19355 if (checkin) { 19356 pw.println("vers,1"); 19357 } 19358 19359 // reader 19360 synchronized (mPackages) { 19361 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 19362 if (!checkin) { 19363 if (dumpState.onTitlePrinted()) 19364 pw.println(); 19365 pw.println("Database versions:"); 19366 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 19367 } 19368 } 19369 19370 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 19371 if (!checkin) { 19372 if (dumpState.onTitlePrinted()) 19373 pw.println(); 19374 pw.println("Verifiers:"); 19375 pw.print(" Required: "); 19376 pw.print(mRequiredVerifierPackage); 19377 pw.print(" (uid="); 19378 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19379 UserHandle.USER_SYSTEM)); 19380 pw.println(")"); 19381 } else if (mRequiredVerifierPackage != null) { 19382 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 19383 pw.print(","); 19384 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19385 UserHandle.USER_SYSTEM)); 19386 } 19387 } 19388 19389 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 19390 packageName == null) { 19391 if (mIntentFilterVerifierComponent != null) { 19392 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 19393 if (!checkin) { 19394 if (dumpState.onTitlePrinted()) 19395 pw.println(); 19396 pw.println("Intent Filter Verifier:"); 19397 pw.print(" Using: "); 19398 pw.print(verifierPackageName); 19399 pw.print(" (uid="); 19400 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19401 UserHandle.USER_SYSTEM)); 19402 pw.println(")"); 19403 } else if (verifierPackageName != null) { 19404 pw.print("ifv,"); pw.print(verifierPackageName); 19405 pw.print(","); 19406 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19407 UserHandle.USER_SYSTEM)); 19408 } 19409 } else { 19410 pw.println(); 19411 pw.println("No Intent Filter Verifier available!"); 19412 } 19413 } 19414 19415 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 19416 boolean printedHeader = false; 19417 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 19418 while (it.hasNext()) { 19419 String name = it.next(); 19420 SharedLibraryEntry ent = mSharedLibraries.get(name); 19421 if (!checkin) { 19422 if (!printedHeader) { 19423 if (dumpState.onTitlePrinted()) 19424 pw.println(); 19425 pw.println("Libraries:"); 19426 printedHeader = true; 19427 } 19428 pw.print(" "); 19429 } else { 19430 pw.print("lib,"); 19431 } 19432 pw.print(name); 19433 if (!checkin) { 19434 pw.print(" -> "); 19435 } 19436 if (ent.path != null) { 19437 if (!checkin) { 19438 pw.print("(jar) "); 19439 pw.print(ent.path); 19440 } else { 19441 pw.print(",jar,"); 19442 pw.print(ent.path); 19443 } 19444 } else { 19445 if (!checkin) { 19446 pw.print("(apk) "); 19447 pw.print(ent.apk); 19448 } else { 19449 pw.print(",apk,"); 19450 pw.print(ent.apk); 19451 } 19452 } 19453 pw.println(); 19454 } 19455 } 19456 19457 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19458 if (dumpState.onTitlePrinted()) 19459 pw.println(); 19460 if (!checkin) { 19461 pw.println("Features:"); 19462 } 19463 19464 for (FeatureInfo feat : mAvailableFeatures.values()) { 19465 if (checkin) { 19466 pw.print("feat,"); 19467 pw.print(feat.name); 19468 pw.print(","); 19469 pw.println(feat.version); 19470 } else { 19471 pw.print(" "); 19472 pw.print(feat.name); 19473 if (feat.version > 0) { 19474 pw.print(" version="); 19475 pw.print(feat.version); 19476 } 19477 pw.println(); 19478 } 19479 } 19480 } 19481 19482 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19483 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19484 : "Activity Resolver Table:", " ", packageName, 19485 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19486 dumpState.setTitlePrinted(true); 19487 } 19488 } 19489 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19490 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19491 : "Receiver Resolver Table:", " ", packageName, 19492 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19493 dumpState.setTitlePrinted(true); 19494 } 19495 } 19496 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19497 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19498 : "Service Resolver Table:", " ", packageName, 19499 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19500 dumpState.setTitlePrinted(true); 19501 } 19502 } 19503 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19504 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19505 : "Provider Resolver Table:", " ", packageName, 19506 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19507 dumpState.setTitlePrinted(true); 19508 } 19509 } 19510 19511 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19512 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19513 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19514 int user = mSettings.mPreferredActivities.keyAt(i); 19515 if (pir.dump(pw, 19516 dumpState.getTitlePrinted() 19517 ? "\nPreferred Activities User " + user + ":" 19518 : "Preferred Activities User " + user + ":", " ", 19519 packageName, true, false)) { 19520 dumpState.setTitlePrinted(true); 19521 } 19522 } 19523 } 19524 19525 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19526 pw.flush(); 19527 FileOutputStream fout = new FileOutputStream(fd); 19528 BufferedOutputStream str = new BufferedOutputStream(fout); 19529 XmlSerializer serializer = new FastXmlSerializer(); 19530 try { 19531 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19532 serializer.startDocument(null, true); 19533 serializer.setFeature( 19534 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19535 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19536 serializer.endDocument(); 19537 serializer.flush(); 19538 } catch (IllegalArgumentException e) { 19539 pw.println("Failed writing: " + e); 19540 } catch (IllegalStateException e) { 19541 pw.println("Failed writing: " + e); 19542 } catch (IOException e) { 19543 pw.println("Failed writing: " + e); 19544 } 19545 } 19546 19547 if (!checkin 19548 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19549 && packageName == null) { 19550 pw.println(); 19551 int count = mSettings.mPackages.size(); 19552 if (count == 0) { 19553 pw.println("No applications!"); 19554 pw.println(); 19555 } else { 19556 final String prefix = " "; 19557 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19558 if (allPackageSettings.size() == 0) { 19559 pw.println("No domain preferred apps!"); 19560 pw.println(); 19561 } else { 19562 pw.println("App verification status:"); 19563 pw.println(); 19564 count = 0; 19565 for (PackageSetting ps : allPackageSettings) { 19566 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19567 if (ivi == null || ivi.getPackageName() == null) continue; 19568 pw.println(prefix + "Package: " + ivi.getPackageName()); 19569 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19570 pw.println(prefix + "Status: " + ivi.getStatusString()); 19571 pw.println(); 19572 count++; 19573 } 19574 if (count == 0) { 19575 pw.println(prefix + "No app verification established."); 19576 pw.println(); 19577 } 19578 for (int userId : sUserManager.getUserIds()) { 19579 pw.println("App linkages for user " + userId + ":"); 19580 pw.println(); 19581 count = 0; 19582 for (PackageSetting ps : allPackageSettings) { 19583 final long status = ps.getDomainVerificationStatusForUser(userId); 19584 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 19585 && !DEBUG_DOMAIN_VERIFICATION) { 19586 continue; 19587 } 19588 pw.println(prefix + "Package: " + ps.name); 19589 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19590 String statusStr = IntentFilterVerificationInfo. 19591 getStatusStringFromValue(status); 19592 pw.println(prefix + "Status: " + statusStr); 19593 pw.println(); 19594 count++; 19595 } 19596 if (count == 0) { 19597 pw.println(prefix + "No configured app linkages."); 19598 pw.println(); 19599 } 19600 } 19601 } 19602 } 19603 } 19604 19605 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19606 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19607 if (packageName == null && permissionNames == null) { 19608 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19609 if (iperm == 0) { 19610 if (dumpState.onTitlePrinted()) 19611 pw.println(); 19612 pw.println("AppOp Permissions:"); 19613 } 19614 pw.print(" AppOp Permission "); 19615 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19616 pw.println(":"); 19617 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19618 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19619 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19620 } 19621 } 19622 } 19623 } 19624 19625 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19626 boolean printedSomething = false; 19627 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19628 if (packageName != null && !packageName.equals(p.info.packageName)) { 19629 continue; 19630 } 19631 if (!printedSomething) { 19632 if (dumpState.onTitlePrinted()) 19633 pw.println(); 19634 pw.println("Registered ContentProviders:"); 19635 printedSomething = true; 19636 } 19637 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19638 pw.print(" "); pw.println(p.toString()); 19639 } 19640 printedSomething = false; 19641 for (Map.Entry<String, PackageParser.Provider> entry : 19642 mProvidersByAuthority.entrySet()) { 19643 PackageParser.Provider p = entry.getValue(); 19644 if (packageName != null && !packageName.equals(p.info.packageName)) { 19645 continue; 19646 } 19647 if (!printedSomething) { 19648 if (dumpState.onTitlePrinted()) 19649 pw.println(); 19650 pw.println("ContentProvider Authorities:"); 19651 printedSomething = true; 19652 } 19653 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19654 pw.print(" "); pw.println(p.toString()); 19655 if (p.info != null && p.info.applicationInfo != null) { 19656 final String appInfo = p.info.applicationInfo.toString(); 19657 pw.print(" applicationInfo="); pw.println(appInfo); 19658 } 19659 } 19660 } 19661 19662 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19663 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19664 } 19665 19666 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19667 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19668 } 19669 19670 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19671 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19672 } 19673 19674 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19675 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19676 } 19677 19678 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19679 // XXX should handle packageName != null by dumping only install data that 19680 // the given package is involved with. 19681 if (dumpState.onTitlePrinted()) pw.println(); 19682 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19683 } 19684 19685 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19686 // XXX should handle packageName != null by dumping only install data that 19687 // the given package is involved with. 19688 if (dumpState.onTitlePrinted()) pw.println(); 19689 19690 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19691 ipw.println(); 19692 ipw.println("Frozen packages:"); 19693 ipw.increaseIndent(); 19694 if (mFrozenPackages.size() == 0) { 19695 ipw.println("(none)"); 19696 } else { 19697 for (int i = 0; i < mFrozenPackages.size(); i++) { 19698 ipw.println(mFrozenPackages.valueAt(i)); 19699 } 19700 } 19701 ipw.decreaseIndent(); 19702 } 19703 19704 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19705 if (dumpState.onTitlePrinted()) pw.println(); 19706 dumpDexoptStateLPr(pw, packageName); 19707 } 19708 19709 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19710 if (dumpState.onTitlePrinted()) pw.println(); 19711 dumpCompilerStatsLPr(pw, packageName); 19712 } 19713 19714 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19715 if (dumpState.onTitlePrinted()) pw.println(); 19716 mSettings.dumpReadMessagesLPr(pw, dumpState); 19717 19718 pw.println(); 19719 pw.println("Package warning messages:"); 19720 BufferedReader in = null; 19721 String line = null; 19722 try { 19723 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19724 while ((line = in.readLine()) != null) { 19725 if (line.contains("ignored: updated version")) continue; 19726 pw.println(line); 19727 } 19728 } catch (IOException ignored) { 19729 } finally { 19730 IoUtils.closeQuietly(in); 19731 } 19732 } 19733 19734 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19735 BufferedReader in = null; 19736 String line = null; 19737 try { 19738 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19739 while ((line = in.readLine()) != null) { 19740 if (line.contains("ignored: updated version")) continue; 19741 pw.print("msg,"); 19742 pw.println(line); 19743 } 19744 } catch (IOException ignored) { 19745 } finally { 19746 IoUtils.closeQuietly(in); 19747 } 19748 } 19749 } 19750 } 19751 19752 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19753 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19754 ipw.println(); 19755 ipw.println("Dexopt state:"); 19756 ipw.increaseIndent(); 19757 Collection<PackageParser.Package> packages = null; 19758 if (packageName != null) { 19759 PackageParser.Package targetPackage = mPackages.get(packageName); 19760 if (targetPackage != null) { 19761 packages = Collections.singletonList(targetPackage); 19762 } else { 19763 ipw.println("Unable to find package: " + packageName); 19764 return; 19765 } 19766 } else { 19767 packages = mPackages.values(); 19768 } 19769 19770 for (PackageParser.Package pkg : packages) { 19771 ipw.println("[" + pkg.packageName + "]"); 19772 ipw.increaseIndent(); 19773 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19774 ipw.decreaseIndent(); 19775 } 19776 } 19777 19778 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19779 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19780 ipw.println(); 19781 ipw.println("Compiler stats:"); 19782 ipw.increaseIndent(); 19783 Collection<PackageParser.Package> packages = null; 19784 if (packageName != null) { 19785 PackageParser.Package targetPackage = mPackages.get(packageName); 19786 if (targetPackage != null) { 19787 packages = Collections.singletonList(targetPackage); 19788 } else { 19789 ipw.println("Unable to find package: " + packageName); 19790 return; 19791 } 19792 } else { 19793 packages = mPackages.values(); 19794 } 19795 19796 for (PackageParser.Package pkg : packages) { 19797 ipw.println("[" + pkg.packageName + "]"); 19798 ipw.increaseIndent(); 19799 19800 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19801 if (stats == null) { 19802 ipw.println("(No recorded stats)"); 19803 } else { 19804 stats.dump(ipw); 19805 } 19806 ipw.decreaseIndent(); 19807 } 19808 } 19809 19810 private String dumpDomainString(String packageName) { 19811 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19812 .getList(); 19813 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19814 19815 ArraySet<String> result = new ArraySet<>(); 19816 if (iviList.size() > 0) { 19817 for (IntentFilterVerificationInfo ivi : iviList) { 19818 for (String host : ivi.getDomains()) { 19819 result.add(host); 19820 } 19821 } 19822 } 19823 if (filters != null && filters.size() > 0) { 19824 for (IntentFilter filter : filters) { 19825 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19826 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19827 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19828 result.addAll(filter.getHostsList()); 19829 } 19830 } 19831 } 19832 19833 StringBuilder sb = new StringBuilder(result.size() * 16); 19834 for (String domain : result) { 19835 if (sb.length() > 0) sb.append(" "); 19836 sb.append(domain); 19837 } 19838 return sb.toString(); 19839 } 19840 19841 // ------- apps on sdcard specific code ------- 19842 static final boolean DEBUG_SD_INSTALL = false; 19843 19844 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19845 19846 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19847 19848 private boolean mMediaMounted = false; 19849 19850 static String getEncryptKey() { 19851 try { 19852 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19853 SD_ENCRYPTION_KEYSTORE_NAME); 19854 if (sdEncKey == null) { 19855 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19856 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19857 if (sdEncKey == null) { 19858 Slog.e(TAG, "Failed to create encryption keys"); 19859 return null; 19860 } 19861 } 19862 return sdEncKey; 19863 } catch (NoSuchAlgorithmException nsae) { 19864 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19865 return null; 19866 } catch (IOException ioe) { 19867 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19868 return null; 19869 } 19870 } 19871 19872 /* 19873 * Update media status on PackageManager. 19874 */ 19875 @Override 19876 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19877 int callingUid = Binder.getCallingUid(); 19878 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19879 throw new SecurityException("Media status can only be updated by the system"); 19880 } 19881 // reader; this apparently protects mMediaMounted, but should probably 19882 // be a different lock in that case. 19883 synchronized (mPackages) { 19884 Log.i(TAG, "Updating external media status from " 19885 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19886 + (mediaStatus ? "mounted" : "unmounted")); 19887 if (DEBUG_SD_INSTALL) 19888 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19889 + ", mMediaMounted=" + mMediaMounted); 19890 if (mediaStatus == mMediaMounted) { 19891 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19892 : 0, -1); 19893 mHandler.sendMessage(msg); 19894 return; 19895 } 19896 mMediaMounted = mediaStatus; 19897 } 19898 // Queue up an async operation since the package installation may take a 19899 // little while. 19900 mHandler.post(new Runnable() { 19901 public void run() { 19902 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19903 } 19904 }); 19905 } 19906 19907 /** 19908 * Called by StorageManagerService when the initial ASECs to scan are available. 19909 * Should block until all the ASEC containers are finished being scanned. 19910 */ 19911 public void scanAvailableAsecs() { 19912 updateExternalMediaStatusInner(true, false, false); 19913 } 19914 19915 /* 19916 * Collect information of applications on external media, map them against 19917 * existing containers and update information based on current mount status. 19918 * Please note that we always have to report status if reportStatus has been 19919 * set to true especially when unloading packages. 19920 */ 19921 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19922 boolean externalStorage) { 19923 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19924 int[] uidArr = EmptyArray.INT; 19925 19926 final String[] list = PackageHelper.getSecureContainerList(); 19927 if (ArrayUtils.isEmpty(list)) { 19928 Log.i(TAG, "No secure containers found"); 19929 } else { 19930 // Process list of secure containers and categorize them 19931 // as active or stale based on their package internal state. 19932 19933 // reader 19934 synchronized (mPackages) { 19935 for (String cid : list) { 19936 // Leave stages untouched for now; installer service owns them 19937 if (PackageInstallerService.isStageName(cid)) continue; 19938 19939 if (DEBUG_SD_INSTALL) 19940 Log.i(TAG, "Processing container " + cid); 19941 String pkgName = getAsecPackageName(cid); 19942 if (pkgName == null) { 19943 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19944 continue; 19945 } 19946 if (DEBUG_SD_INSTALL) 19947 Log.i(TAG, "Looking for pkg : " + pkgName); 19948 19949 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19950 if (ps == null) { 19951 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19952 continue; 19953 } 19954 19955 /* 19956 * Skip packages that are not external if we're unmounting 19957 * external storage. 19958 */ 19959 if (externalStorage && !isMounted && !isExternal(ps)) { 19960 continue; 19961 } 19962 19963 final AsecInstallArgs args = new AsecInstallArgs(cid, 19964 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19965 // The package status is changed only if the code path 19966 // matches between settings and the container id. 19967 if (ps.codePathString != null 19968 && ps.codePathString.startsWith(args.getCodePath())) { 19969 if (DEBUG_SD_INSTALL) { 19970 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19971 + " at code path: " + ps.codePathString); 19972 } 19973 19974 // We do have a valid package installed on sdcard 19975 processCids.put(args, ps.codePathString); 19976 final int uid = ps.appId; 19977 if (uid != -1) { 19978 uidArr = ArrayUtils.appendInt(uidArr, uid); 19979 } 19980 } else { 19981 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19982 + ps.codePathString); 19983 } 19984 } 19985 } 19986 19987 Arrays.sort(uidArr); 19988 } 19989 19990 // Process packages with valid entries. 19991 if (isMounted) { 19992 if (DEBUG_SD_INSTALL) 19993 Log.i(TAG, "Loading packages"); 19994 loadMediaPackages(processCids, uidArr, externalStorage); 19995 startCleaningPackages(); 19996 mInstallerService.onSecureContainersAvailable(); 19997 } else { 19998 if (DEBUG_SD_INSTALL) 19999 Log.i(TAG, "Unloading packages"); 20000 unloadMediaPackages(processCids, uidArr, reportStatus); 20001 } 20002 } 20003 20004 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20005 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 20006 final int size = infos.size(); 20007 final String[] packageNames = new String[size]; 20008 final int[] packageUids = new int[size]; 20009 for (int i = 0; i < size; i++) { 20010 final ApplicationInfo info = infos.get(i); 20011 packageNames[i] = info.packageName; 20012 packageUids[i] = info.uid; 20013 } 20014 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 20015 finishedReceiver); 20016 } 20017 20018 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20019 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 20020 sendResourcesChangedBroadcast(mediaStatus, replacing, 20021 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 20022 } 20023 20024 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 20025 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 20026 int size = pkgList.length; 20027 if (size > 0) { 20028 // Send broadcasts here 20029 Bundle extras = new Bundle(); 20030 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 20031 if (uidArr != null) { 20032 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 20033 } 20034 if (replacing) { 20035 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 20036 } 20037 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 20038 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 20039 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 20040 } 20041 } 20042 20043 /* 20044 * Look at potentially valid container ids from processCids If package 20045 * information doesn't match the one on record or package scanning fails, 20046 * the cid is added to list of removeCids. We currently don't delete stale 20047 * containers. 20048 */ 20049 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 20050 boolean externalStorage) { 20051 ArrayList<String> pkgList = new ArrayList<String>(); 20052 Set<AsecInstallArgs> keys = processCids.keySet(); 20053 20054 for (AsecInstallArgs args : keys) { 20055 String codePath = processCids.get(args); 20056 if (DEBUG_SD_INSTALL) 20057 Log.i(TAG, "Loading container : " + args.cid); 20058 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 20059 try { 20060 // Make sure there are no container errors first. 20061 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 20062 Slog.e(TAG, "Failed to mount cid : " + args.cid 20063 + " when installing from sdcard"); 20064 continue; 20065 } 20066 // Check code path here. 20067 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 20068 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 20069 + " does not match one in settings " + codePath); 20070 continue; 20071 } 20072 // Parse package 20073 int parseFlags = mDefParseFlags; 20074 if (args.isExternalAsec()) { 20075 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 20076 } 20077 if (args.isFwdLocked()) { 20078 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 20079 } 20080 20081 synchronized (mInstallLock) { 20082 PackageParser.Package pkg = null; 20083 try { 20084 // Sadly we don't know the package name yet to freeze it 20085 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 20086 SCAN_IGNORE_FROZEN, 0, null); 20087 } catch (PackageManagerException e) { 20088 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 20089 } 20090 // Scan the package 20091 if (pkg != null) { 20092 /* 20093 * TODO why is the lock being held? doPostInstall is 20094 * called in other places without the lock. This needs 20095 * to be straightened out. 20096 */ 20097 // writer 20098 synchronized (mPackages) { 20099 retCode = PackageManager.INSTALL_SUCCEEDED; 20100 pkgList.add(pkg.packageName); 20101 // Post process args 20102 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 20103 pkg.applicationInfo.uid); 20104 } 20105 } else { 20106 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 20107 } 20108 } 20109 20110 } finally { 20111 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 20112 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 20113 } 20114 } 20115 } 20116 // writer 20117 synchronized (mPackages) { 20118 // If the platform SDK has changed since the last time we booted, 20119 // we need to re-grant app permission to catch any new ones that 20120 // appear. This is really a hack, and means that apps can in some 20121 // cases get permissions that the user didn't initially explicitly 20122 // allow... it would be nice to have some better way to handle 20123 // this situation. 20124 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 20125 : mSettings.getInternalVersion(); 20126 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 20127 : StorageManager.UUID_PRIVATE_INTERNAL; 20128 20129 int updateFlags = UPDATE_PERMISSIONS_ALL; 20130 if (ver.sdkVersion != mSdkVersion) { 20131 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20132 + mSdkVersion + "; regranting permissions for external"); 20133 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20134 } 20135 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20136 20137 // Yay, everything is now upgraded 20138 ver.forceCurrent(); 20139 20140 // can downgrade to reader 20141 // Persist settings 20142 mSettings.writeLPr(); 20143 } 20144 // Send a broadcast to let everyone know we are done processing 20145 if (pkgList.size() > 0) { 20146 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 20147 } 20148 } 20149 20150 /* 20151 * Utility method to unload a list of specified containers 20152 */ 20153 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 20154 // Just unmount all valid containers. 20155 for (AsecInstallArgs arg : cidArgs) { 20156 synchronized (mInstallLock) { 20157 arg.doPostDeleteLI(false); 20158 } 20159 } 20160 } 20161 20162 /* 20163 * Unload packages mounted on external media. This involves deleting package 20164 * data from internal structures, sending broadcasts about disabled packages, 20165 * gc'ing to free up references, unmounting all secure containers 20166 * corresponding to packages on external media, and posting a 20167 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 20168 * that we always have to post this message if status has been requested no 20169 * matter what. 20170 */ 20171 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 20172 final boolean reportStatus) { 20173 if (DEBUG_SD_INSTALL) 20174 Log.i(TAG, "unloading media packages"); 20175 ArrayList<String> pkgList = new ArrayList<String>(); 20176 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 20177 final Set<AsecInstallArgs> keys = processCids.keySet(); 20178 for (AsecInstallArgs args : keys) { 20179 String pkgName = args.getPackageName(); 20180 if (DEBUG_SD_INSTALL) 20181 Log.i(TAG, "Trying to unload pkg : " + pkgName); 20182 // Delete package internally 20183 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20184 synchronized (mInstallLock) { 20185 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20186 final boolean res; 20187 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 20188 "unloadMediaPackages")) { 20189 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 20190 null); 20191 } 20192 if (res) { 20193 pkgList.add(pkgName); 20194 } else { 20195 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 20196 failedList.add(args); 20197 } 20198 } 20199 } 20200 20201 // reader 20202 synchronized (mPackages) { 20203 // We didn't update the settings after removing each package; 20204 // write them now for all packages. 20205 mSettings.writeLPr(); 20206 } 20207 20208 // We have to absolutely send UPDATED_MEDIA_STATUS only 20209 // after confirming that all the receivers processed the ordered 20210 // broadcast when packages get disabled, force a gc to clean things up. 20211 // and unload all the containers. 20212 if (pkgList.size() > 0) { 20213 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 20214 new IIntentReceiver.Stub() { 20215 public void performReceive(Intent intent, int resultCode, String data, 20216 Bundle extras, boolean ordered, boolean sticky, 20217 int sendingUser) throws RemoteException { 20218 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 20219 reportStatus ? 1 : 0, 1, keys); 20220 mHandler.sendMessage(msg); 20221 } 20222 }); 20223 } else { 20224 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 20225 keys); 20226 mHandler.sendMessage(msg); 20227 } 20228 } 20229 20230 private void loadPrivatePackages(final VolumeInfo vol) { 20231 mHandler.post(new Runnable() { 20232 @Override 20233 public void run() { 20234 loadPrivatePackagesInner(vol); 20235 } 20236 }); 20237 } 20238 20239 private void loadPrivatePackagesInner(VolumeInfo vol) { 20240 final String volumeUuid = vol.fsUuid; 20241 if (TextUtils.isEmpty(volumeUuid)) { 20242 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 20243 return; 20244 } 20245 20246 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 20247 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 20248 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 20249 20250 final VersionInfo ver; 20251 final List<PackageSetting> packages; 20252 synchronized (mPackages) { 20253 ver = mSettings.findOrCreateVersion(volumeUuid); 20254 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20255 } 20256 20257 for (PackageSetting ps : packages) { 20258 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 20259 synchronized (mInstallLock) { 20260 final PackageParser.Package pkg; 20261 try { 20262 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 20263 loaded.add(pkg.applicationInfo); 20264 20265 } catch (PackageManagerException e) { 20266 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 20267 } 20268 20269 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 20270 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 20271 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 20272 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20273 } 20274 } 20275 } 20276 20277 // Reconcile app data for all started/unlocked users 20278 final StorageManager sm = mContext.getSystemService(StorageManager.class); 20279 final UserManager um = mContext.getSystemService(UserManager.class); 20280 UserManagerInternal umInternal = getUserManagerInternal(); 20281 for (UserInfo user : um.getUsers()) { 20282 final int flags; 20283 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20284 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20285 } else if (umInternal.isUserRunning(user.id)) { 20286 flags = StorageManager.FLAG_STORAGE_DE; 20287 } else { 20288 continue; 20289 } 20290 20291 try { 20292 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 20293 synchronized (mInstallLock) { 20294 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 20295 } 20296 } catch (IllegalStateException e) { 20297 // Device was probably ejected, and we'll process that event momentarily 20298 Slog.w(TAG, "Failed to prepare storage: " + e); 20299 } 20300 } 20301 20302 synchronized (mPackages) { 20303 int updateFlags = UPDATE_PERMISSIONS_ALL; 20304 if (ver.sdkVersion != mSdkVersion) { 20305 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20306 + mSdkVersion + "; regranting permissions for " + volumeUuid); 20307 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20308 } 20309 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20310 20311 // Yay, everything is now upgraded 20312 ver.forceCurrent(); 20313 20314 mSettings.writeLPr(); 20315 } 20316 20317 for (PackageFreezer freezer : freezers) { 20318 freezer.close(); 20319 } 20320 20321 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 20322 sendResourcesChangedBroadcast(true, false, loaded, null); 20323 } 20324 20325 private void unloadPrivatePackages(final VolumeInfo vol) { 20326 mHandler.post(new Runnable() { 20327 @Override 20328 public void run() { 20329 unloadPrivatePackagesInner(vol); 20330 } 20331 }); 20332 } 20333 20334 private void unloadPrivatePackagesInner(VolumeInfo vol) { 20335 final String volumeUuid = vol.fsUuid; 20336 if (TextUtils.isEmpty(volumeUuid)) { 20337 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 20338 return; 20339 } 20340 20341 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 20342 synchronized (mInstallLock) { 20343 synchronized (mPackages) { 20344 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 20345 for (PackageSetting ps : packages) { 20346 if (ps.pkg == null) continue; 20347 20348 final ApplicationInfo info = ps.pkg.applicationInfo; 20349 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20350 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20351 20352 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 20353 "unloadPrivatePackagesInner")) { 20354 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 20355 false, null)) { 20356 unloaded.add(info); 20357 } else { 20358 Slog.w(TAG, "Failed to unload " + ps.codePath); 20359 } 20360 } 20361 20362 // Try very hard to release any references to this package 20363 // so we don't risk the system server being killed due to 20364 // open FDs 20365 AttributeCache.instance().removePackage(ps.name); 20366 } 20367 20368 mSettings.writeLPr(); 20369 } 20370 } 20371 20372 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 20373 sendResourcesChangedBroadcast(false, false, unloaded, null); 20374 20375 // Try very hard to release any references to this path so we don't risk 20376 // the system server being killed due to open FDs 20377 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 20378 20379 for (int i = 0; i < 3; i++) { 20380 System.gc(); 20381 System.runFinalization(); 20382 } 20383 } 20384 20385 /** 20386 * Prepare storage areas for given user on all mounted devices. 20387 */ 20388 void prepareUserData(int userId, int userSerial, int flags) { 20389 synchronized (mInstallLock) { 20390 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20391 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20392 final String volumeUuid = vol.getFsUuid(); 20393 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 20394 } 20395 } 20396 } 20397 20398 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 20399 boolean allowRecover) { 20400 // Prepare storage and verify that serial numbers are consistent; if 20401 // there's a mismatch we need to destroy to avoid leaking data 20402 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20403 try { 20404 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 20405 20406 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 20407 UserManagerService.enforceSerialNumber( 20408 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 20409 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20410 UserManagerService.enforceSerialNumber( 20411 Environment.getDataSystemDeDirectory(userId), userSerial); 20412 } 20413 } 20414 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 20415 UserManagerService.enforceSerialNumber( 20416 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 20417 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20418 UserManagerService.enforceSerialNumber( 20419 Environment.getDataSystemCeDirectory(userId), userSerial); 20420 } 20421 } 20422 20423 synchronized (mInstallLock) { 20424 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20425 } 20426 } catch (Exception e) { 20427 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20428 + " because we failed to prepare: " + e); 20429 destroyUserDataLI(volumeUuid, userId, 20430 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20431 20432 if (allowRecover) { 20433 // Try one last time; if we fail again we're really in trouble 20434 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20435 } 20436 } 20437 } 20438 20439 /** 20440 * Destroy storage areas for given user on all mounted devices. 20441 */ 20442 void destroyUserData(int userId, int flags) { 20443 synchronized (mInstallLock) { 20444 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20445 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20446 final String volumeUuid = vol.getFsUuid(); 20447 destroyUserDataLI(volumeUuid, userId, flags); 20448 } 20449 } 20450 } 20451 20452 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20453 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20454 try { 20455 // Clean up app data, profile data, and media data 20456 mInstaller.destroyUserData(volumeUuid, userId, flags); 20457 20458 // Clean up system data 20459 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20460 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20461 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20462 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20463 } 20464 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20465 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20466 } 20467 } 20468 20469 // Data with special labels is now gone, so finish the job 20470 storage.destroyUserStorage(volumeUuid, userId, flags); 20471 20472 } catch (Exception e) { 20473 logCriticalInfo(Log.WARN, 20474 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20475 } 20476 } 20477 20478 /** 20479 * Examine all users present on given mounted volume, and destroy data 20480 * belonging to users that are no longer valid, or whose user ID has been 20481 * recycled. 20482 */ 20483 private void reconcileUsers(String volumeUuid) { 20484 final List<File> files = new ArrayList<>(); 20485 Collections.addAll(files, FileUtils 20486 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20487 Collections.addAll(files, FileUtils 20488 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20489 Collections.addAll(files, FileUtils 20490 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20491 Collections.addAll(files, FileUtils 20492 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20493 for (File file : files) { 20494 if (!file.isDirectory()) continue; 20495 20496 final int userId; 20497 final UserInfo info; 20498 try { 20499 userId = Integer.parseInt(file.getName()); 20500 info = sUserManager.getUserInfo(userId); 20501 } catch (NumberFormatException e) { 20502 Slog.w(TAG, "Invalid user directory " + file); 20503 continue; 20504 } 20505 20506 boolean destroyUser = false; 20507 if (info == null) { 20508 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20509 + " because no matching user was found"); 20510 destroyUser = true; 20511 } else if (!mOnlyCore) { 20512 try { 20513 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20514 } catch (IOException e) { 20515 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20516 + " because we failed to enforce serial number: " + e); 20517 destroyUser = true; 20518 } 20519 } 20520 20521 if (destroyUser) { 20522 synchronized (mInstallLock) { 20523 destroyUserDataLI(volumeUuid, userId, 20524 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20525 } 20526 } 20527 } 20528 } 20529 20530 private void assertPackageKnown(String volumeUuid, String packageName) 20531 throws PackageManagerException { 20532 synchronized (mPackages) { 20533 // Normalize package name to handle renamed packages 20534 packageName = normalizePackageNameLPr(packageName); 20535 20536 final PackageSetting ps = mSettings.mPackages.get(packageName); 20537 if (ps == null) { 20538 throw new PackageManagerException("Package " + packageName + " is unknown"); 20539 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20540 throw new PackageManagerException( 20541 "Package " + packageName + " found on unknown volume " + volumeUuid 20542 + "; expected volume " + ps.volumeUuid); 20543 } 20544 } 20545 } 20546 20547 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20548 throws PackageManagerException { 20549 synchronized (mPackages) { 20550 // Normalize package name to handle renamed packages 20551 packageName = normalizePackageNameLPr(packageName); 20552 20553 final PackageSetting ps = mSettings.mPackages.get(packageName); 20554 if (ps == null) { 20555 throw new PackageManagerException("Package " + packageName + " is unknown"); 20556 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20557 throw new PackageManagerException( 20558 "Package " + packageName + " found on unknown volume " + volumeUuid 20559 + "; expected volume " + ps.volumeUuid); 20560 } else if (!ps.getInstalled(userId)) { 20561 throw new PackageManagerException( 20562 "Package " + packageName + " not installed for user " + userId); 20563 } 20564 } 20565 } 20566 20567 /** 20568 * Examine all apps present on given mounted volume, and destroy apps that 20569 * aren't expected, either due to uninstallation or reinstallation on 20570 * another volume. 20571 */ 20572 private void reconcileApps(String volumeUuid) { 20573 final File[] files = FileUtils 20574 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20575 for (File file : files) { 20576 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20577 && !PackageInstallerService.isStageName(file.getName()); 20578 if (!isPackage) { 20579 // Ignore entries which are not packages 20580 continue; 20581 } 20582 20583 try { 20584 final PackageLite pkg = PackageParser.parsePackageLite(file, 20585 PackageParser.PARSE_MUST_BE_APK); 20586 assertPackageKnown(volumeUuid, pkg.packageName); 20587 20588 } catch (PackageParserException | PackageManagerException e) { 20589 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20590 synchronized (mInstallLock) { 20591 removeCodePathLI(file); 20592 } 20593 } 20594 } 20595 } 20596 20597 /** 20598 * Reconcile all app data for the given user. 20599 * <p> 20600 * Verifies that directories exist and that ownership and labeling is 20601 * correct for all installed apps on all mounted volumes. 20602 */ 20603 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20604 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20605 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20606 final String volumeUuid = vol.getFsUuid(); 20607 synchronized (mInstallLock) { 20608 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20609 } 20610 } 20611 } 20612 20613 /** 20614 * Reconcile all app data on given mounted volume. 20615 * <p> 20616 * Destroys app data that isn't expected, either due to uninstallation or 20617 * reinstallation on another volume. 20618 * <p> 20619 * Verifies that directories exist and that ownership and labeling is 20620 * correct for all installed apps. 20621 */ 20622 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20623 boolean migrateAppData) { 20624 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20625 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20626 20627 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20628 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20629 20630 // First look for stale data that doesn't belong, and check if things 20631 // have changed since we did our last restorecon 20632 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20633 if (StorageManager.isFileEncryptedNativeOrEmulated() 20634 && !StorageManager.isUserKeyUnlocked(userId)) { 20635 throw new RuntimeException( 20636 "Yikes, someone asked us to reconcile CE storage while " + userId 20637 + " was still locked; this would have caused massive data loss!"); 20638 } 20639 20640 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20641 for (File file : files) { 20642 final String packageName = file.getName(); 20643 try { 20644 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20645 } catch (PackageManagerException e) { 20646 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20647 try { 20648 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20649 StorageManager.FLAG_STORAGE_CE, 0); 20650 } catch (InstallerException e2) { 20651 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20652 } 20653 } 20654 } 20655 } 20656 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20657 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20658 for (File file : files) { 20659 final String packageName = file.getName(); 20660 try { 20661 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20662 } catch (PackageManagerException e) { 20663 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20664 try { 20665 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20666 StorageManager.FLAG_STORAGE_DE, 0); 20667 } catch (InstallerException e2) { 20668 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20669 } 20670 } 20671 } 20672 } 20673 20674 // Ensure that data directories are ready to roll for all packages 20675 // installed for this volume and user 20676 final List<PackageSetting> packages; 20677 synchronized (mPackages) { 20678 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20679 } 20680 int preparedCount = 0; 20681 for (PackageSetting ps : packages) { 20682 final String packageName = ps.name; 20683 if (ps.pkg == null) { 20684 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20685 // TODO: might be due to legacy ASEC apps; we should circle back 20686 // and reconcile again once they're scanned 20687 continue; 20688 } 20689 20690 if (ps.getInstalled(userId)) { 20691 prepareAppDataLIF(ps.pkg, userId, flags); 20692 20693 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20694 // We may have just shuffled around app data directories, so 20695 // prepare them one more time 20696 prepareAppDataLIF(ps.pkg, userId, flags); 20697 } 20698 20699 preparedCount++; 20700 } 20701 } 20702 20703 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20704 } 20705 20706 /** 20707 * Prepare app data for the given app just after it was installed or 20708 * upgraded. This method carefully only touches users that it's installed 20709 * for, and it forces a restorecon to handle any seinfo changes. 20710 * <p> 20711 * Verifies that directories exist and that ownership and labeling is 20712 * correct for all installed apps. If there is an ownership mismatch, it 20713 * will try recovering system apps by wiping data; third-party app data is 20714 * left intact. 20715 * <p> 20716 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20717 */ 20718 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20719 final PackageSetting ps; 20720 synchronized (mPackages) { 20721 ps = mSettings.mPackages.get(pkg.packageName); 20722 mSettings.writeKernelMappingLPr(ps); 20723 } 20724 20725 final UserManager um = mContext.getSystemService(UserManager.class); 20726 UserManagerInternal umInternal = getUserManagerInternal(); 20727 for (UserInfo user : um.getUsers()) { 20728 final int flags; 20729 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20730 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20731 } else if (umInternal.isUserRunning(user.id)) { 20732 flags = StorageManager.FLAG_STORAGE_DE; 20733 } else { 20734 continue; 20735 } 20736 20737 if (ps.getInstalled(user.id)) { 20738 // TODO: when user data is locked, mark that we're still dirty 20739 prepareAppDataLIF(pkg, user.id, flags); 20740 } 20741 } 20742 } 20743 20744 /** 20745 * Prepare app data for the given app. 20746 * <p> 20747 * Verifies that directories exist and that ownership and labeling is 20748 * correct for all installed apps. If there is an ownership mismatch, this 20749 * will try recovering system apps by wiping data; third-party app data is 20750 * left intact. 20751 */ 20752 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20753 if (pkg == null) { 20754 Slog.wtf(TAG, "Package was null!", new Throwable()); 20755 return; 20756 } 20757 prepareAppDataLeafLIF(pkg, userId, flags); 20758 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20759 for (int i = 0; i < childCount; i++) { 20760 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20761 } 20762 } 20763 20764 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20765 if (DEBUG_APP_DATA) { 20766 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20767 + Integer.toHexString(flags)); 20768 } 20769 20770 final String volumeUuid = pkg.volumeUuid; 20771 final String packageName = pkg.packageName; 20772 final ApplicationInfo app = pkg.applicationInfo; 20773 final int appId = UserHandle.getAppId(app.uid); 20774 20775 Preconditions.checkNotNull(app.seinfo); 20776 20777 long ceDataInode = -1; 20778 try { 20779 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20780 appId, app.seinfo, app.targetSdkVersion); 20781 } catch (InstallerException e) { 20782 if (app.isSystemApp()) { 20783 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20784 + ", but trying to recover: " + e); 20785 destroyAppDataLeafLIF(pkg, userId, flags); 20786 try { 20787 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20788 appId, app.seinfo, app.targetSdkVersion); 20789 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20790 } catch (InstallerException e2) { 20791 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20792 } 20793 } else { 20794 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20795 } 20796 } 20797 20798 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20799 // TODO: mark this structure as dirty so we persist it! 20800 synchronized (mPackages) { 20801 final PackageSetting ps = mSettings.mPackages.get(packageName); 20802 if (ps != null) { 20803 ps.setCeDataInode(ceDataInode, userId); 20804 } 20805 } 20806 } 20807 20808 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20809 } 20810 20811 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20812 if (pkg == null) { 20813 Slog.wtf(TAG, "Package was null!", new Throwable()); 20814 return; 20815 } 20816 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20817 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20818 for (int i = 0; i < childCount; i++) { 20819 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20820 } 20821 } 20822 20823 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20824 final String volumeUuid = pkg.volumeUuid; 20825 final String packageName = pkg.packageName; 20826 final ApplicationInfo app = pkg.applicationInfo; 20827 20828 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20829 // Create a native library symlink only if we have native libraries 20830 // and if the native libraries are 32 bit libraries. We do not provide 20831 // this symlink for 64 bit libraries. 20832 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20833 final String nativeLibPath = app.nativeLibraryDir; 20834 try { 20835 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20836 nativeLibPath, userId); 20837 } catch (InstallerException e) { 20838 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20839 } 20840 } 20841 } 20842 } 20843 20844 /** 20845 * For system apps on non-FBE devices, this method migrates any existing 20846 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20847 * requested by the app. 20848 */ 20849 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20850 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20851 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20852 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20853 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20854 try { 20855 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20856 storageTarget); 20857 } catch (InstallerException e) { 20858 logCriticalInfo(Log.WARN, 20859 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20860 } 20861 return true; 20862 } else { 20863 return false; 20864 } 20865 } 20866 20867 public PackageFreezer freezePackage(String packageName, String killReason) { 20868 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20869 } 20870 20871 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20872 return new PackageFreezer(packageName, userId, killReason); 20873 } 20874 20875 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20876 String killReason) { 20877 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20878 } 20879 20880 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20881 String killReason) { 20882 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20883 return new PackageFreezer(); 20884 } else { 20885 return freezePackage(packageName, userId, killReason); 20886 } 20887 } 20888 20889 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20890 String killReason) { 20891 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20892 } 20893 20894 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20895 String killReason) { 20896 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20897 return new PackageFreezer(); 20898 } else { 20899 return freezePackage(packageName, userId, killReason); 20900 } 20901 } 20902 20903 /** 20904 * Class that freezes and kills the given package upon creation, and 20905 * unfreezes it upon closing. This is typically used when doing surgery on 20906 * app code/data to prevent the app from running while you're working. 20907 */ 20908 private class PackageFreezer implements AutoCloseable { 20909 private final String mPackageName; 20910 private final PackageFreezer[] mChildren; 20911 20912 private final boolean mWeFroze; 20913 20914 private final AtomicBoolean mClosed = new AtomicBoolean(); 20915 private final CloseGuard mCloseGuard = CloseGuard.get(); 20916 20917 /** 20918 * Create and return a stub freezer that doesn't actually do anything, 20919 * typically used when someone requested 20920 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20921 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20922 */ 20923 public PackageFreezer() { 20924 mPackageName = null; 20925 mChildren = null; 20926 mWeFroze = false; 20927 mCloseGuard.open("close"); 20928 } 20929 20930 public PackageFreezer(String packageName, int userId, String killReason) { 20931 synchronized (mPackages) { 20932 mPackageName = packageName; 20933 mWeFroze = mFrozenPackages.add(mPackageName); 20934 20935 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20936 if (ps != null) { 20937 killApplication(ps.name, ps.appId, userId, killReason); 20938 } 20939 20940 final PackageParser.Package p = mPackages.get(packageName); 20941 if (p != null && p.childPackages != null) { 20942 final int N = p.childPackages.size(); 20943 mChildren = new PackageFreezer[N]; 20944 for (int i = 0; i < N; i++) { 20945 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20946 userId, killReason); 20947 } 20948 } else { 20949 mChildren = null; 20950 } 20951 } 20952 mCloseGuard.open("close"); 20953 } 20954 20955 @Override 20956 protected void finalize() throws Throwable { 20957 try { 20958 mCloseGuard.warnIfOpen(); 20959 close(); 20960 } finally { 20961 super.finalize(); 20962 } 20963 } 20964 20965 @Override 20966 public void close() { 20967 mCloseGuard.close(); 20968 if (mClosed.compareAndSet(false, true)) { 20969 synchronized (mPackages) { 20970 if (mWeFroze) { 20971 mFrozenPackages.remove(mPackageName); 20972 } 20973 20974 if (mChildren != null) { 20975 for (PackageFreezer freezer : mChildren) { 20976 freezer.close(); 20977 } 20978 } 20979 } 20980 } 20981 } 20982 } 20983 20984 /** 20985 * Verify that given package is currently frozen. 20986 */ 20987 private void checkPackageFrozen(String packageName) { 20988 synchronized (mPackages) { 20989 if (!mFrozenPackages.contains(packageName)) { 20990 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20991 } 20992 } 20993 } 20994 20995 @Override 20996 public int movePackage(final String packageName, final String volumeUuid) { 20997 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20998 20999 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 21000 final int moveId = mNextMoveId.getAndIncrement(); 21001 mHandler.post(new Runnable() { 21002 @Override 21003 public void run() { 21004 try { 21005 movePackageInternal(packageName, volumeUuid, moveId, user); 21006 } catch (PackageManagerException e) { 21007 Slog.w(TAG, "Failed to move " + packageName, e); 21008 mMoveCallbacks.notifyStatusChanged(moveId, 21009 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21010 } 21011 } 21012 }); 21013 return moveId; 21014 } 21015 21016 private void movePackageInternal(final String packageName, final String volumeUuid, 21017 final int moveId, UserHandle user) throws PackageManagerException { 21018 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21019 final PackageManager pm = mContext.getPackageManager(); 21020 21021 final boolean currentAsec; 21022 final String currentVolumeUuid; 21023 final File codeFile; 21024 final String installerPackageName; 21025 final String packageAbiOverride; 21026 final int appId; 21027 final String seinfo; 21028 final String label; 21029 final int targetSdkVersion; 21030 final PackageFreezer freezer; 21031 final int[] installedUserIds; 21032 21033 // reader 21034 synchronized (mPackages) { 21035 final PackageParser.Package pkg = mPackages.get(packageName); 21036 final PackageSetting ps = mSettings.mPackages.get(packageName); 21037 if (pkg == null || ps == null) { 21038 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 21039 } 21040 21041 if (pkg.applicationInfo.isSystemApp()) { 21042 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 21043 "Cannot move system application"); 21044 } 21045 21046 if (pkg.applicationInfo.isExternalAsec()) { 21047 currentAsec = true; 21048 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 21049 } else if (pkg.applicationInfo.isForwardLocked()) { 21050 currentAsec = true; 21051 currentVolumeUuid = "forward_locked"; 21052 } else { 21053 currentAsec = false; 21054 currentVolumeUuid = ps.volumeUuid; 21055 21056 final File probe = new File(pkg.codePath); 21057 final File probeOat = new File(probe, "oat"); 21058 if (!probe.isDirectory() || !probeOat.isDirectory()) { 21059 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21060 "Move only supported for modern cluster style installs"); 21061 } 21062 } 21063 21064 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 21065 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21066 "Package already moved to " + volumeUuid); 21067 } 21068 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 21069 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 21070 "Device admin cannot be moved"); 21071 } 21072 21073 if (mFrozenPackages.contains(packageName)) { 21074 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 21075 "Failed to move already frozen package"); 21076 } 21077 21078 codeFile = new File(pkg.codePath); 21079 installerPackageName = ps.installerPackageName; 21080 packageAbiOverride = ps.cpuAbiOverrideString; 21081 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 21082 seinfo = pkg.applicationInfo.seinfo; 21083 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 21084 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 21085 freezer = freezePackage(packageName, "movePackageInternal"); 21086 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 21087 } 21088 21089 final Bundle extras = new Bundle(); 21090 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 21091 extras.putString(Intent.EXTRA_TITLE, label); 21092 mMoveCallbacks.notifyCreated(moveId, extras); 21093 21094 int installFlags; 21095 final boolean moveCompleteApp; 21096 final File measurePath; 21097 21098 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 21099 installFlags = INSTALL_INTERNAL; 21100 moveCompleteApp = !currentAsec; 21101 measurePath = Environment.getDataAppDirectory(volumeUuid); 21102 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 21103 installFlags = INSTALL_EXTERNAL; 21104 moveCompleteApp = false; 21105 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 21106 } else { 21107 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 21108 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 21109 || !volume.isMountedWritable()) { 21110 freezer.close(); 21111 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21112 "Move location not mounted private volume"); 21113 } 21114 21115 Preconditions.checkState(!currentAsec); 21116 21117 installFlags = INSTALL_INTERNAL; 21118 moveCompleteApp = true; 21119 measurePath = Environment.getDataAppDirectory(volumeUuid); 21120 } 21121 21122 final PackageStats stats = new PackageStats(null, -1); 21123 synchronized (mInstaller) { 21124 for (int userId : installedUserIds) { 21125 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 21126 freezer.close(); 21127 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21128 "Failed to measure package size"); 21129 } 21130 } 21131 } 21132 21133 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 21134 + stats.dataSize); 21135 21136 final long startFreeBytes = measurePath.getFreeSpace(); 21137 final long sizeBytes; 21138 if (moveCompleteApp) { 21139 sizeBytes = stats.codeSize + stats.dataSize; 21140 } else { 21141 sizeBytes = stats.codeSize; 21142 } 21143 21144 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 21145 freezer.close(); 21146 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21147 "Not enough free space to move"); 21148 } 21149 21150 mMoveCallbacks.notifyStatusChanged(moveId, 10); 21151 21152 final CountDownLatch installedLatch = new CountDownLatch(1); 21153 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 21154 @Override 21155 public void onUserActionRequired(Intent intent) throws RemoteException { 21156 throw new IllegalStateException(); 21157 } 21158 21159 @Override 21160 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 21161 Bundle extras) throws RemoteException { 21162 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 21163 + PackageManager.installStatusToString(returnCode, msg)); 21164 21165 installedLatch.countDown(); 21166 freezer.close(); 21167 21168 final int status = PackageManager.installStatusToPublicStatus(returnCode); 21169 switch (status) { 21170 case PackageInstaller.STATUS_SUCCESS: 21171 mMoveCallbacks.notifyStatusChanged(moveId, 21172 PackageManager.MOVE_SUCCEEDED); 21173 break; 21174 case PackageInstaller.STATUS_FAILURE_STORAGE: 21175 mMoveCallbacks.notifyStatusChanged(moveId, 21176 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 21177 break; 21178 default: 21179 mMoveCallbacks.notifyStatusChanged(moveId, 21180 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21181 break; 21182 } 21183 } 21184 }; 21185 21186 final MoveInfo move; 21187 if (moveCompleteApp) { 21188 // Kick off a thread to report progress estimates 21189 new Thread() { 21190 @Override 21191 public void run() { 21192 while (true) { 21193 try { 21194 if (installedLatch.await(1, TimeUnit.SECONDS)) { 21195 break; 21196 } 21197 } catch (InterruptedException ignored) { 21198 } 21199 21200 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 21201 final int progress = 10 + (int) MathUtils.constrain( 21202 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 21203 mMoveCallbacks.notifyStatusChanged(moveId, progress); 21204 } 21205 } 21206 }.start(); 21207 21208 final String dataAppName = codeFile.getName(); 21209 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 21210 dataAppName, appId, seinfo, targetSdkVersion); 21211 } else { 21212 move = null; 21213 } 21214 21215 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 21216 21217 final Message msg = mHandler.obtainMessage(INIT_COPY); 21218 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 21219 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 21220 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 21221 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 21222 PackageManager.INSTALL_REASON_UNKNOWN); 21223 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 21224 msg.obj = params; 21225 21226 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 21227 System.identityHashCode(msg.obj)); 21228 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 21229 System.identityHashCode(msg.obj)); 21230 21231 mHandler.sendMessage(msg); 21232 } 21233 21234 @Override 21235 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 21236 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21237 21238 final int realMoveId = mNextMoveId.getAndIncrement(); 21239 final Bundle extras = new Bundle(); 21240 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 21241 mMoveCallbacks.notifyCreated(realMoveId, extras); 21242 21243 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 21244 @Override 21245 public void onCreated(int moveId, Bundle extras) { 21246 // Ignored 21247 } 21248 21249 @Override 21250 public void onStatusChanged(int moveId, int status, long estMillis) { 21251 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 21252 } 21253 }; 21254 21255 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21256 storage.setPrimaryStorageUuid(volumeUuid, callback); 21257 return realMoveId; 21258 } 21259 21260 @Override 21261 public int getMoveStatus(int moveId) { 21262 mContext.enforceCallingOrSelfPermission( 21263 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21264 return mMoveCallbacks.mLastStatus.get(moveId); 21265 } 21266 21267 @Override 21268 public void registerMoveCallback(IPackageMoveObserver callback) { 21269 mContext.enforceCallingOrSelfPermission( 21270 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21271 mMoveCallbacks.register(callback); 21272 } 21273 21274 @Override 21275 public void unregisterMoveCallback(IPackageMoveObserver callback) { 21276 mContext.enforceCallingOrSelfPermission( 21277 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21278 mMoveCallbacks.unregister(callback); 21279 } 21280 21281 @Override 21282 public boolean setInstallLocation(int loc) { 21283 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 21284 null); 21285 if (getInstallLocation() == loc) { 21286 return true; 21287 } 21288 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 21289 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 21290 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 21291 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 21292 return true; 21293 } 21294 return false; 21295 } 21296 21297 @Override 21298 public int getInstallLocation() { 21299 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 21300 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 21301 PackageHelper.APP_INSTALL_AUTO); 21302 } 21303 21304 /** Called by UserManagerService */ 21305 void cleanUpUser(UserManagerService userManager, int userHandle) { 21306 synchronized (mPackages) { 21307 mDirtyUsers.remove(userHandle); 21308 mUserNeedsBadging.delete(userHandle); 21309 mSettings.removeUserLPw(userHandle); 21310 mPendingBroadcasts.remove(userHandle); 21311 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 21312 removeUnusedPackagesLPw(userManager, userHandle); 21313 } 21314 } 21315 21316 /** 21317 * We're removing userHandle and would like to remove any downloaded packages 21318 * that are no longer in use by any other user. 21319 * @param userHandle the user being removed 21320 */ 21321 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 21322 final boolean DEBUG_CLEAN_APKS = false; 21323 int [] users = userManager.getUserIds(); 21324 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 21325 while (psit.hasNext()) { 21326 PackageSetting ps = psit.next(); 21327 if (ps.pkg == null) { 21328 continue; 21329 } 21330 final String packageName = ps.pkg.packageName; 21331 // Skip over if system app 21332 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 21333 continue; 21334 } 21335 if (DEBUG_CLEAN_APKS) { 21336 Slog.i(TAG, "Checking package " + packageName); 21337 } 21338 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 21339 if (keep) { 21340 if (DEBUG_CLEAN_APKS) { 21341 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 21342 } 21343 } else { 21344 for (int i = 0; i < users.length; i++) { 21345 if (users[i] != userHandle && ps.getInstalled(users[i])) { 21346 keep = true; 21347 if (DEBUG_CLEAN_APKS) { 21348 Slog.i(TAG, " Keeping package " + packageName + " for user " 21349 + users[i]); 21350 } 21351 break; 21352 } 21353 } 21354 } 21355 if (!keep) { 21356 if (DEBUG_CLEAN_APKS) { 21357 Slog.i(TAG, " Removing package " + packageName); 21358 } 21359 mHandler.post(new Runnable() { 21360 public void run() { 21361 deletePackageX(packageName, userHandle, 0); 21362 } //end run 21363 }); 21364 } 21365 } 21366 } 21367 21368 /** Called by UserManagerService */ 21369 void createNewUser(int userId, String[] disallowedPackages) { 21370 synchronized (mInstallLock) { 21371 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 21372 } 21373 synchronized (mPackages) { 21374 scheduleWritePackageRestrictionsLocked(userId); 21375 scheduleWritePackageListLocked(userId); 21376 applyFactoryDefaultBrowserLPw(userId); 21377 primeDomainVerificationsLPw(userId); 21378 } 21379 } 21380 21381 void onNewUserCreated(final int userId) { 21382 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21383 // If permission review for legacy apps is required, we represent 21384 // dagerous permissions for such apps as always granted runtime 21385 // permissions to keep per user flag state whether review is needed. 21386 // Hence, if a new user is added we have to propagate dangerous 21387 // permission grants for these legacy apps. 21388 if (mPermissionReviewRequired) { 21389 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 21390 | UPDATE_PERMISSIONS_REPLACE_ALL); 21391 } 21392 } 21393 21394 @Override 21395 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 21396 mContext.enforceCallingOrSelfPermission( 21397 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 21398 "Only package verification agents can read the verifier device identity"); 21399 21400 synchronized (mPackages) { 21401 return mSettings.getVerifierDeviceIdentityLPw(); 21402 } 21403 } 21404 21405 @Override 21406 public void setPermissionEnforced(String permission, boolean enforced) { 21407 // TODO: Now that we no longer change GID for storage, this should to away. 21408 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 21409 "setPermissionEnforced"); 21410 if (READ_EXTERNAL_STORAGE.equals(permission)) { 21411 synchronized (mPackages) { 21412 if (mSettings.mReadExternalStorageEnforced == null 21413 || mSettings.mReadExternalStorageEnforced != enforced) { 21414 mSettings.mReadExternalStorageEnforced = enforced; 21415 mSettings.writeLPr(); 21416 } 21417 } 21418 // kill any non-foreground processes so we restart them and 21419 // grant/revoke the GID. 21420 final IActivityManager am = ActivityManager.getService(); 21421 if (am != null) { 21422 final long token = Binder.clearCallingIdentity(); 21423 try { 21424 am.killProcessesBelowForeground("setPermissionEnforcement"); 21425 } catch (RemoteException e) { 21426 } finally { 21427 Binder.restoreCallingIdentity(token); 21428 } 21429 } 21430 } else { 21431 throw new IllegalArgumentException("No selective enforcement for " + permission); 21432 } 21433 } 21434 21435 @Override 21436 @Deprecated 21437 public boolean isPermissionEnforced(String permission) { 21438 return true; 21439 } 21440 21441 @Override 21442 public boolean isStorageLow() { 21443 final long token = Binder.clearCallingIdentity(); 21444 try { 21445 final DeviceStorageMonitorInternal 21446 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21447 if (dsm != null) { 21448 return dsm.isMemoryLow(); 21449 } else { 21450 return false; 21451 } 21452 } finally { 21453 Binder.restoreCallingIdentity(token); 21454 } 21455 } 21456 21457 @Override 21458 public IPackageInstaller getPackageInstaller() { 21459 return mInstallerService; 21460 } 21461 21462 private boolean userNeedsBadging(int userId) { 21463 int index = mUserNeedsBadging.indexOfKey(userId); 21464 if (index < 0) { 21465 final UserInfo userInfo; 21466 final long token = Binder.clearCallingIdentity(); 21467 try { 21468 userInfo = sUserManager.getUserInfo(userId); 21469 } finally { 21470 Binder.restoreCallingIdentity(token); 21471 } 21472 final boolean b; 21473 if (userInfo != null && userInfo.isManagedProfile()) { 21474 b = true; 21475 } else { 21476 b = false; 21477 } 21478 mUserNeedsBadging.put(userId, b); 21479 return b; 21480 } 21481 return mUserNeedsBadging.valueAt(index); 21482 } 21483 21484 @Override 21485 public KeySet getKeySetByAlias(String packageName, String alias) { 21486 if (packageName == null || alias == null) { 21487 return null; 21488 } 21489 synchronized(mPackages) { 21490 final PackageParser.Package pkg = mPackages.get(packageName); 21491 if (pkg == null) { 21492 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21493 throw new IllegalArgumentException("Unknown package: " + packageName); 21494 } 21495 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21496 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21497 } 21498 } 21499 21500 @Override 21501 public KeySet getSigningKeySet(String packageName) { 21502 if (packageName == null) { 21503 return null; 21504 } 21505 synchronized(mPackages) { 21506 final PackageParser.Package pkg = mPackages.get(packageName); 21507 if (pkg == null) { 21508 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21509 throw new IllegalArgumentException("Unknown package: " + packageName); 21510 } 21511 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21512 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21513 throw new SecurityException("May not access signing KeySet of other apps."); 21514 } 21515 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21516 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21517 } 21518 } 21519 21520 @Override 21521 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21522 if (packageName == null || ks == null) { 21523 return false; 21524 } 21525 synchronized(mPackages) { 21526 final PackageParser.Package pkg = mPackages.get(packageName); 21527 if (pkg == null) { 21528 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21529 throw new IllegalArgumentException("Unknown package: " + packageName); 21530 } 21531 IBinder ksh = ks.getToken(); 21532 if (ksh instanceof KeySetHandle) { 21533 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21534 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21535 } 21536 return false; 21537 } 21538 } 21539 21540 @Override 21541 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21542 if (packageName == null || ks == null) { 21543 return false; 21544 } 21545 synchronized(mPackages) { 21546 final PackageParser.Package pkg = mPackages.get(packageName); 21547 if (pkg == null) { 21548 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21549 throw new IllegalArgumentException("Unknown package: " + packageName); 21550 } 21551 IBinder ksh = ks.getToken(); 21552 if (ksh instanceof KeySetHandle) { 21553 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21554 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21555 } 21556 return false; 21557 } 21558 } 21559 21560 private void deletePackageIfUnusedLPr(final String packageName) { 21561 PackageSetting ps = mSettings.mPackages.get(packageName); 21562 if (ps == null) { 21563 return; 21564 } 21565 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21566 // TODO Implement atomic delete if package is unused 21567 // It is currently possible that the package will be deleted even if it is installed 21568 // after this method returns. 21569 mHandler.post(new Runnable() { 21570 public void run() { 21571 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21572 } 21573 }); 21574 } 21575 } 21576 21577 /** 21578 * Check and throw if the given before/after packages would be considered a 21579 * downgrade. 21580 */ 21581 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21582 throws PackageManagerException { 21583 if (after.versionCode < before.mVersionCode) { 21584 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21585 "Update version code " + after.versionCode + " is older than current " 21586 + before.mVersionCode); 21587 } else if (after.versionCode == before.mVersionCode) { 21588 if (after.baseRevisionCode < before.baseRevisionCode) { 21589 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21590 "Update base revision code " + after.baseRevisionCode 21591 + " is older than current " + before.baseRevisionCode); 21592 } 21593 21594 if (!ArrayUtils.isEmpty(after.splitNames)) { 21595 for (int i = 0; i < after.splitNames.length; i++) { 21596 final String splitName = after.splitNames[i]; 21597 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21598 if (j != -1) { 21599 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21600 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21601 "Update split " + splitName + " revision code " 21602 + after.splitRevisionCodes[i] + " is older than current " 21603 + before.splitRevisionCodes[j]); 21604 } 21605 } 21606 } 21607 } 21608 } 21609 } 21610 21611 private static class MoveCallbacks extends Handler { 21612 private static final int MSG_CREATED = 1; 21613 private static final int MSG_STATUS_CHANGED = 2; 21614 21615 private final RemoteCallbackList<IPackageMoveObserver> 21616 mCallbacks = new RemoteCallbackList<>(); 21617 21618 private final SparseIntArray mLastStatus = new SparseIntArray(); 21619 21620 public MoveCallbacks(Looper looper) { 21621 super(looper); 21622 } 21623 21624 public void register(IPackageMoveObserver callback) { 21625 mCallbacks.register(callback); 21626 } 21627 21628 public void unregister(IPackageMoveObserver callback) { 21629 mCallbacks.unregister(callback); 21630 } 21631 21632 @Override 21633 public void handleMessage(Message msg) { 21634 final SomeArgs args = (SomeArgs) msg.obj; 21635 final int n = mCallbacks.beginBroadcast(); 21636 for (int i = 0; i < n; i++) { 21637 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21638 try { 21639 invokeCallback(callback, msg.what, args); 21640 } catch (RemoteException ignored) { 21641 } 21642 } 21643 mCallbacks.finishBroadcast(); 21644 args.recycle(); 21645 } 21646 21647 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21648 throws RemoteException { 21649 switch (what) { 21650 case MSG_CREATED: { 21651 callback.onCreated(args.argi1, (Bundle) args.arg2); 21652 break; 21653 } 21654 case MSG_STATUS_CHANGED: { 21655 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21656 break; 21657 } 21658 } 21659 } 21660 21661 private void notifyCreated(int moveId, Bundle extras) { 21662 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21663 21664 final SomeArgs args = SomeArgs.obtain(); 21665 args.argi1 = moveId; 21666 args.arg2 = extras; 21667 obtainMessage(MSG_CREATED, args).sendToTarget(); 21668 } 21669 21670 private void notifyStatusChanged(int moveId, int status) { 21671 notifyStatusChanged(moveId, status, -1); 21672 } 21673 21674 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21675 Slog.v(TAG, "Move " + moveId + " status " + status); 21676 21677 final SomeArgs args = SomeArgs.obtain(); 21678 args.argi1 = moveId; 21679 args.argi2 = status; 21680 args.arg3 = estMillis; 21681 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21682 21683 synchronized (mLastStatus) { 21684 mLastStatus.put(moveId, status); 21685 } 21686 } 21687 } 21688 21689 private final static class OnPermissionChangeListeners extends Handler { 21690 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21691 21692 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21693 new RemoteCallbackList<>(); 21694 21695 public OnPermissionChangeListeners(Looper looper) { 21696 super(looper); 21697 } 21698 21699 @Override 21700 public void handleMessage(Message msg) { 21701 switch (msg.what) { 21702 case MSG_ON_PERMISSIONS_CHANGED: { 21703 final int uid = msg.arg1; 21704 handleOnPermissionsChanged(uid); 21705 } break; 21706 } 21707 } 21708 21709 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21710 mPermissionListeners.register(listener); 21711 21712 } 21713 21714 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21715 mPermissionListeners.unregister(listener); 21716 } 21717 21718 public void onPermissionsChanged(int uid) { 21719 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21720 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21721 } 21722 } 21723 21724 private void handleOnPermissionsChanged(int uid) { 21725 final int count = mPermissionListeners.beginBroadcast(); 21726 try { 21727 for (int i = 0; i < count; i++) { 21728 IOnPermissionsChangeListener callback = mPermissionListeners 21729 .getBroadcastItem(i); 21730 try { 21731 callback.onPermissionsChanged(uid); 21732 } catch (RemoteException e) { 21733 Log.e(TAG, "Permission listener is dead", e); 21734 } 21735 } 21736 } finally { 21737 mPermissionListeners.finishBroadcast(); 21738 } 21739 } 21740 } 21741 21742 private class PackageManagerInternalImpl extends PackageManagerInternal { 21743 @Override 21744 public void setLocationPackagesProvider(PackagesProvider provider) { 21745 synchronized (mPackages) { 21746 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21747 } 21748 } 21749 21750 @Override 21751 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21752 synchronized (mPackages) { 21753 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21754 } 21755 } 21756 21757 @Override 21758 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21759 synchronized (mPackages) { 21760 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21761 } 21762 } 21763 21764 @Override 21765 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21766 synchronized (mPackages) { 21767 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21768 } 21769 } 21770 21771 @Override 21772 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21773 synchronized (mPackages) { 21774 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21775 } 21776 } 21777 21778 @Override 21779 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21780 synchronized (mPackages) { 21781 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21782 } 21783 } 21784 21785 @Override 21786 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21787 synchronized (mPackages) { 21788 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21789 packageName, userId); 21790 } 21791 } 21792 21793 @Override 21794 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21795 synchronized (mPackages) { 21796 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21797 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21798 packageName, userId); 21799 } 21800 } 21801 21802 @Override 21803 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21804 synchronized (mPackages) { 21805 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21806 packageName, userId); 21807 } 21808 } 21809 21810 @Override 21811 public void setKeepUninstalledPackages(final List<String> packageList) { 21812 Preconditions.checkNotNull(packageList); 21813 List<String> removedFromList = null; 21814 synchronized (mPackages) { 21815 if (mKeepUninstalledPackages != null) { 21816 final int packagesCount = mKeepUninstalledPackages.size(); 21817 for (int i = 0; i < packagesCount; i++) { 21818 String oldPackage = mKeepUninstalledPackages.get(i); 21819 if (packageList != null && packageList.contains(oldPackage)) { 21820 continue; 21821 } 21822 if (removedFromList == null) { 21823 removedFromList = new ArrayList<>(); 21824 } 21825 removedFromList.add(oldPackage); 21826 } 21827 } 21828 mKeepUninstalledPackages = new ArrayList<>(packageList); 21829 if (removedFromList != null) { 21830 final int removedCount = removedFromList.size(); 21831 for (int i = 0; i < removedCount; i++) { 21832 deletePackageIfUnusedLPr(removedFromList.get(i)); 21833 } 21834 } 21835 } 21836 } 21837 21838 @Override 21839 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21840 synchronized (mPackages) { 21841 // If we do not support permission review, done. 21842 if (!mPermissionReviewRequired) { 21843 return false; 21844 } 21845 21846 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21847 if (packageSetting == null) { 21848 return false; 21849 } 21850 21851 // Permission review applies only to apps not supporting the new permission model. 21852 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21853 return false; 21854 } 21855 21856 // Legacy apps have the permission and get user consent on launch. 21857 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21858 return permissionsState.isPermissionReviewRequired(userId); 21859 } 21860 } 21861 21862 @Override 21863 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21864 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21865 } 21866 21867 @Override 21868 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21869 int userId) { 21870 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21871 } 21872 21873 @Override 21874 public void setDeviceAndProfileOwnerPackages( 21875 int deviceOwnerUserId, String deviceOwnerPackage, 21876 SparseArray<String> profileOwnerPackages) { 21877 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21878 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21879 } 21880 21881 @Override 21882 public boolean isPackageDataProtected(int userId, String packageName) { 21883 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21884 } 21885 21886 @Override 21887 public boolean isPackageEphemeral(int userId, String packageName) { 21888 synchronized (mPackages) { 21889 PackageParser.Package p = mPackages.get(packageName); 21890 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21891 } 21892 } 21893 21894 @Override 21895 public boolean wasPackageEverLaunched(String packageName, int userId) { 21896 synchronized (mPackages) { 21897 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21898 } 21899 } 21900 21901 @Override 21902 public void grantRuntimePermission(String packageName, String name, int userId, 21903 boolean overridePolicy) { 21904 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21905 overridePolicy); 21906 } 21907 21908 @Override 21909 public void revokeRuntimePermission(String packageName, String name, int userId, 21910 boolean overridePolicy) { 21911 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21912 overridePolicy); 21913 } 21914 21915 @Override 21916 public String getNameForUid(int uid) { 21917 return PackageManagerService.this.getNameForUid(uid); 21918 } 21919 21920 @Override 21921 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21922 Intent origIntent, String resolvedType, Intent launchIntent, 21923 String callingPackage, int userId) { 21924 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21925 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21926 } 21927 21928 public String getSetupWizardPackageName() { 21929 return mSetupWizardPackage; 21930 } 21931 } 21932 21933 @Override 21934 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21935 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21936 synchronized (mPackages) { 21937 final long identity = Binder.clearCallingIdentity(); 21938 try { 21939 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21940 packageNames, userId); 21941 } finally { 21942 Binder.restoreCallingIdentity(identity); 21943 } 21944 } 21945 } 21946 21947 private static void enforceSystemOrPhoneCaller(String tag) { 21948 int callingUid = Binder.getCallingUid(); 21949 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21950 throw new SecurityException( 21951 "Cannot call " + tag + " from UID " + callingUid); 21952 } 21953 } 21954 21955 boolean isHistoricalPackageUsageAvailable() { 21956 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21957 } 21958 21959 /** 21960 * Return a <b>copy</b> of the collection of packages known to the package manager. 21961 * @return A copy of the values of mPackages. 21962 */ 21963 Collection<PackageParser.Package> getPackages() { 21964 synchronized (mPackages) { 21965 return new ArrayList<>(mPackages.values()); 21966 } 21967 } 21968 21969 /** 21970 * Logs process start information (including base APK hash) to the security log. 21971 * @hide 21972 */ 21973 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21974 String apkFile, int pid) { 21975 if (!SecurityLog.isLoggingEnabled()) { 21976 return; 21977 } 21978 Bundle data = new Bundle(); 21979 data.putLong("startTimestamp", System.currentTimeMillis()); 21980 data.putString("processName", processName); 21981 data.putInt("uid", uid); 21982 data.putString("seinfo", seinfo); 21983 data.putString("apkFile", apkFile); 21984 data.putInt("pid", pid); 21985 Message msg = mProcessLoggingHandler.obtainMessage( 21986 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21987 msg.setData(data); 21988 mProcessLoggingHandler.sendMessage(msg); 21989 } 21990 21991 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21992 return mCompilerStats.getPackageStats(pkgName); 21993 } 21994 21995 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21996 return getOrCreateCompilerPackageStats(pkg.packageName); 21997 } 21998 21999 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 22000 return mCompilerStats.getOrCreatePackageStats(pkgName); 22001 } 22002 22003 public void deleteCompilerPackageStats(String pkgName) { 22004 mCompilerStats.deletePackageStats(pkgName); 22005 } 22006 22007 @Override 22008 public int getInstallReason(String packageName, int userId) { 22009 enforceCrossUserPermission(Binder.getCallingUid(), userId, 22010 true /* requireFullPermission */, false /* checkShell */, 22011 "get install reason"); 22012 synchronized (mPackages) { 22013 final PackageSetting ps = mSettings.mPackages.get(packageName); 22014 if (ps != null) { 22015 return ps.getInstallReason(userId); 22016 } 22017 } 22018 return PackageManager.INSTALL_REASON_UNKNOWN; 22019 } 22020} 22021