PackageManagerService.java revision 21a2838e3474c7b7918ca638be70aa1c27649117
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_ANY_USER; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 69import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 70import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 71import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 72import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 73import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 74import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 75import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 76import static android.content.pm.PackageManager.PERMISSION_DENIED; 77import static android.content.pm.PackageManager.PERMISSION_GRANTED; 78import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 79import static android.content.pm.PackageParser.isApkFile; 80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 81import static android.system.OsConstants.O_CREAT; 82import static android.system.OsConstants.O_RDWR; 83 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 88import static com.android.internal.util.ArrayUtils.appendInt; 89import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.AppOpsManager; 107import android.app.IActivityManager; 108import android.app.ResourcesManager; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.ContentResolver; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralRequest; 128import android.content.pm.EphemeralResolveInfo; 129import android.content.pm.EphemeralResponse; 130import android.content.pm.FallbackCategoryProvider; 131import android.content.pm.FeatureInfo; 132import android.content.pm.IOnPermissionsChangeListener; 133import android.content.pm.IPackageDataObserver; 134import android.content.pm.IPackageDeleteObserver; 135import android.content.pm.IPackageDeleteObserver2; 136import android.content.pm.IPackageInstallObserver2; 137import android.content.pm.IPackageInstaller; 138import android.content.pm.IPackageManager; 139import android.content.pm.IPackageMoveObserver; 140import android.content.pm.IPackageStatsObserver; 141import android.content.pm.InstrumentationInfo; 142import android.content.pm.IntentFilterVerificationInfo; 143import android.content.pm.KeySet; 144import android.content.pm.PackageCleanItem; 145import android.content.pm.PackageInfo; 146import android.content.pm.PackageInfoLite; 147import android.content.pm.PackageInstaller; 148import android.content.pm.PackageManager; 149import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 150import android.content.pm.PackageManagerInternal; 151import android.content.pm.PackageParser; 152import android.content.pm.PackageParser.ActivityIntentInfo; 153import android.content.pm.PackageParser.PackageLite; 154import android.content.pm.PackageParser.PackageParserException; 155import android.content.pm.PackageStats; 156import android.content.pm.PackageUserState; 157import android.content.pm.ParceledListSlice; 158import android.content.pm.PermissionGroupInfo; 159import android.content.pm.PermissionInfo; 160import android.content.pm.ProviderInfo; 161import android.content.pm.ResolveInfo; 162import android.content.pm.ServiceInfo; 163import android.content.pm.Signature; 164import android.content.pm.UserInfo; 165import android.content.pm.VerifierDeviceIdentity; 166import android.content.pm.VerifierInfo; 167import android.content.res.Resources; 168import android.graphics.Bitmap; 169import android.hardware.display.DisplayManager; 170import android.net.Uri; 171import android.os.Binder; 172import android.os.Build; 173import android.os.Bundle; 174import android.os.Debug; 175import android.os.Environment; 176import android.os.Environment.UserEnvironment; 177import android.os.FileUtils; 178import android.os.Handler; 179import android.os.IBinder; 180import android.os.Looper; 181import android.os.Message; 182import android.os.Parcel; 183import android.os.ParcelFileDescriptor; 184import android.os.PatternMatcher; 185import android.os.Process; 186import android.os.RemoteCallbackList; 187import android.os.RemoteException; 188import android.os.ResultReceiver; 189import android.os.SELinux; 190import android.os.ServiceManager; 191import android.os.ShellCallback; 192import android.os.SystemClock; 193import android.os.SystemProperties; 194import android.os.Trace; 195import android.os.UserHandle; 196import android.os.UserManager; 197import android.os.UserManagerInternal; 198import android.os.storage.IStorageManager; 199import android.os.storage.StorageManagerInternal; 200import android.os.storage.StorageEventListener; 201import android.os.storage.StorageManager; 202import android.os.storage.VolumeInfo; 203import android.os.storage.VolumeRecord; 204import android.provider.Settings.Global; 205import android.provider.Settings.Secure; 206import android.security.KeyStore; 207import android.security.SystemKeyStore; 208import android.system.ErrnoException; 209import android.system.Os; 210import android.text.TextUtils; 211import android.text.format.DateUtils; 212import android.util.ArrayMap; 213import android.util.ArraySet; 214import android.util.Base64; 215import android.util.DisplayMetrics; 216import android.util.EventLog; 217import android.util.ExceptionUtils; 218import android.util.Log; 219import android.util.LogPrinter; 220import android.util.MathUtils; 221import android.util.Pair; 222import android.util.PrintStreamPrinter; 223import android.util.Slog; 224import android.util.SparseArray; 225import android.util.SparseBooleanArray; 226import android.util.SparseIntArray; 227import android.util.Xml; 228import android.util.jar.StrictJarFile; 229import android.view.Display; 230 231import com.android.internal.R; 232import com.android.internal.annotations.GuardedBy; 233import com.android.internal.app.IMediaContainerService; 234import com.android.internal.app.ResolverActivity; 235import com.android.internal.content.NativeLibraryHelper; 236import com.android.internal.content.PackageHelper; 237import com.android.internal.logging.MetricsLogger; 238import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 239import com.android.internal.os.IParcelFileDescriptorFactory; 240import com.android.internal.os.RoSystemProperties; 241import com.android.internal.os.SomeArgs; 242import com.android.internal.os.Zygote; 243import com.android.internal.telephony.CarrierAppUtils; 244import com.android.internal.util.ArrayUtils; 245import com.android.internal.util.FastPrintWriter; 246import com.android.internal.util.FastXmlSerializer; 247import com.android.internal.util.IndentingPrintWriter; 248import com.android.internal.util.Preconditions; 249import com.android.internal.util.XmlUtils; 250import com.android.server.AttributeCache; 251import com.android.server.EventLogTags; 252import com.android.server.FgThread; 253import com.android.server.IntentResolver; 254import com.android.server.LocalServices; 255import com.android.server.ServiceThread; 256import com.android.server.SystemConfig; 257import com.android.server.Watchdog; 258import com.android.server.net.NetworkPolicyManagerInternal; 259import com.android.server.pm.Installer.InstallerException; 260import com.android.server.pm.PermissionsState.PermissionState; 261import com.android.server.pm.Settings.DatabaseVersion; 262import com.android.server.pm.Settings.VersionInfo; 263import com.android.server.pm.dex.DexManager; 264import com.android.server.storage.DeviceStorageMonitorInternal; 265 266import dalvik.system.CloseGuard; 267import dalvik.system.DexFile; 268import dalvik.system.VMRuntime; 269 270import libcore.io.IoUtils; 271import libcore.util.EmptyArray; 272 273import org.xmlpull.v1.XmlPullParser; 274import org.xmlpull.v1.XmlPullParserException; 275import org.xmlpull.v1.XmlSerializer; 276 277import java.io.BufferedOutputStream; 278import java.io.BufferedReader; 279import java.io.ByteArrayInputStream; 280import java.io.ByteArrayOutputStream; 281import java.io.File; 282import java.io.FileDescriptor; 283import java.io.FileInputStream; 284import java.io.FileNotFoundException; 285import java.io.FileOutputStream; 286import java.io.FileReader; 287import java.io.FilenameFilter; 288import java.io.IOException; 289import java.io.PrintWriter; 290import java.nio.charset.StandardCharsets; 291import java.security.DigestInputStream; 292import java.security.MessageDigest; 293import java.security.NoSuchAlgorithmException; 294import java.security.PublicKey; 295import java.security.SecureRandom; 296import java.security.cert.Certificate; 297import java.security.cert.CertificateEncodingException; 298import java.security.cert.CertificateException; 299import java.text.SimpleDateFormat; 300import java.util.ArrayList; 301import java.util.Arrays; 302import java.util.Collection; 303import java.util.Collections; 304import java.util.Comparator; 305import java.util.Date; 306import java.util.HashSet; 307import java.util.HashMap; 308import java.util.Iterator; 309import java.util.List; 310import java.util.Map; 311import java.util.Objects; 312import java.util.Set; 313import java.util.concurrent.CountDownLatch; 314import java.util.concurrent.TimeUnit; 315import java.util.concurrent.atomic.AtomicBoolean; 316import java.util.concurrent.atomic.AtomicInteger; 317 318/** 319 * Keep track of all those APKs everywhere. 320 * <p> 321 * Internally there are two important locks: 322 * <ul> 323 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 324 * and other related state. It is a fine-grained lock that should only be held 325 * momentarily, as it's one of the most contended locks in the system. 326 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 327 * operations typically involve heavy lifting of application data on disk. Since 328 * {@code installd} is single-threaded, and it's operations can often be slow, 329 * this lock should never be acquired while already holding {@link #mPackages}. 330 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 331 * holding {@link #mInstallLock}. 332 * </ul> 333 * Many internal methods rely on the caller to hold the appropriate locks, and 334 * this contract is expressed through method name suffixes: 335 * <ul> 336 * <li>fooLI(): the caller must hold {@link #mInstallLock} 337 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 338 * being modified must be frozen 339 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 340 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 341 * </ul> 342 * <p> 343 * Because this class is very central to the platform's security; please run all 344 * CTS and unit tests whenever making modifications: 345 * 346 * <pre> 347 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 348 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 349 * </pre> 350 */ 351public class PackageManagerService extends IPackageManager.Stub { 352 static final String TAG = "PackageManager"; 353 static final boolean DEBUG_SETTINGS = false; 354 static final boolean DEBUG_PREFERRED = false; 355 static final boolean DEBUG_UPGRADE = false; 356 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 357 private static final boolean DEBUG_BACKUP = false; 358 private static final boolean DEBUG_INSTALL = false; 359 private static final boolean DEBUG_REMOVE = false; 360 private static final boolean DEBUG_BROADCASTS = false; 361 private static final boolean DEBUG_SHOW_INFO = false; 362 private static final boolean DEBUG_PACKAGE_INFO = false; 363 private static final boolean DEBUG_INTENT_MATCHING = false; 364 private static final boolean DEBUG_PACKAGE_SCANNING = false; 365 private static final boolean DEBUG_VERIFY = false; 366 private static final boolean DEBUG_FILTERS = false; 367 368 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 369 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 370 // user, but by default initialize to this. 371 static final boolean DEBUG_DEXOPT = false; 372 373 private static final boolean DEBUG_ABI_SELECTION = false; 374 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 375 private static final boolean DEBUG_TRIAGED_MISSING = false; 376 private static final boolean DEBUG_APP_DATA = false; 377 378 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 379 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 380 381 private static final boolean DISABLE_EPHEMERAL_APPS = false; 382 private static final boolean HIDE_EPHEMERAL_APIS = true; 383 384 private static final boolean ENABLE_QUOTA = 385 SystemProperties.getBoolean("persist.fw.quota", false); 386 387 private static final int RADIO_UID = Process.PHONE_UID; 388 private static final int LOG_UID = Process.LOG_UID; 389 private static final int NFC_UID = Process.NFC_UID; 390 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 391 private static final int SHELL_UID = Process.SHELL_UID; 392 393 // Cap the size of permission trees that 3rd party apps can define 394 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 395 396 // Suffix used during package installation when copying/moving 397 // package apks to install directory. 398 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 399 400 static final int SCAN_NO_DEX = 1<<1; 401 static final int SCAN_FORCE_DEX = 1<<2; 402 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 403 static final int SCAN_NEW_INSTALL = 1<<4; 404 static final int SCAN_UPDATE_TIME = 1<<5; 405 static final int SCAN_BOOTING = 1<<6; 406 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 407 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 408 static final int SCAN_REPLACING = 1<<9; 409 static final int SCAN_REQUIRE_KNOWN = 1<<10; 410 static final int SCAN_MOVE = 1<<11; 411 static final int SCAN_INITIAL = 1<<12; 412 static final int SCAN_CHECK_ONLY = 1<<13; 413 static final int SCAN_DONT_KILL_APP = 1<<14; 414 static final int SCAN_IGNORE_FROZEN = 1<<15; 415 static final int REMOVE_CHATTY = 1<<16; 416 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 417 418 private static final int[] EMPTY_INT_ARRAY = new int[0]; 419 420 /** 421 * Timeout (in milliseconds) after which the watchdog should declare that 422 * our handler thread is wedged. The usual default for such things is one 423 * minute but we sometimes do very lengthy I/O operations on this thread, 424 * such as installing multi-gigabyte applications, so ours needs to be longer. 425 */ 426 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 427 428 /** 429 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 430 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 431 * settings entry if available, otherwise we use the hardcoded default. If it's been 432 * more than this long since the last fstrim, we force one during the boot sequence. 433 * 434 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 435 * one gets run at the next available charging+idle time. This final mandatory 436 * no-fstrim check kicks in only of the other scheduling criteria is never met. 437 */ 438 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 439 440 /** 441 * Whether verification is enabled by default. 442 */ 443 private static final boolean DEFAULT_VERIFY_ENABLE = true; 444 445 /** 446 * The default maximum time to wait for the verification agent to return in 447 * milliseconds. 448 */ 449 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 450 451 /** 452 * The default response for package verification timeout. 453 * 454 * This can be either PackageManager.VERIFICATION_ALLOW or 455 * PackageManager.VERIFICATION_REJECT. 456 */ 457 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 458 459 static final String PLATFORM_PACKAGE_NAME = "android"; 460 461 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 462 463 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 464 DEFAULT_CONTAINER_PACKAGE, 465 "com.android.defcontainer.DefaultContainerService"); 466 467 private static final String KILL_APP_REASON_GIDS_CHANGED = 468 "permission grant or revoke changed gids"; 469 470 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 471 "permissions revoked"; 472 473 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 474 475 private static final String PACKAGE_SCHEME = "package"; 476 477 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 478 /** 479 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 480 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 481 * VENDOR_OVERLAY_DIR. 482 */ 483 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 484 /** 485 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 486 * is in VENDOR_OVERLAY_THEME_PROPERTY. 487 */ 488 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 489 = "persist.vendor.overlay.theme"; 490 491 /** Permission grant: not grant the permission. */ 492 private static final int GRANT_DENIED = 1; 493 494 /** Permission grant: grant the permission as an install permission. */ 495 private static final int GRANT_INSTALL = 2; 496 497 /** Permission grant: grant the permission as a runtime one. */ 498 private static final int GRANT_RUNTIME = 3; 499 500 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 501 private static final int GRANT_UPGRADE = 4; 502 503 /** Canonical intent used to identify what counts as a "web browser" app */ 504 private static final Intent sBrowserIntent; 505 static { 506 sBrowserIntent = new Intent(); 507 sBrowserIntent.setAction(Intent.ACTION_VIEW); 508 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 509 sBrowserIntent.setData(Uri.parse("http:")); 510 } 511 512 /** 513 * The set of all protected actions [i.e. those actions for which a high priority 514 * intent filter is disallowed]. 515 */ 516 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 517 static { 518 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 519 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 520 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 521 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 522 } 523 524 // Compilation reasons. 525 public static final int REASON_FIRST_BOOT = 0; 526 public static final int REASON_BOOT = 1; 527 public static final int REASON_INSTALL = 2; 528 public static final int REASON_BACKGROUND_DEXOPT = 3; 529 public static final int REASON_AB_OTA = 4; 530 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 531 public static final int REASON_SHARED_APK = 6; 532 public static final int REASON_FORCED_DEXOPT = 7; 533 public static final int REASON_CORE_APP = 8; 534 535 public static final int REASON_LAST = REASON_CORE_APP; 536 537 /** Special library name that skips shared libraries check during compilation. */ 538 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 539 540 /** All dangerous permission names in the same order as the events in MetricsEvent */ 541 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 542 Manifest.permission.READ_CALENDAR, 543 Manifest.permission.WRITE_CALENDAR, 544 Manifest.permission.CAMERA, 545 Manifest.permission.READ_CONTACTS, 546 Manifest.permission.WRITE_CONTACTS, 547 Manifest.permission.GET_ACCOUNTS, 548 Manifest.permission.ACCESS_FINE_LOCATION, 549 Manifest.permission.ACCESS_COARSE_LOCATION, 550 Manifest.permission.RECORD_AUDIO, 551 Manifest.permission.READ_PHONE_STATE, 552 Manifest.permission.CALL_PHONE, 553 Manifest.permission.READ_CALL_LOG, 554 Manifest.permission.WRITE_CALL_LOG, 555 Manifest.permission.ADD_VOICEMAIL, 556 Manifest.permission.USE_SIP, 557 Manifest.permission.PROCESS_OUTGOING_CALLS, 558 Manifest.permission.READ_CELL_BROADCASTS, 559 Manifest.permission.BODY_SENSORS, 560 Manifest.permission.SEND_SMS, 561 Manifest.permission.RECEIVE_SMS, 562 Manifest.permission.READ_SMS, 563 Manifest.permission.RECEIVE_WAP_PUSH, 564 Manifest.permission.RECEIVE_MMS, 565 Manifest.permission.READ_EXTERNAL_STORAGE, 566 Manifest.permission.WRITE_EXTERNAL_STORAGE, 567 Manifest.permission.READ_PHONE_NUMBER); 568 569 570 /** 571 * Version number for the package parser cache. Increment this whenever the format or 572 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 573 */ 574 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 575 576 /** 577 * Whether the package parser cache is enabled. 578 */ 579 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 580 581 final ServiceThread mHandlerThread; 582 583 final PackageHandler mHandler; 584 585 private final ProcessLoggingHandler mProcessLoggingHandler; 586 587 /** 588 * Messages for {@link #mHandler} that need to wait for system ready before 589 * being dispatched. 590 */ 591 private ArrayList<Message> mPostSystemReadyMessages; 592 593 final int mSdkVersion = Build.VERSION.SDK_INT; 594 595 final Context mContext; 596 final boolean mFactoryTest; 597 final boolean mOnlyCore; 598 final DisplayMetrics mMetrics; 599 final int mDefParseFlags; 600 final String[] mSeparateProcesses; 601 final boolean mIsUpgrade; 602 final boolean mIsPreNUpgrade; 603 final boolean mIsPreNMR1Upgrade; 604 605 @GuardedBy("mPackages") 606 private boolean mDexOptDialogShown; 607 608 /** The location for ASEC container files on internal storage. */ 609 final String mAsecInternalPath; 610 611 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 612 // LOCK HELD. Can be called with mInstallLock held. 613 @GuardedBy("mInstallLock") 614 final Installer mInstaller; 615 616 /** Directory where installed third-party apps stored */ 617 final File mAppInstallDir; 618 final File mEphemeralInstallDir; 619 620 /** 621 * Directory to which applications installed internally have their 622 * 32 bit native libraries copied. 623 */ 624 private File mAppLib32InstallDir; 625 626 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 627 // apps. 628 final File mDrmAppPrivateInstallDir; 629 630 // ---------------------------------------------------------------- 631 632 // Lock for state used when installing and doing other long running 633 // operations. Methods that must be called with this lock held have 634 // the suffix "LI". 635 final Object mInstallLock = new Object(); 636 637 // ---------------------------------------------------------------- 638 639 // Keys are String (package name), values are Package. This also serves 640 // as the lock for the global state. Methods that must be called with 641 // this lock held have the prefix "LP". 642 @GuardedBy("mPackages") 643 final ArrayMap<String, PackageParser.Package> mPackages = 644 new ArrayMap<String, PackageParser.Package>(); 645 646 final ArrayMap<String, Set<String>> mKnownCodebase = 647 new ArrayMap<String, Set<String>>(); 648 649 // Tracks available target package names -> overlay package paths. 650 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 651 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 652 653 /** 654 * Tracks new system packages [received in an OTA] that we expect to 655 * find updated user-installed versions. Keys are package name, values 656 * are package location. 657 */ 658 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 659 /** 660 * Tracks high priority intent filters for protected actions. During boot, certain 661 * filter actions are protected and should never be allowed to have a high priority 662 * intent filter for them. However, there is one, and only one exception -- the 663 * setup wizard. It must be able to define a high priority intent filter for these 664 * actions to ensure there are no escapes from the wizard. We need to delay processing 665 * of these during boot as we need to look at all of the system packages in order 666 * to know which component is the setup wizard. 667 */ 668 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 669 /** 670 * Whether or not processing protected filters should be deferred. 671 */ 672 private boolean mDeferProtectedFilters = true; 673 674 /** 675 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 676 */ 677 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 678 /** 679 * Whether or not system app permissions should be promoted from install to runtime. 680 */ 681 boolean mPromoteSystemApps; 682 683 @GuardedBy("mPackages") 684 final Settings mSettings; 685 686 /** 687 * Set of package names that are currently "frozen", which means active 688 * surgery is being done on the code/data for that package. The platform 689 * will refuse to launch frozen packages to avoid race conditions. 690 * 691 * @see PackageFreezer 692 */ 693 @GuardedBy("mPackages") 694 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 695 696 final ProtectedPackages mProtectedPackages; 697 698 boolean mFirstBoot; 699 700 // System configuration read by SystemConfig. 701 final int[] mGlobalGids; 702 final SparseArray<ArraySet<String>> mSystemPermissions; 703 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 704 705 // If mac_permissions.xml was found for seinfo labeling. 706 boolean mFoundPolicyFile; 707 708 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 709 710 public static final class SharedLibraryEntry { 711 public final String path; 712 public final String apk; 713 714 SharedLibraryEntry(String _path, String _apk) { 715 path = _path; 716 apk = _apk; 717 } 718 } 719 720 // Currently known shared libraries. 721 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 722 new ArrayMap<String, SharedLibraryEntry>(); 723 724 // All available activities, for your resolving pleasure. 725 final ActivityIntentResolver mActivities = 726 new ActivityIntentResolver(); 727 728 // All available receivers, for your resolving pleasure. 729 final ActivityIntentResolver mReceivers = 730 new ActivityIntentResolver(); 731 732 // All available services, for your resolving pleasure. 733 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 734 735 // All available providers, for your resolving pleasure. 736 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 737 738 // Mapping from provider base names (first directory in content URI codePath) 739 // to the provider information. 740 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 741 new ArrayMap<String, PackageParser.Provider>(); 742 743 // Mapping from instrumentation class names to info about them. 744 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 745 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 746 747 // Mapping from permission names to info about them. 748 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 749 new ArrayMap<String, PackageParser.PermissionGroup>(); 750 751 // Packages whose data we have transfered into another package, thus 752 // should no longer exist. 753 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 754 755 // Broadcast actions that are only available to the system. 756 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 757 758 /** List of packages waiting for verification. */ 759 final SparseArray<PackageVerificationState> mPendingVerification 760 = new SparseArray<PackageVerificationState>(); 761 762 /** Set of packages associated with each app op permission. */ 763 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 764 765 final PackageInstallerService mInstallerService; 766 767 private final PackageDexOptimizer mPackageDexOptimizer; 768 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 769 // is used by other apps). 770 private final DexManager mDexManager; 771 772 private AtomicInteger mNextMoveId = new AtomicInteger(); 773 private final MoveCallbacks mMoveCallbacks; 774 775 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 776 777 // Cache of users who need badging. 778 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 779 780 /** Token for keys in mPendingVerification. */ 781 private int mPendingVerificationToken = 0; 782 783 volatile boolean mSystemReady; 784 volatile boolean mSafeMode; 785 volatile boolean mHasSystemUidErrors; 786 787 ApplicationInfo mAndroidApplication; 788 final ActivityInfo mResolveActivity = new ActivityInfo(); 789 final ResolveInfo mResolveInfo = new ResolveInfo(); 790 ComponentName mResolveComponentName; 791 PackageParser.Package mPlatformPackage; 792 ComponentName mCustomResolverComponentName; 793 794 boolean mResolverReplaced = false; 795 796 private final @Nullable ComponentName mIntentFilterVerifierComponent; 797 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 798 799 private int mIntentFilterVerificationToken = 0; 800 801 /** The service connection to the ephemeral resolver */ 802 final EphemeralResolverConnection mEphemeralResolverConnection; 803 804 /** Component used to install ephemeral applications */ 805 ComponentName mEphemeralInstallerComponent; 806 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 807 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 808 809 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 810 = new SparseArray<IntentFilterVerificationState>(); 811 812 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 813 814 // List of packages names to keep cached, even if they are uninstalled for all users 815 private List<String> mKeepUninstalledPackages; 816 817 private UserManagerInternal mUserManagerInternal; 818 819 private File mCacheDir; 820 821 private static class IFVerificationParams { 822 PackageParser.Package pkg; 823 boolean replacing; 824 int userId; 825 int verifierUid; 826 827 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 828 int _userId, int _verifierUid) { 829 pkg = _pkg; 830 replacing = _replacing; 831 userId = _userId; 832 replacing = _replacing; 833 verifierUid = _verifierUid; 834 } 835 } 836 837 private interface IntentFilterVerifier<T extends IntentFilter> { 838 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 839 T filter, String packageName); 840 void startVerifications(int userId); 841 void receiveVerificationResponse(int verificationId); 842 } 843 844 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 845 private Context mContext; 846 private ComponentName mIntentFilterVerifierComponent; 847 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 848 849 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 850 mContext = context; 851 mIntentFilterVerifierComponent = verifierComponent; 852 } 853 854 private String getDefaultScheme() { 855 return IntentFilter.SCHEME_HTTPS; 856 } 857 858 @Override 859 public void startVerifications(int userId) { 860 // Launch verifications requests 861 int count = mCurrentIntentFilterVerifications.size(); 862 for (int n=0; n<count; n++) { 863 int verificationId = mCurrentIntentFilterVerifications.get(n); 864 final IntentFilterVerificationState ivs = 865 mIntentFilterVerificationStates.get(verificationId); 866 867 String packageName = ivs.getPackageName(); 868 869 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 870 final int filterCount = filters.size(); 871 ArraySet<String> domainsSet = new ArraySet<>(); 872 for (int m=0; m<filterCount; m++) { 873 PackageParser.ActivityIntentInfo filter = filters.get(m); 874 domainsSet.addAll(filter.getHostsList()); 875 } 876 synchronized (mPackages) { 877 if (mSettings.createIntentFilterVerificationIfNeededLPw( 878 packageName, domainsSet) != null) { 879 scheduleWriteSettingsLocked(); 880 } 881 } 882 sendVerificationRequest(userId, verificationId, ivs); 883 } 884 mCurrentIntentFilterVerifications.clear(); 885 } 886 887 private void sendVerificationRequest(int userId, int verificationId, 888 IntentFilterVerificationState ivs) { 889 890 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 891 verificationIntent.putExtra( 892 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 893 verificationId); 894 verificationIntent.putExtra( 895 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 896 getDefaultScheme()); 897 verificationIntent.putExtra( 898 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 899 ivs.getHostsString()); 900 verificationIntent.putExtra( 901 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 902 ivs.getPackageName()); 903 verificationIntent.setComponent(mIntentFilterVerifierComponent); 904 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 905 906 UserHandle user = new UserHandle(userId); 907 mContext.sendBroadcastAsUser(verificationIntent, user); 908 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 909 "Sending IntentFilter verification broadcast"); 910 } 911 912 public void receiveVerificationResponse(int verificationId) { 913 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 914 915 final boolean verified = ivs.isVerified(); 916 917 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 918 final int count = filters.size(); 919 if (DEBUG_DOMAIN_VERIFICATION) { 920 Slog.i(TAG, "Received verification response " + verificationId 921 + " for " + count + " filters, verified=" + verified); 922 } 923 for (int n=0; n<count; n++) { 924 PackageParser.ActivityIntentInfo filter = filters.get(n); 925 filter.setVerified(verified); 926 927 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 928 + " verified with result:" + verified + " and hosts:" 929 + ivs.getHostsString()); 930 } 931 932 mIntentFilterVerificationStates.remove(verificationId); 933 934 final String packageName = ivs.getPackageName(); 935 IntentFilterVerificationInfo ivi = null; 936 937 synchronized (mPackages) { 938 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 939 } 940 if (ivi == null) { 941 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 942 + verificationId + " packageName:" + packageName); 943 return; 944 } 945 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 946 "Updating IntentFilterVerificationInfo for package " + packageName 947 +" verificationId:" + verificationId); 948 949 synchronized (mPackages) { 950 if (verified) { 951 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 952 } else { 953 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 954 } 955 scheduleWriteSettingsLocked(); 956 957 final int userId = ivs.getUserId(); 958 if (userId != UserHandle.USER_ALL) { 959 final int userStatus = 960 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 961 962 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 963 boolean needUpdate = false; 964 965 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 966 // already been set by the User thru the Disambiguation dialog 967 switch (userStatus) { 968 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 969 if (verified) { 970 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 971 } else { 972 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 973 } 974 needUpdate = true; 975 break; 976 977 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 978 if (verified) { 979 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 980 needUpdate = true; 981 } 982 break; 983 984 default: 985 // Nothing to do 986 } 987 988 if (needUpdate) { 989 mSettings.updateIntentFilterVerificationStatusLPw( 990 packageName, updatedStatus, userId); 991 scheduleWritePackageRestrictionsLocked(userId); 992 } 993 } 994 } 995 } 996 997 @Override 998 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 999 ActivityIntentInfo filter, String packageName) { 1000 if (!hasValidDomains(filter)) { 1001 return false; 1002 } 1003 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1004 if (ivs == null) { 1005 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1006 packageName); 1007 } 1008 if (DEBUG_DOMAIN_VERIFICATION) { 1009 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1010 } 1011 ivs.addFilter(filter); 1012 return true; 1013 } 1014 1015 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1016 int userId, int verificationId, String packageName) { 1017 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1018 verifierUid, userId, packageName); 1019 ivs.setPendingState(); 1020 synchronized (mPackages) { 1021 mIntentFilterVerificationStates.append(verificationId, ivs); 1022 mCurrentIntentFilterVerifications.add(verificationId); 1023 } 1024 return ivs; 1025 } 1026 } 1027 1028 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1029 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1030 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1031 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1032 } 1033 1034 // Set of pending broadcasts for aggregating enable/disable of components. 1035 static class PendingPackageBroadcasts { 1036 // for each user id, a map of <package name -> components within that package> 1037 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1038 1039 public PendingPackageBroadcasts() { 1040 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1041 } 1042 1043 public ArrayList<String> get(int userId, String packageName) { 1044 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1045 return packages.get(packageName); 1046 } 1047 1048 public void put(int userId, String packageName, ArrayList<String> components) { 1049 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1050 packages.put(packageName, components); 1051 } 1052 1053 public void remove(int userId, String packageName) { 1054 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1055 if (packages != null) { 1056 packages.remove(packageName); 1057 } 1058 } 1059 1060 public void remove(int userId) { 1061 mUidMap.remove(userId); 1062 } 1063 1064 public int userIdCount() { 1065 return mUidMap.size(); 1066 } 1067 1068 public int userIdAt(int n) { 1069 return mUidMap.keyAt(n); 1070 } 1071 1072 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1073 return mUidMap.get(userId); 1074 } 1075 1076 public int size() { 1077 // total number of pending broadcast entries across all userIds 1078 int num = 0; 1079 for (int i = 0; i< mUidMap.size(); i++) { 1080 num += mUidMap.valueAt(i).size(); 1081 } 1082 return num; 1083 } 1084 1085 public void clear() { 1086 mUidMap.clear(); 1087 } 1088 1089 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1090 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1091 if (map == null) { 1092 map = new ArrayMap<String, ArrayList<String>>(); 1093 mUidMap.put(userId, map); 1094 } 1095 return map; 1096 } 1097 } 1098 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1099 1100 // Service Connection to remote media container service to copy 1101 // package uri's from external media onto secure containers 1102 // or internal storage. 1103 private IMediaContainerService mContainerService = null; 1104 1105 static final int SEND_PENDING_BROADCAST = 1; 1106 static final int MCS_BOUND = 3; 1107 static final int END_COPY = 4; 1108 static final int INIT_COPY = 5; 1109 static final int MCS_UNBIND = 6; 1110 static final int START_CLEANING_PACKAGE = 7; 1111 static final int FIND_INSTALL_LOC = 8; 1112 static final int POST_INSTALL = 9; 1113 static final int MCS_RECONNECT = 10; 1114 static final int MCS_GIVE_UP = 11; 1115 static final int UPDATED_MEDIA_STATUS = 12; 1116 static final int WRITE_SETTINGS = 13; 1117 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1118 static final int PACKAGE_VERIFIED = 15; 1119 static final int CHECK_PENDING_VERIFICATION = 16; 1120 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1121 static final int INTENT_FILTER_VERIFIED = 18; 1122 static final int WRITE_PACKAGE_LIST = 19; 1123 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1124 1125 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1126 1127 // Delay time in millisecs 1128 static final int BROADCAST_DELAY = 10 * 1000; 1129 1130 static UserManagerService sUserManager; 1131 1132 // Stores a list of users whose package restrictions file needs to be updated 1133 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1134 1135 final private DefaultContainerConnection mDefContainerConn = 1136 new DefaultContainerConnection(); 1137 class DefaultContainerConnection implements ServiceConnection { 1138 public void onServiceConnected(ComponentName name, IBinder service) { 1139 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1140 final IMediaContainerService imcs = IMediaContainerService.Stub 1141 .asInterface(Binder.allowBlocking(service)); 1142 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1143 } 1144 1145 public void onServiceDisconnected(ComponentName name) { 1146 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1147 } 1148 } 1149 1150 // Recordkeeping of restore-after-install operations that are currently in flight 1151 // between the Package Manager and the Backup Manager 1152 static class PostInstallData { 1153 public InstallArgs args; 1154 public PackageInstalledInfo res; 1155 1156 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1157 args = _a; 1158 res = _r; 1159 } 1160 } 1161 1162 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1163 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1164 1165 // XML tags for backup/restore of various bits of state 1166 private static final String TAG_PREFERRED_BACKUP = "pa"; 1167 private static final String TAG_DEFAULT_APPS = "da"; 1168 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1169 1170 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1171 private static final String TAG_ALL_GRANTS = "rt-grants"; 1172 private static final String TAG_GRANT = "grant"; 1173 private static final String ATTR_PACKAGE_NAME = "pkg"; 1174 1175 private static final String TAG_PERMISSION = "perm"; 1176 private static final String ATTR_PERMISSION_NAME = "name"; 1177 private static final String ATTR_IS_GRANTED = "g"; 1178 private static final String ATTR_USER_SET = "set"; 1179 private static final String ATTR_USER_FIXED = "fixed"; 1180 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1181 1182 // System/policy permission grants are not backed up 1183 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1184 FLAG_PERMISSION_POLICY_FIXED 1185 | FLAG_PERMISSION_SYSTEM_FIXED 1186 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1187 1188 // And we back up these user-adjusted states 1189 private static final int USER_RUNTIME_GRANT_MASK = 1190 FLAG_PERMISSION_USER_SET 1191 | FLAG_PERMISSION_USER_FIXED 1192 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1193 1194 final @Nullable String mRequiredVerifierPackage; 1195 final @NonNull String mRequiredInstallerPackage; 1196 final @NonNull String mRequiredUninstallerPackage; 1197 final @Nullable String mSetupWizardPackage; 1198 final @Nullable String mStorageManagerPackage; 1199 final @NonNull String mServicesSystemSharedLibraryPackageName; 1200 final @NonNull String mSharedSystemSharedLibraryPackageName; 1201 1202 final boolean mPermissionReviewRequired; 1203 1204 private final PackageUsage mPackageUsage = new PackageUsage(); 1205 private final CompilerStats mCompilerStats = new CompilerStats(); 1206 1207 class PackageHandler extends Handler { 1208 private boolean mBound = false; 1209 final ArrayList<HandlerParams> mPendingInstalls = 1210 new ArrayList<HandlerParams>(); 1211 1212 private boolean connectToService() { 1213 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1214 " DefaultContainerService"); 1215 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1216 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1217 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1218 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1219 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1220 mBound = true; 1221 return true; 1222 } 1223 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1224 return false; 1225 } 1226 1227 private void disconnectService() { 1228 mContainerService = null; 1229 mBound = false; 1230 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1231 mContext.unbindService(mDefContainerConn); 1232 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1233 } 1234 1235 PackageHandler(Looper looper) { 1236 super(looper); 1237 } 1238 1239 public void handleMessage(Message msg) { 1240 try { 1241 doHandleMessage(msg); 1242 } finally { 1243 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1244 } 1245 } 1246 1247 void doHandleMessage(Message msg) { 1248 switch (msg.what) { 1249 case INIT_COPY: { 1250 HandlerParams params = (HandlerParams) msg.obj; 1251 int idx = mPendingInstalls.size(); 1252 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1253 // If a bind was already initiated we dont really 1254 // need to do anything. The pending install 1255 // will be processed later on. 1256 if (!mBound) { 1257 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1258 System.identityHashCode(mHandler)); 1259 // If this is the only one pending we might 1260 // have to bind to the service again. 1261 if (!connectToService()) { 1262 Slog.e(TAG, "Failed to bind to media container service"); 1263 params.serviceError(); 1264 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1265 System.identityHashCode(mHandler)); 1266 if (params.traceMethod != null) { 1267 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1268 params.traceCookie); 1269 } 1270 return; 1271 } else { 1272 // Once we bind to the service, the first 1273 // pending request will be processed. 1274 mPendingInstalls.add(idx, params); 1275 } 1276 } else { 1277 mPendingInstalls.add(idx, params); 1278 // Already bound to the service. Just make 1279 // sure we trigger off processing the first request. 1280 if (idx == 0) { 1281 mHandler.sendEmptyMessage(MCS_BOUND); 1282 } 1283 } 1284 break; 1285 } 1286 case MCS_BOUND: { 1287 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1288 if (msg.obj != null) { 1289 mContainerService = (IMediaContainerService) msg.obj; 1290 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1291 System.identityHashCode(mHandler)); 1292 } 1293 if (mContainerService == null) { 1294 if (!mBound) { 1295 // Something seriously wrong since we are not bound and we are not 1296 // waiting for connection. Bail out. 1297 Slog.e(TAG, "Cannot bind to media container service"); 1298 for (HandlerParams params : mPendingInstalls) { 1299 // Indicate service bind error 1300 params.serviceError(); 1301 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1302 System.identityHashCode(params)); 1303 if (params.traceMethod != null) { 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1305 params.traceMethod, params.traceCookie); 1306 } 1307 return; 1308 } 1309 mPendingInstalls.clear(); 1310 } else { 1311 Slog.w(TAG, "Waiting to connect to media container service"); 1312 } 1313 } else if (mPendingInstalls.size() > 0) { 1314 HandlerParams params = mPendingInstalls.get(0); 1315 if (params != null) { 1316 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1317 System.identityHashCode(params)); 1318 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1319 if (params.startCopy()) { 1320 // We are done... look for more work or to 1321 // go idle. 1322 if (DEBUG_SD_INSTALL) Log.i(TAG, 1323 "Checking for more work or unbind..."); 1324 // Delete pending install 1325 if (mPendingInstalls.size() > 0) { 1326 mPendingInstalls.remove(0); 1327 } 1328 if (mPendingInstalls.size() == 0) { 1329 if (mBound) { 1330 if (DEBUG_SD_INSTALL) Log.i(TAG, 1331 "Posting delayed MCS_UNBIND"); 1332 removeMessages(MCS_UNBIND); 1333 Message ubmsg = obtainMessage(MCS_UNBIND); 1334 // Unbind after a little delay, to avoid 1335 // continual thrashing. 1336 sendMessageDelayed(ubmsg, 10000); 1337 } 1338 } else { 1339 // There are more pending requests in queue. 1340 // Just post MCS_BOUND message to trigger processing 1341 // of next pending install. 1342 if (DEBUG_SD_INSTALL) Log.i(TAG, 1343 "Posting MCS_BOUND for next work"); 1344 mHandler.sendEmptyMessage(MCS_BOUND); 1345 } 1346 } 1347 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1348 } 1349 } else { 1350 // Should never happen ideally. 1351 Slog.w(TAG, "Empty queue"); 1352 } 1353 break; 1354 } 1355 case MCS_RECONNECT: { 1356 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1357 if (mPendingInstalls.size() > 0) { 1358 if (mBound) { 1359 disconnectService(); 1360 } 1361 if (!connectToService()) { 1362 Slog.e(TAG, "Failed to bind to media container service"); 1363 for (HandlerParams params : mPendingInstalls) { 1364 // Indicate service bind error 1365 params.serviceError(); 1366 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1367 System.identityHashCode(params)); 1368 } 1369 mPendingInstalls.clear(); 1370 } 1371 } 1372 break; 1373 } 1374 case MCS_UNBIND: { 1375 // If there is no actual work left, then time to unbind. 1376 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1377 1378 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1379 if (mBound) { 1380 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1381 1382 disconnectService(); 1383 } 1384 } else if (mPendingInstalls.size() > 0) { 1385 // There are more pending requests in queue. 1386 // Just post MCS_BOUND message to trigger processing 1387 // of next pending install. 1388 mHandler.sendEmptyMessage(MCS_BOUND); 1389 } 1390 1391 break; 1392 } 1393 case MCS_GIVE_UP: { 1394 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1395 HandlerParams params = mPendingInstalls.remove(0); 1396 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1397 System.identityHashCode(params)); 1398 break; 1399 } 1400 case SEND_PENDING_BROADCAST: { 1401 String packages[]; 1402 ArrayList<String> components[]; 1403 int size = 0; 1404 int uids[]; 1405 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1406 synchronized (mPackages) { 1407 if (mPendingBroadcasts == null) { 1408 return; 1409 } 1410 size = mPendingBroadcasts.size(); 1411 if (size <= 0) { 1412 // Nothing to be done. Just return 1413 return; 1414 } 1415 packages = new String[size]; 1416 components = new ArrayList[size]; 1417 uids = new int[size]; 1418 int i = 0; // filling out the above arrays 1419 1420 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1421 int packageUserId = mPendingBroadcasts.userIdAt(n); 1422 Iterator<Map.Entry<String, ArrayList<String>>> it 1423 = mPendingBroadcasts.packagesForUserId(packageUserId) 1424 .entrySet().iterator(); 1425 while (it.hasNext() && i < size) { 1426 Map.Entry<String, ArrayList<String>> ent = it.next(); 1427 packages[i] = ent.getKey(); 1428 components[i] = ent.getValue(); 1429 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1430 uids[i] = (ps != null) 1431 ? UserHandle.getUid(packageUserId, ps.appId) 1432 : -1; 1433 i++; 1434 } 1435 } 1436 size = i; 1437 mPendingBroadcasts.clear(); 1438 } 1439 // Send broadcasts 1440 for (int i = 0; i < size; i++) { 1441 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1442 } 1443 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1444 break; 1445 } 1446 case START_CLEANING_PACKAGE: { 1447 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1448 final String packageName = (String)msg.obj; 1449 final int userId = msg.arg1; 1450 final boolean andCode = msg.arg2 != 0; 1451 synchronized (mPackages) { 1452 if (userId == UserHandle.USER_ALL) { 1453 int[] users = sUserManager.getUserIds(); 1454 for (int user : users) { 1455 mSettings.addPackageToCleanLPw( 1456 new PackageCleanItem(user, packageName, andCode)); 1457 } 1458 } else { 1459 mSettings.addPackageToCleanLPw( 1460 new PackageCleanItem(userId, packageName, andCode)); 1461 } 1462 } 1463 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1464 startCleaningPackages(); 1465 } break; 1466 case POST_INSTALL: { 1467 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1468 1469 PostInstallData data = mRunningInstalls.get(msg.arg1); 1470 final boolean didRestore = (msg.arg2 != 0); 1471 mRunningInstalls.delete(msg.arg1); 1472 1473 if (data != null) { 1474 InstallArgs args = data.args; 1475 PackageInstalledInfo parentRes = data.res; 1476 1477 final boolean grantPermissions = (args.installFlags 1478 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1479 final boolean killApp = (args.installFlags 1480 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1481 final String[] grantedPermissions = args.installGrantPermissions; 1482 1483 // Handle the parent package 1484 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1485 grantedPermissions, didRestore, args.installerPackageName, 1486 args.observer); 1487 1488 // Handle the child packages 1489 final int childCount = (parentRes.addedChildPackages != null) 1490 ? parentRes.addedChildPackages.size() : 0; 1491 for (int i = 0; i < childCount; i++) { 1492 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1493 handlePackagePostInstall(childRes, grantPermissions, killApp, 1494 grantedPermissions, false, args.installerPackageName, 1495 args.observer); 1496 } 1497 1498 // Log tracing if needed 1499 if (args.traceMethod != null) { 1500 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1501 args.traceCookie); 1502 } 1503 } else { 1504 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1505 } 1506 1507 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1508 } break; 1509 case UPDATED_MEDIA_STATUS: { 1510 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1511 boolean reportStatus = msg.arg1 == 1; 1512 boolean doGc = msg.arg2 == 1; 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1514 if (doGc) { 1515 // Force a gc to clear up stale containers. 1516 Runtime.getRuntime().gc(); 1517 } 1518 if (msg.obj != null) { 1519 @SuppressWarnings("unchecked") 1520 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1521 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1522 // Unload containers 1523 unloadAllContainers(args); 1524 } 1525 if (reportStatus) { 1526 try { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, 1528 "Invoking StorageManagerService call back"); 1529 PackageHelper.getStorageManager().finishMediaUpdate(); 1530 } catch (RemoteException e) { 1531 Log.e(TAG, "StorageManagerService not running?"); 1532 } 1533 } 1534 } break; 1535 case WRITE_SETTINGS: { 1536 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1537 synchronized (mPackages) { 1538 removeMessages(WRITE_SETTINGS); 1539 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1540 mSettings.writeLPr(); 1541 mDirtyUsers.clear(); 1542 } 1543 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1544 } break; 1545 case WRITE_PACKAGE_RESTRICTIONS: { 1546 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1547 synchronized (mPackages) { 1548 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1549 for (int userId : mDirtyUsers) { 1550 mSettings.writePackageRestrictionsLPr(userId); 1551 } 1552 mDirtyUsers.clear(); 1553 } 1554 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1555 } break; 1556 case WRITE_PACKAGE_LIST: { 1557 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1558 synchronized (mPackages) { 1559 removeMessages(WRITE_PACKAGE_LIST); 1560 mSettings.writePackageListLPr(msg.arg1); 1561 } 1562 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1563 } break; 1564 case CHECK_PENDING_VERIFICATION: { 1565 final int verificationId = msg.arg1; 1566 final PackageVerificationState state = mPendingVerification.get(verificationId); 1567 1568 if ((state != null) && !state.timeoutExtended()) { 1569 final InstallArgs args = state.getInstallArgs(); 1570 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1571 1572 Slog.i(TAG, "Verification timed out for " + originUri); 1573 mPendingVerification.remove(verificationId); 1574 1575 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1576 1577 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1578 Slog.i(TAG, "Continuing with installation of " + originUri); 1579 state.setVerifierResponse(Binder.getCallingUid(), 1580 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1581 broadcastPackageVerified(verificationId, originUri, 1582 PackageManager.VERIFICATION_ALLOW, 1583 state.getInstallArgs().getUser()); 1584 try { 1585 ret = args.copyApk(mContainerService, true); 1586 } catch (RemoteException e) { 1587 Slog.e(TAG, "Could not contact the ContainerService"); 1588 } 1589 } else { 1590 broadcastPackageVerified(verificationId, originUri, 1591 PackageManager.VERIFICATION_REJECT, 1592 state.getInstallArgs().getUser()); 1593 } 1594 1595 Trace.asyncTraceEnd( 1596 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1597 1598 processPendingInstall(args, ret); 1599 mHandler.sendEmptyMessage(MCS_UNBIND); 1600 } 1601 break; 1602 } 1603 case PACKAGE_VERIFIED: { 1604 final int verificationId = msg.arg1; 1605 1606 final PackageVerificationState state = mPendingVerification.get(verificationId); 1607 if (state == null) { 1608 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1609 break; 1610 } 1611 1612 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1613 1614 state.setVerifierResponse(response.callerUid, response.code); 1615 1616 if (state.isVerificationComplete()) { 1617 mPendingVerification.remove(verificationId); 1618 1619 final InstallArgs args = state.getInstallArgs(); 1620 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1621 1622 int ret; 1623 if (state.isInstallAllowed()) { 1624 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1625 broadcastPackageVerified(verificationId, originUri, 1626 response.code, state.getInstallArgs().getUser()); 1627 try { 1628 ret = args.copyApk(mContainerService, true); 1629 } catch (RemoteException e) { 1630 Slog.e(TAG, "Could not contact the ContainerService"); 1631 } 1632 } else { 1633 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1634 } 1635 1636 Trace.asyncTraceEnd( 1637 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1638 1639 processPendingInstall(args, ret); 1640 mHandler.sendEmptyMessage(MCS_UNBIND); 1641 } 1642 1643 break; 1644 } 1645 case START_INTENT_FILTER_VERIFICATIONS: { 1646 IFVerificationParams params = (IFVerificationParams) msg.obj; 1647 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1648 params.replacing, params.pkg); 1649 break; 1650 } 1651 case INTENT_FILTER_VERIFIED: { 1652 final int verificationId = msg.arg1; 1653 1654 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1655 verificationId); 1656 if (state == null) { 1657 Slog.w(TAG, "Invalid IntentFilter verification token " 1658 + verificationId + " received"); 1659 break; 1660 } 1661 1662 final int userId = state.getUserId(); 1663 1664 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1665 "Processing IntentFilter verification with token:" 1666 + verificationId + " and userId:" + userId); 1667 1668 final IntentFilterVerificationResponse response = 1669 (IntentFilterVerificationResponse) msg.obj; 1670 1671 state.setVerifierResponse(response.callerUid, response.code); 1672 1673 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1674 "IntentFilter verification with token:" + verificationId 1675 + " and userId:" + userId 1676 + " is settings verifier response with response code:" 1677 + response.code); 1678 1679 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1680 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1681 + response.getFailedDomainsString()); 1682 } 1683 1684 if (state.isVerificationComplete()) { 1685 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1686 } else { 1687 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1688 "IntentFilter verification with token:" + verificationId 1689 + " was not said to be complete"); 1690 } 1691 1692 break; 1693 } 1694 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1695 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1696 mEphemeralResolverConnection, 1697 (EphemeralRequest) msg.obj, 1698 mEphemeralInstallerActivity, 1699 mHandler); 1700 } 1701 } 1702 } 1703 } 1704 1705 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1706 boolean killApp, String[] grantedPermissions, 1707 boolean launchedForRestore, String installerPackage, 1708 IPackageInstallObserver2 installObserver) { 1709 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1710 // Send the removed broadcasts 1711 if (res.removedInfo != null) { 1712 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1713 } 1714 1715 // Now that we successfully installed the package, grant runtime 1716 // permissions if requested before broadcasting the install. 1717 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1718 >= Build.VERSION_CODES.M) { 1719 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1720 } 1721 1722 final boolean update = res.removedInfo != null 1723 && res.removedInfo.removedPackage != null; 1724 1725 // If this is the first time we have child packages for a disabled privileged 1726 // app that had no children, we grant requested runtime permissions to the new 1727 // children if the parent on the system image had them already granted. 1728 if (res.pkg.parentPackage != null) { 1729 synchronized (mPackages) { 1730 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1731 } 1732 } 1733 1734 synchronized (mPackages) { 1735 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1736 } 1737 1738 final String packageName = res.pkg.applicationInfo.packageName; 1739 1740 // Determine the set of users who are adding this package for 1741 // the first time vs. those who are seeing an update. 1742 int[] firstUsers = EMPTY_INT_ARRAY; 1743 int[] updateUsers = EMPTY_INT_ARRAY; 1744 if (res.origUsers == null || res.origUsers.length == 0) { 1745 firstUsers = res.newUsers; 1746 } else { 1747 for (int newUser : res.newUsers) { 1748 boolean isNew = true; 1749 for (int origUser : res.origUsers) { 1750 if (origUser == newUser) { 1751 isNew = false; 1752 break; 1753 } 1754 } 1755 if (isNew) { 1756 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1757 } else { 1758 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1759 } 1760 } 1761 } 1762 1763 // Send installed broadcasts if the install/update is not ephemeral 1764 if (!isEphemeral(res.pkg)) { 1765 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1766 1767 // Send added for users that see the package for the first time 1768 // sendPackageAddedForNewUsers also deals with system apps 1769 int appId = UserHandle.getAppId(res.uid); 1770 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1771 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1772 1773 // Send added for users that don't see the package for the first time 1774 Bundle extras = new Bundle(1); 1775 extras.putInt(Intent.EXTRA_UID, res.uid); 1776 if (update) { 1777 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1778 } 1779 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1780 extras, 0 /*flags*/, null /*targetPackage*/, 1781 null /*finishedReceiver*/, updateUsers); 1782 1783 // Send replaced for users that don't see the package for the first time 1784 if (update) { 1785 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1786 packageName, extras, 0 /*flags*/, 1787 null /*targetPackage*/, null /*finishedReceiver*/, 1788 updateUsers); 1789 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1790 null /*package*/, null /*extras*/, 0 /*flags*/, 1791 packageName /*targetPackage*/, 1792 null /*finishedReceiver*/, updateUsers); 1793 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1794 // First-install and we did a restore, so we're responsible for the 1795 // first-launch broadcast. 1796 if (DEBUG_BACKUP) { 1797 Slog.i(TAG, "Post-restore of " + packageName 1798 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1799 } 1800 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1801 } 1802 1803 // Send broadcast package appeared if forward locked/external for all users 1804 // treat asec-hosted packages like removable media on upgrade 1805 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1806 if (DEBUG_INSTALL) { 1807 Slog.i(TAG, "upgrading pkg " + res.pkg 1808 + " is ASEC-hosted -> AVAILABLE"); 1809 } 1810 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1811 ArrayList<String> pkgList = new ArrayList<>(1); 1812 pkgList.add(packageName); 1813 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1814 } 1815 } 1816 1817 // Work that needs to happen on first install within each user 1818 if (firstUsers != null && firstUsers.length > 0) { 1819 synchronized (mPackages) { 1820 for (int userId : firstUsers) { 1821 // If this app is a browser and it's newly-installed for some 1822 // users, clear any default-browser state in those users. The 1823 // app's nature doesn't depend on the user, so we can just check 1824 // its browser nature in any user and generalize. 1825 if (packageIsBrowser(packageName, userId)) { 1826 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1827 } 1828 1829 // We may also need to apply pending (restored) runtime 1830 // permission grants within these users. 1831 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1832 } 1833 } 1834 } 1835 1836 // Log current value of "unknown sources" setting 1837 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1838 getUnknownSourcesSettings()); 1839 1840 // Force a gc to clear up things 1841 Runtime.getRuntime().gc(); 1842 1843 // Remove the replaced package's older resources safely now 1844 // We delete after a gc for applications on sdcard. 1845 if (res.removedInfo != null && res.removedInfo.args != null) { 1846 synchronized (mInstallLock) { 1847 res.removedInfo.args.doPostDeleteLI(true); 1848 } 1849 } 1850 } 1851 1852 // If someone is watching installs - notify them 1853 if (installObserver != null) { 1854 try { 1855 Bundle extras = extrasForInstallResult(res); 1856 installObserver.onPackageInstalled(res.name, res.returnCode, 1857 res.returnMsg, extras); 1858 } catch (RemoteException e) { 1859 Slog.i(TAG, "Observer no longer exists."); 1860 } 1861 } 1862 } 1863 1864 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1865 PackageParser.Package pkg) { 1866 if (pkg.parentPackage == null) { 1867 return; 1868 } 1869 if (pkg.requestedPermissions == null) { 1870 return; 1871 } 1872 final PackageSetting disabledSysParentPs = mSettings 1873 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1874 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1875 || !disabledSysParentPs.isPrivileged() 1876 || (disabledSysParentPs.childPackageNames != null 1877 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1878 return; 1879 } 1880 final int[] allUserIds = sUserManager.getUserIds(); 1881 final int permCount = pkg.requestedPermissions.size(); 1882 for (int i = 0; i < permCount; i++) { 1883 String permission = pkg.requestedPermissions.get(i); 1884 BasePermission bp = mSettings.mPermissions.get(permission); 1885 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1886 continue; 1887 } 1888 for (int userId : allUserIds) { 1889 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1890 permission, userId)) { 1891 grantRuntimePermission(pkg.packageName, permission, userId); 1892 } 1893 } 1894 } 1895 } 1896 1897 private StorageEventListener mStorageListener = new StorageEventListener() { 1898 @Override 1899 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1900 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1901 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1902 final String volumeUuid = vol.getFsUuid(); 1903 1904 // Clean up any users or apps that were removed or recreated 1905 // while this volume was missing 1906 reconcileUsers(volumeUuid); 1907 reconcileApps(volumeUuid); 1908 1909 // Clean up any install sessions that expired or were 1910 // cancelled while this volume was missing 1911 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1912 1913 loadPrivatePackages(vol); 1914 1915 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1916 unloadPrivatePackages(vol); 1917 } 1918 } 1919 1920 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1921 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1922 updateExternalMediaStatus(true, false); 1923 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1924 updateExternalMediaStatus(false, false); 1925 } 1926 } 1927 } 1928 1929 @Override 1930 public void onVolumeForgotten(String fsUuid) { 1931 if (TextUtils.isEmpty(fsUuid)) { 1932 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1933 return; 1934 } 1935 1936 // Remove any apps installed on the forgotten volume 1937 synchronized (mPackages) { 1938 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1939 for (PackageSetting ps : packages) { 1940 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1941 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1942 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1943 1944 // Try very hard to release any references to this package 1945 // so we don't risk the system server being killed due to 1946 // open FDs 1947 AttributeCache.instance().removePackage(ps.name); 1948 } 1949 1950 mSettings.onVolumeForgotten(fsUuid); 1951 mSettings.writeLPr(); 1952 } 1953 } 1954 }; 1955 1956 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1957 String[] grantedPermissions) { 1958 for (int userId : userIds) { 1959 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1960 } 1961 1962 // We could have touched GID membership, so flush out packages.list 1963 synchronized (mPackages) { 1964 mSettings.writePackageListLPr(); 1965 } 1966 } 1967 1968 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1969 String[] grantedPermissions) { 1970 SettingBase sb = (SettingBase) pkg.mExtras; 1971 if (sb == null) { 1972 return; 1973 } 1974 1975 PermissionsState permissionsState = sb.getPermissionsState(); 1976 1977 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1978 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1979 1980 for (String permission : pkg.requestedPermissions) { 1981 final BasePermission bp; 1982 synchronized (mPackages) { 1983 bp = mSettings.mPermissions.get(permission); 1984 } 1985 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1986 && (grantedPermissions == null 1987 || ArrayUtils.contains(grantedPermissions, permission))) { 1988 final int flags = permissionsState.getPermissionFlags(permission, userId); 1989 // Installer cannot change immutable permissions. 1990 if ((flags & immutableFlags) == 0) { 1991 grantRuntimePermission(pkg.packageName, permission, userId); 1992 } 1993 } 1994 } 1995 } 1996 1997 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1998 Bundle extras = null; 1999 switch (res.returnCode) { 2000 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2001 extras = new Bundle(); 2002 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2003 res.origPermission); 2004 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2005 res.origPackage); 2006 break; 2007 } 2008 case PackageManager.INSTALL_SUCCEEDED: { 2009 extras = new Bundle(); 2010 extras.putBoolean(Intent.EXTRA_REPLACING, 2011 res.removedInfo != null && res.removedInfo.removedPackage != null); 2012 break; 2013 } 2014 } 2015 return extras; 2016 } 2017 2018 void scheduleWriteSettingsLocked() { 2019 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2020 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2021 } 2022 } 2023 2024 void scheduleWritePackageListLocked(int userId) { 2025 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2026 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2027 msg.arg1 = userId; 2028 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2029 } 2030 } 2031 2032 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2033 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2034 scheduleWritePackageRestrictionsLocked(userId); 2035 } 2036 2037 void scheduleWritePackageRestrictionsLocked(int userId) { 2038 final int[] userIds = (userId == UserHandle.USER_ALL) 2039 ? sUserManager.getUserIds() : new int[]{userId}; 2040 for (int nextUserId : userIds) { 2041 if (!sUserManager.exists(nextUserId)) return; 2042 mDirtyUsers.add(nextUserId); 2043 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2044 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2045 } 2046 } 2047 } 2048 2049 public static PackageManagerService main(Context context, Installer installer, 2050 boolean factoryTest, boolean onlyCore) { 2051 // Self-check for initial settings. 2052 PackageManagerServiceCompilerMapping.checkProperties(); 2053 2054 PackageManagerService m = new PackageManagerService(context, installer, 2055 factoryTest, onlyCore); 2056 m.enableSystemUserPackages(); 2057 ServiceManager.addService("package", m); 2058 return m; 2059 } 2060 2061 private void enableSystemUserPackages() { 2062 if (!UserManager.isSplitSystemUser()) { 2063 return; 2064 } 2065 // For system user, enable apps based on the following conditions: 2066 // - app is whitelisted or belong to one of these groups: 2067 // -- system app which has no launcher icons 2068 // -- system app which has INTERACT_ACROSS_USERS permission 2069 // -- system IME app 2070 // - app is not in the blacklist 2071 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2072 Set<String> enableApps = new ArraySet<>(); 2073 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2074 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2075 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2076 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2077 enableApps.addAll(wlApps); 2078 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2079 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2080 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2081 enableApps.removeAll(blApps); 2082 Log.i(TAG, "Applications installed for system user: " + enableApps); 2083 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2084 UserHandle.SYSTEM); 2085 final int allAppsSize = allAps.size(); 2086 synchronized (mPackages) { 2087 for (int i = 0; i < allAppsSize; i++) { 2088 String pName = allAps.get(i); 2089 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2090 // Should not happen, but we shouldn't be failing if it does 2091 if (pkgSetting == null) { 2092 continue; 2093 } 2094 boolean install = enableApps.contains(pName); 2095 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2096 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2097 + " for system user"); 2098 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2099 } 2100 } 2101 } 2102 } 2103 2104 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2105 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2106 Context.DISPLAY_SERVICE); 2107 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2108 } 2109 2110 /** 2111 * Requests that files preopted on a secondary system partition be copied to the data partition 2112 * if possible. Note that the actual copying of the files is accomplished by init for security 2113 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2114 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2115 */ 2116 private static void requestCopyPreoptedFiles() { 2117 final int WAIT_TIME_MS = 100; 2118 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2119 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2120 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2121 // We will wait for up to 100 seconds. 2122 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2123 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2124 try { 2125 Thread.sleep(WAIT_TIME_MS); 2126 } catch (InterruptedException e) { 2127 // Do nothing 2128 } 2129 if (SystemClock.uptimeMillis() > timeEnd) { 2130 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2131 Slog.wtf(TAG, "cppreopt did not finish!"); 2132 break; 2133 } 2134 } 2135 } 2136 } 2137 2138 public PackageManagerService(Context context, Installer installer, 2139 boolean factoryTest, boolean onlyCore) { 2140 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2141 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2142 SystemClock.uptimeMillis()); 2143 2144 if (mSdkVersion <= 0) { 2145 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2146 } 2147 2148 mContext = context; 2149 2150 mPermissionReviewRequired = context.getResources().getBoolean( 2151 R.bool.config_permissionReviewRequired); 2152 2153 mFactoryTest = factoryTest; 2154 mOnlyCore = onlyCore; 2155 mMetrics = new DisplayMetrics(); 2156 mSettings = new Settings(mPackages); 2157 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2158 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2159 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2160 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2161 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2162 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2163 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2164 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2165 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2166 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2167 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2168 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2169 2170 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2171 if (separateProcesses != null && separateProcesses.length() > 0) { 2172 if ("*".equals(separateProcesses)) { 2173 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2174 mSeparateProcesses = null; 2175 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2176 } else { 2177 mDefParseFlags = 0; 2178 mSeparateProcesses = separateProcesses.split(","); 2179 Slog.w(TAG, "Running with debug.separate_processes: " 2180 + separateProcesses); 2181 } 2182 } else { 2183 mDefParseFlags = 0; 2184 mSeparateProcesses = null; 2185 } 2186 2187 mInstaller = installer; 2188 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2189 "*dexopt*"); 2190 mDexManager = new DexManager(); 2191 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2192 2193 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2194 FgThread.get().getLooper()); 2195 2196 getDefaultDisplayMetrics(context, mMetrics); 2197 2198 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2199 SystemConfig systemConfig = SystemConfig.getInstance(); 2200 mGlobalGids = systemConfig.getGlobalGids(); 2201 mSystemPermissions = systemConfig.getSystemPermissions(); 2202 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2204 2205 mProtectedPackages = new ProtectedPackages(mContext); 2206 2207 synchronized (mInstallLock) { 2208 // writer 2209 synchronized (mPackages) { 2210 mHandlerThread = new ServiceThread(TAG, 2211 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2212 mHandlerThread.start(); 2213 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2214 mProcessLoggingHandler = new ProcessLoggingHandler(); 2215 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2216 2217 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2218 2219 File dataDir = Environment.getDataDirectory(); 2220 mAppInstallDir = new File(dataDir, "app"); 2221 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2222 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2223 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2224 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2225 2226 sUserManager = new UserManagerService(context, this, mPackages); 2227 2228 // Propagate permission configuration in to package manager. 2229 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2230 = systemConfig.getPermissions(); 2231 for (int i=0; i<permConfig.size(); i++) { 2232 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2233 BasePermission bp = mSettings.mPermissions.get(perm.name); 2234 if (bp == null) { 2235 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2236 mSettings.mPermissions.put(perm.name, bp); 2237 } 2238 if (perm.gids != null) { 2239 bp.setGids(perm.gids, perm.perUser); 2240 } 2241 } 2242 2243 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2244 for (int i=0; i<libConfig.size(); i++) { 2245 mSharedLibraries.put(libConfig.keyAt(i), 2246 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2247 } 2248 2249 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2250 2251 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2252 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2253 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2254 2255 // Clean up orphaned packages for which the code path doesn't exist 2256 // and they are an update to a system app - caused by bug/32321269 2257 final int packageSettingCount = mSettings.mPackages.size(); 2258 for (int i = packageSettingCount - 1; i >= 0; i--) { 2259 PackageSetting ps = mSettings.mPackages.valueAt(i); 2260 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2261 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2262 mSettings.mPackages.removeAt(i); 2263 mSettings.enableSystemPackageLPw(ps.name); 2264 } 2265 } 2266 2267 if (mFirstBoot) { 2268 requestCopyPreoptedFiles(); 2269 } 2270 2271 String customResolverActivity = Resources.getSystem().getString( 2272 R.string.config_customResolverActivity); 2273 if (TextUtils.isEmpty(customResolverActivity)) { 2274 customResolverActivity = null; 2275 } else { 2276 mCustomResolverComponentName = ComponentName.unflattenFromString( 2277 customResolverActivity); 2278 } 2279 2280 long startTime = SystemClock.uptimeMillis(); 2281 2282 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2283 startTime); 2284 2285 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2286 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2287 2288 if (bootClassPath == null) { 2289 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2290 } 2291 2292 if (systemServerClassPath == null) { 2293 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2294 } 2295 2296 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2297 final String[] dexCodeInstructionSets = 2298 getDexCodeInstructionSets( 2299 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2300 2301 /** 2302 * Ensure all external libraries have had dexopt run on them. 2303 */ 2304 if (mSharedLibraries.size() > 0) { 2305 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2306 // NOTE: For now, we're compiling these system "shared libraries" 2307 // (and framework jars) into all available architectures. It's possible 2308 // to compile them only when we come across an app that uses them (there's 2309 // already logic for that in scanPackageLI) but that adds some complexity. 2310 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2311 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2312 final String lib = libEntry.path; 2313 if (lib == null) { 2314 continue; 2315 } 2316 2317 try { 2318 // Shared libraries do not have profiles so we perform a full 2319 // AOT compilation (if needed). 2320 int dexoptNeeded = DexFile.getDexOptNeeded( 2321 lib, dexCodeInstructionSet, 2322 getCompilerFilterForReason(REASON_SHARED_APK), 2323 false /* newProfile */); 2324 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2325 mInstaller.dexopt(lib, Process.SYSTEM_UID, "*", 2326 dexCodeInstructionSet, dexoptNeeded, null, 2327 DEXOPT_PUBLIC, 2328 getCompilerFilterForReason(REASON_SHARED_APK), 2329 StorageManager.UUID_PRIVATE_INTERNAL, 2330 SKIP_SHARED_LIBRARY_CHECK); 2331 } 2332 } catch (FileNotFoundException e) { 2333 Slog.w(TAG, "Library not found: " + lib); 2334 } catch (IOException | InstallerException e) { 2335 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2336 + e.getMessage()); 2337 } 2338 } 2339 } 2340 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2341 } 2342 2343 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2344 2345 final VersionInfo ver = mSettings.getInternalVersion(); 2346 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2347 2348 // when upgrading from pre-M, promote system app permissions from install to runtime 2349 mPromoteSystemApps = 2350 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2351 2352 // When upgrading from pre-N, we need to handle package extraction like first boot, 2353 // as there is no profiling data available. 2354 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2355 2356 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2357 2358 // save off the names of pre-existing system packages prior to scanning; we don't 2359 // want to automatically grant runtime permissions for new system apps 2360 if (mPromoteSystemApps) { 2361 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2362 while (pkgSettingIter.hasNext()) { 2363 PackageSetting ps = pkgSettingIter.next(); 2364 if (isSystemApp(ps)) { 2365 mExistingSystemPackages.add(ps.name); 2366 } 2367 } 2368 } 2369 2370 mCacheDir = preparePackageParserCache(mIsUpgrade); 2371 2372 // Set flag to monitor and not change apk file paths when 2373 // scanning install directories. 2374 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2375 2376 if (mIsUpgrade || mFirstBoot) { 2377 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2378 } 2379 2380 // Collect vendor overlay packages. (Do this before scanning any apps.) 2381 // For security and version matching reason, only consider 2382 // overlay packages if they reside in the right directory. 2383 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2384 if (overlayThemeDir.isEmpty()) { 2385 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2386 } 2387 if (!overlayThemeDir.isEmpty()) { 2388 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2389 | PackageParser.PARSE_IS_SYSTEM 2390 | PackageParser.PARSE_IS_SYSTEM_DIR 2391 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2392 } 2393 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2394 | PackageParser.PARSE_IS_SYSTEM 2395 | PackageParser.PARSE_IS_SYSTEM_DIR 2396 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2397 2398 // Find base frameworks (resource packages without code). 2399 scanDirTracedLI(frameworkDir, mDefParseFlags 2400 | PackageParser.PARSE_IS_SYSTEM 2401 | PackageParser.PARSE_IS_SYSTEM_DIR 2402 | PackageParser.PARSE_IS_PRIVILEGED, 2403 scanFlags | SCAN_NO_DEX, 0); 2404 2405 // Collected privileged system packages. 2406 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2407 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2408 | PackageParser.PARSE_IS_SYSTEM 2409 | PackageParser.PARSE_IS_SYSTEM_DIR 2410 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2411 2412 // Collect ordinary system packages. 2413 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2414 scanDirTracedLI(systemAppDir, mDefParseFlags 2415 | PackageParser.PARSE_IS_SYSTEM 2416 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2417 2418 // Collect all vendor packages. 2419 File vendorAppDir = new File("/vendor/app"); 2420 try { 2421 vendorAppDir = vendorAppDir.getCanonicalFile(); 2422 } catch (IOException e) { 2423 // failed to look up canonical path, continue with original one 2424 } 2425 scanDirTracedLI(vendorAppDir, mDefParseFlags 2426 | PackageParser.PARSE_IS_SYSTEM 2427 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2428 2429 // Collect all OEM packages. 2430 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2431 scanDirTracedLI(oemAppDir, mDefParseFlags 2432 | PackageParser.PARSE_IS_SYSTEM 2433 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2434 2435 // Prune any system packages that no longer exist. 2436 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2437 if (!mOnlyCore) { 2438 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2439 while (psit.hasNext()) { 2440 PackageSetting ps = psit.next(); 2441 2442 /* 2443 * If this is not a system app, it can't be a 2444 * disable system app. 2445 */ 2446 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2447 continue; 2448 } 2449 2450 /* 2451 * If the package is scanned, it's not erased. 2452 */ 2453 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2454 if (scannedPkg != null) { 2455 /* 2456 * If the system app is both scanned and in the 2457 * disabled packages list, then it must have been 2458 * added via OTA. Remove it from the currently 2459 * scanned package so the previously user-installed 2460 * application can be scanned. 2461 */ 2462 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2463 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2464 + ps.name + "; removing system app. Last known codePath=" 2465 + ps.codePathString + ", installStatus=" + ps.installStatus 2466 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2467 + scannedPkg.mVersionCode); 2468 removePackageLI(scannedPkg, true); 2469 mExpectingBetter.put(ps.name, ps.codePath); 2470 } 2471 2472 continue; 2473 } 2474 2475 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2476 psit.remove(); 2477 logCriticalInfo(Log.WARN, "System package " + ps.name 2478 + " no longer exists; it's data will be wiped"); 2479 // Actual deletion of code and data will be handled by later 2480 // reconciliation step 2481 } else { 2482 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2483 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2484 possiblyDeletedUpdatedSystemApps.add(ps.name); 2485 } 2486 } 2487 } 2488 } 2489 2490 //look for any incomplete package installations 2491 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2492 for (int i = 0; i < deletePkgsList.size(); i++) { 2493 // Actual deletion of code and data will be handled by later 2494 // reconciliation step 2495 final String packageName = deletePkgsList.get(i).name; 2496 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2497 synchronized (mPackages) { 2498 mSettings.removePackageLPw(packageName); 2499 } 2500 } 2501 2502 //delete tmp files 2503 deleteTempPackageFiles(); 2504 2505 // Remove any shared userIDs that have no associated packages 2506 mSettings.pruneSharedUsersLPw(); 2507 2508 if (!mOnlyCore) { 2509 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2510 SystemClock.uptimeMillis()); 2511 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2512 2513 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2514 | PackageParser.PARSE_FORWARD_LOCK, 2515 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2516 2517 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2518 | PackageParser.PARSE_IS_EPHEMERAL, 2519 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2520 2521 /** 2522 * Remove disable package settings for any updated system 2523 * apps that were removed via an OTA. If they're not a 2524 * previously-updated app, remove them completely. 2525 * Otherwise, just revoke their system-level permissions. 2526 */ 2527 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2528 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2529 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2530 2531 String msg; 2532 if (deletedPkg == null) { 2533 msg = "Updated system package " + deletedAppName 2534 + " no longer exists; it's data will be wiped"; 2535 // Actual deletion of code and data will be handled by later 2536 // reconciliation step 2537 } else { 2538 msg = "Updated system app + " + deletedAppName 2539 + " no longer present; removing system privileges for " 2540 + deletedAppName; 2541 2542 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2543 2544 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2545 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2546 } 2547 logCriticalInfo(Log.WARN, msg); 2548 } 2549 2550 /** 2551 * Make sure all system apps that we expected to appear on 2552 * the userdata partition actually showed up. If they never 2553 * appeared, crawl back and revive the system version. 2554 */ 2555 for (int i = 0; i < mExpectingBetter.size(); i++) { 2556 final String packageName = mExpectingBetter.keyAt(i); 2557 if (!mPackages.containsKey(packageName)) { 2558 final File scanFile = mExpectingBetter.valueAt(i); 2559 2560 logCriticalInfo(Log.WARN, "Expected better " + packageName 2561 + " but never showed up; reverting to system"); 2562 2563 int reparseFlags = mDefParseFlags; 2564 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2565 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2566 | PackageParser.PARSE_IS_SYSTEM_DIR 2567 | PackageParser.PARSE_IS_PRIVILEGED; 2568 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2569 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2570 | PackageParser.PARSE_IS_SYSTEM_DIR; 2571 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2572 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2573 | PackageParser.PARSE_IS_SYSTEM_DIR; 2574 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2575 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2576 | PackageParser.PARSE_IS_SYSTEM_DIR; 2577 } else { 2578 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2579 continue; 2580 } 2581 2582 mSettings.enableSystemPackageLPw(packageName); 2583 2584 try { 2585 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2586 } catch (PackageManagerException e) { 2587 Slog.e(TAG, "Failed to parse original system package: " 2588 + e.getMessage()); 2589 } 2590 } 2591 } 2592 } 2593 mExpectingBetter.clear(); 2594 2595 // Resolve the storage manager. 2596 mStorageManagerPackage = getStorageManagerPackageName(); 2597 2598 // Resolve protected action filters. Only the setup wizard is allowed to 2599 // have a high priority filter for these actions. 2600 mSetupWizardPackage = getSetupWizardPackageName(); 2601 if (mProtectedFilters.size() > 0) { 2602 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2603 Slog.i(TAG, "No setup wizard;" 2604 + " All protected intents capped to priority 0"); 2605 } 2606 for (ActivityIntentInfo filter : mProtectedFilters) { 2607 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2608 if (DEBUG_FILTERS) { 2609 Slog.i(TAG, "Found setup wizard;" 2610 + " allow priority " + filter.getPriority() + ";" 2611 + " package: " + filter.activity.info.packageName 2612 + " activity: " + filter.activity.className 2613 + " priority: " + filter.getPriority()); 2614 } 2615 // skip setup wizard; allow it to keep the high priority filter 2616 continue; 2617 } 2618 Slog.w(TAG, "Protected action; cap priority to 0;" 2619 + " package: " + filter.activity.info.packageName 2620 + " activity: " + filter.activity.className 2621 + " origPrio: " + filter.getPriority()); 2622 filter.setPriority(0); 2623 } 2624 } 2625 mDeferProtectedFilters = false; 2626 mProtectedFilters.clear(); 2627 2628 // Now that we know all of the shared libraries, update all clients to have 2629 // the correct library paths. 2630 updateAllSharedLibrariesLPw(); 2631 2632 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2633 // NOTE: We ignore potential failures here during a system scan (like 2634 // the rest of the commands above) because there's precious little we 2635 // can do about it. A settings error is reported, though. 2636 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2637 } 2638 2639 // Now that we know all the packages we are keeping, 2640 // read and update their last usage times. 2641 mPackageUsage.read(mPackages); 2642 mCompilerStats.read(); 2643 2644 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2645 SystemClock.uptimeMillis()); 2646 Slog.i(TAG, "Time to scan packages: " 2647 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2648 + " seconds"); 2649 2650 // If the platform SDK has changed since the last time we booted, 2651 // we need to re-grant app permission to catch any new ones that 2652 // appear. This is really a hack, and means that apps can in some 2653 // cases get permissions that the user didn't initially explicitly 2654 // allow... it would be nice to have some better way to handle 2655 // this situation. 2656 int updateFlags = UPDATE_PERMISSIONS_ALL; 2657 if (ver.sdkVersion != mSdkVersion) { 2658 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2659 + mSdkVersion + "; regranting permissions for internal storage"); 2660 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2661 } 2662 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2663 ver.sdkVersion = mSdkVersion; 2664 2665 // If this is the first boot or an update from pre-M, and it is a normal 2666 // boot, then we need to initialize the default preferred apps across 2667 // all defined users. 2668 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2669 for (UserInfo user : sUserManager.getUsers(true)) { 2670 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2671 applyFactoryDefaultBrowserLPw(user.id); 2672 primeDomainVerificationsLPw(user.id); 2673 } 2674 } 2675 2676 // Prepare storage for system user really early during boot, 2677 // since core system apps like SettingsProvider and SystemUI 2678 // can't wait for user to start 2679 final int storageFlags; 2680 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2681 storageFlags = StorageManager.FLAG_STORAGE_DE; 2682 } else { 2683 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2684 } 2685 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2686 storageFlags, true /* migrateAppData */); 2687 2688 // If this is first boot after an OTA, and a normal boot, then 2689 // we need to clear code cache directories. 2690 // Note that we do *not* clear the application profiles. These remain valid 2691 // across OTAs and are used to drive profile verification (post OTA) and 2692 // profile compilation (without waiting to collect a fresh set of profiles). 2693 if (mIsUpgrade && !onlyCore) { 2694 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2695 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2696 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2697 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2698 // No apps are running this early, so no need to freeze 2699 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2700 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2701 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2702 } 2703 } 2704 ver.fingerprint = Build.FINGERPRINT; 2705 } 2706 2707 checkDefaultBrowser(); 2708 2709 // clear only after permissions and other defaults have been updated 2710 mExistingSystemPackages.clear(); 2711 mPromoteSystemApps = false; 2712 2713 // All the changes are done during package scanning. 2714 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2715 2716 // can downgrade to reader 2717 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2718 mSettings.writeLPr(); 2719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2720 2721 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2722 // early on (before the package manager declares itself as early) because other 2723 // components in the system server might ask for package contexts for these apps. 2724 // 2725 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2726 // (i.e, that the data partition is unavailable). 2727 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2728 long start = System.nanoTime(); 2729 List<PackageParser.Package> coreApps = new ArrayList<>(); 2730 for (PackageParser.Package pkg : mPackages.values()) { 2731 if (pkg.coreApp) { 2732 coreApps.add(pkg); 2733 } 2734 } 2735 2736 int[] stats = performDexOptUpgrade(coreApps, false, 2737 getCompilerFilterForReason(REASON_CORE_APP)); 2738 2739 final int elapsedTimeSeconds = 2740 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2741 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2742 2743 if (DEBUG_DEXOPT) { 2744 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2745 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2746 } 2747 2748 2749 // TODO: Should we log these stats to tron too ? 2750 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2751 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2752 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2753 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2754 } 2755 2756 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2757 SystemClock.uptimeMillis()); 2758 2759 if (!mOnlyCore) { 2760 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2761 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2762 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2763 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2764 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2765 mIntentFilterVerifierComponent); 2766 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2767 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2768 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2769 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2770 } else { 2771 mRequiredVerifierPackage = null; 2772 mRequiredInstallerPackage = null; 2773 mRequiredUninstallerPackage = null; 2774 mIntentFilterVerifierComponent = null; 2775 mIntentFilterVerifier = null; 2776 mServicesSystemSharedLibraryPackageName = null; 2777 mSharedSystemSharedLibraryPackageName = null; 2778 } 2779 2780 mInstallerService = new PackageInstallerService(context, this); 2781 2782 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2783 if (ephemeralResolverComponent != null) { 2784 if (DEBUG_EPHEMERAL) { 2785 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2786 } 2787 mEphemeralResolverConnection = 2788 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2789 } else { 2790 mEphemeralResolverConnection = null; 2791 } 2792 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2793 if (mEphemeralInstallerComponent != null) { 2794 if (DEBUG_EPHEMERAL) { 2795 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2796 } 2797 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2798 } 2799 2800 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2801 2802 // Read and update the usage of dex files. 2803 // Do this at the end of PM init so that all the packages have their 2804 // data directory reconciled. 2805 // At this point we know the code paths of the packages, so we can validate 2806 // the disk file and build the internal cache. 2807 // The usage file is expected to be small so loading and verifying it 2808 // should take a fairly small time compare to the other activities (e.g. package 2809 // scanning). 2810 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2811 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2812 for (int userId : currentUserIds) { 2813 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2814 } 2815 mDexManager.load(userPackages); 2816 } // synchronized (mPackages) 2817 } // synchronized (mInstallLock) 2818 2819 // Now after opening every single application zip, make sure they 2820 // are all flushed. Not really needed, but keeps things nice and 2821 // tidy. 2822 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2823 Runtime.getRuntime().gc(); 2824 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2825 2826 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2827 FallbackCategoryProvider.loadFallbacks(); 2828 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2829 2830 // The initial scanning above does many calls into installd while 2831 // holding the mPackages lock, but we're mostly interested in yelling 2832 // once we have a booted system. 2833 mInstaller.setWarnIfHeld(mPackages); 2834 2835 // Expose private service for system components to use. 2836 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2837 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2838 } 2839 2840 private static File preparePackageParserCache(boolean isUpgrade) { 2841 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2842 return null; 2843 } 2844 2845 // Disable package parsing on eng builds to allow for faster incremental development. 2846 if ("eng".equals(Build.TYPE)) { 2847 return null; 2848 } 2849 2850 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2851 Slog.i(TAG, "Disabling package parser cache due to system property."); 2852 return null; 2853 } 2854 2855 // The base directory for the package parser cache lives under /data/system/. 2856 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2857 "package_cache"); 2858 if (cacheBaseDir == null) { 2859 return null; 2860 } 2861 2862 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2863 // This also serves to "GC" unused entries when the package cache version changes (which 2864 // can only happen during upgrades). 2865 if (isUpgrade) { 2866 FileUtils.deleteContents(cacheBaseDir); 2867 } 2868 2869 2870 // Return the versioned package cache directory. This is something like 2871 // "/data/system/package_cache/1" 2872 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2873 2874 // The following is a workaround to aid development on non-numbered userdebug 2875 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2876 // the system partition is newer. 2877 // 2878 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2879 // that starts with "eng." to signify that this is an engineering build and not 2880 // destined for release. 2881 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2882 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2883 2884 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2885 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2886 // in general and should not be used for production changes. In this specific case, 2887 // we know that they will work. 2888 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2889 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2890 FileUtils.deleteContents(cacheBaseDir); 2891 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2892 } 2893 } 2894 2895 return cacheDir; 2896 } 2897 2898 @Override 2899 public boolean isFirstBoot() { 2900 return mFirstBoot; 2901 } 2902 2903 @Override 2904 public boolean isOnlyCoreApps() { 2905 return mOnlyCore; 2906 } 2907 2908 @Override 2909 public boolean isUpgrade() { 2910 return mIsUpgrade; 2911 } 2912 2913 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2914 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2915 2916 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2917 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2918 UserHandle.USER_SYSTEM); 2919 if (matches.size() == 1) { 2920 return matches.get(0).getComponentInfo().packageName; 2921 } else if (matches.size() == 0) { 2922 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2923 return null; 2924 } 2925 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2926 } 2927 2928 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2929 synchronized (mPackages) { 2930 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2931 if (libraryEntry == null) { 2932 throw new IllegalStateException("Missing required shared library:" + libraryName); 2933 } 2934 return libraryEntry.apk; 2935 } 2936 } 2937 2938 private @NonNull String getRequiredInstallerLPr() { 2939 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2940 intent.addCategory(Intent.CATEGORY_DEFAULT); 2941 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2942 2943 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2944 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2945 UserHandle.USER_SYSTEM); 2946 if (matches.size() == 1) { 2947 ResolveInfo resolveInfo = matches.get(0); 2948 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2949 throw new RuntimeException("The installer must be a privileged app"); 2950 } 2951 return matches.get(0).getComponentInfo().packageName; 2952 } else { 2953 throw new RuntimeException("There must be exactly one installer; found " + matches); 2954 } 2955 } 2956 2957 private @NonNull String getRequiredUninstallerLPr() { 2958 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2959 intent.addCategory(Intent.CATEGORY_DEFAULT); 2960 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2961 2962 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2963 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2964 UserHandle.USER_SYSTEM); 2965 if (resolveInfo == null || 2966 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2967 throw new RuntimeException("There must be exactly one uninstaller; found " 2968 + resolveInfo); 2969 } 2970 return resolveInfo.getComponentInfo().packageName; 2971 } 2972 2973 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2974 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2975 2976 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2977 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2978 UserHandle.USER_SYSTEM); 2979 ResolveInfo best = null; 2980 final int N = matches.size(); 2981 for (int i = 0; i < N; i++) { 2982 final ResolveInfo cur = matches.get(i); 2983 final String packageName = cur.getComponentInfo().packageName; 2984 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2985 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2986 continue; 2987 } 2988 2989 if (best == null || cur.priority > best.priority) { 2990 best = cur; 2991 } 2992 } 2993 2994 if (best != null) { 2995 return best.getComponentInfo().getComponentName(); 2996 } else { 2997 throw new RuntimeException("There must be at least one intent filter verifier"); 2998 } 2999 } 3000 3001 private @Nullable ComponentName getEphemeralResolverLPr() { 3002 final String[] packageArray = 3003 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3004 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3005 if (DEBUG_EPHEMERAL) { 3006 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3007 } 3008 return null; 3009 } 3010 3011 final int resolveFlags = 3012 MATCH_DIRECT_BOOT_AWARE 3013 | MATCH_DIRECT_BOOT_UNAWARE 3014 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3015 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3016 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3017 resolveFlags, UserHandle.USER_SYSTEM); 3018 3019 final int N = resolvers.size(); 3020 if (N == 0) { 3021 if (DEBUG_EPHEMERAL) { 3022 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3023 } 3024 return null; 3025 } 3026 3027 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3028 for (int i = 0; i < N; i++) { 3029 final ResolveInfo info = resolvers.get(i); 3030 3031 if (info.serviceInfo == null) { 3032 continue; 3033 } 3034 3035 final String packageName = info.serviceInfo.packageName; 3036 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3037 if (DEBUG_EPHEMERAL) { 3038 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3039 + " pkg: " + packageName + ", info:" + info); 3040 } 3041 continue; 3042 } 3043 3044 if (DEBUG_EPHEMERAL) { 3045 Slog.v(TAG, "Ephemeral resolver found;" 3046 + " pkg: " + packageName + ", info:" + info); 3047 } 3048 return new ComponentName(packageName, info.serviceInfo.name); 3049 } 3050 if (DEBUG_EPHEMERAL) { 3051 Slog.v(TAG, "Ephemeral resolver NOT found"); 3052 } 3053 return null; 3054 } 3055 3056 private @Nullable ComponentName getEphemeralInstallerLPr() { 3057 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3058 intent.addCategory(Intent.CATEGORY_DEFAULT); 3059 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3060 3061 final int resolveFlags = 3062 MATCH_DIRECT_BOOT_AWARE 3063 | MATCH_DIRECT_BOOT_UNAWARE 3064 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3065 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3066 resolveFlags, UserHandle.USER_SYSTEM); 3067 Iterator<ResolveInfo> iter = matches.iterator(); 3068 while (iter.hasNext()) { 3069 final ResolveInfo rInfo = iter.next(); 3070 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3071 if (ps != null) { 3072 final PermissionsState permissionsState = ps.getPermissionsState(); 3073 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3074 continue; 3075 } 3076 } 3077 iter.remove(); 3078 } 3079 if (matches.size() == 0) { 3080 return null; 3081 } else if (matches.size() == 1) { 3082 return matches.get(0).getComponentInfo().getComponentName(); 3083 } else { 3084 throw new RuntimeException( 3085 "There must be at most one ephemeral installer; found " + matches); 3086 } 3087 } 3088 3089 private void primeDomainVerificationsLPw(int userId) { 3090 if (DEBUG_DOMAIN_VERIFICATION) { 3091 Slog.d(TAG, "Priming domain verifications in user " + userId); 3092 } 3093 3094 SystemConfig systemConfig = SystemConfig.getInstance(); 3095 ArraySet<String> packages = systemConfig.getLinkedApps(); 3096 3097 for (String packageName : packages) { 3098 PackageParser.Package pkg = mPackages.get(packageName); 3099 if (pkg != null) { 3100 if (!pkg.isSystemApp()) { 3101 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3102 continue; 3103 } 3104 3105 ArraySet<String> domains = null; 3106 for (PackageParser.Activity a : pkg.activities) { 3107 for (ActivityIntentInfo filter : a.intents) { 3108 if (hasValidDomains(filter)) { 3109 if (domains == null) { 3110 domains = new ArraySet<String>(); 3111 } 3112 domains.addAll(filter.getHostsList()); 3113 } 3114 } 3115 } 3116 3117 if (domains != null && domains.size() > 0) { 3118 if (DEBUG_DOMAIN_VERIFICATION) { 3119 Slog.v(TAG, " + " + packageName); 3120 } 3121 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3122 // state w.r.t. the formal app-linkage "no verification attempted" state; 3123 // and then 'always' in the per-user state actually used for intent resolution. 3124 final IntentFilterVerificationInfo ivi; 3125 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3126 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3127 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3128 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3129 } else { 3130 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3131 + "' does not handle web links"); 3132 } 3133 } else { 3134 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3135 } 3136 } 3137 3138 scheduleWritePackageRestrictionsLocked(userId); 3139 scheduleWriteSettingsLocked(); 3140 } 3141 3142 private void applyFactoryDefaultBrowserLPw(int userId) { 3143 // The default browser app's package name is stored in a string resource, 3144 // with a product-specific overlay used for vendor customization. 3145 String browserPkg = mContext.getResources().getString( 3146 com.android.internal.R.string.default_browser); 3147 if (!TextUtils.isEmpty(browserPkg)) { 3148 // non-empty string => required to be a known package 3149 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3150 if (ps == null) { 3151 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3152 browserPkg = null; 3153 } else { 3154 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3155 } 3156 } 3157 3158 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3159 // default. If there's more than one, just leave everything alone. 3160 if (browserPkg == null) { 3161 calculateDefaultBrowserLPw(userId); 3162 } 3163 } 3164 3165 private void calculateDefaultBrowserLPw(int userId) { 3166 List<String> allBrowsers = resolveAllBrowserApps(userId); 3167 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3168 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3169 } 3170 3171 private List<String> resolveAllBrowserApps(int userId) { 3172 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3173 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3174 PackageManager.MATCH_ALL, userId); 3175 3176 final int count = list.size(); 3177 List<String> result = new ArrayList<String>(count); 3178 for (int i=0; i<count; i++) { 3179 ResolveInfo info = list.get(i); 3180 if (info.activityInfo == null 3181 || !info.handleAllWebDataURI 3182 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3183 || result.contains(info.activityInfo.packageName)) { 3184 continue; 3185 } 3186 result.add(info.activityInfo.packageName); 3187 } 3188 3189 return result; 3190 } 3191 3192 private boolean packageIsBrowser(String packageName, int userId) { 3193 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3194 PackageManager.MATCH_ALL, userId); 3195 final int N = list.size(); 3196 for (int i = 0; i < N; i++) { 3197 ResolveInfo info = list.get(i); 3198 if (packageName.equals(info.activityInfo.packageName)) { 3199 return true; 3200 } 3201 } 3202 return false; 3203 } 3204 3205 private void checkDefaultBrowser() { 3206 final int myUserId = UserHandle.myUserId(); 3207 final String packageName = getDefaultBrowserPackageName(myUserId); 3208 if (packageName != null) { 3209 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3210 if (info == null) { 3211 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3212 synchronized (mPackages) { 3213 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3214 } 3215 } 3216 } 3217 } 3218 3219 @Override 3220 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3221 throws RemoteException { 3222 try { 3223 return super.onTransact(code, data, reply, flags); 3224 } catch (RuntimeException e) { 3225 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3226 Slog.wtf(TAG, "Package Manager Crash", e); 3227 } 3228 throw e; 3229 } 3230 } 3231 3232 static int[] appendInts(int[] cur, int[] add) { 3233 if (add == null) return cur; 3234 if (cur == null) return add; 3235 final int N = add.length; 3236 for (int i=0; i<N; i++) { 3237 cur = appendInt(cur, add[i]); 3238 } 3239 return cur; 3240 } 3241 3242 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3243 if (!sUserManager.exists(userId)) return null; 3244 if (ps == null) { 3245 return null; 3246 } 3247 final PackageParser.Package p = ps.pkg; 3248 if (p == null) { 3249 return null; 3250 } 3251 3252 final PermissionsState permissionsState = ps.getPermissionsState(); 3253 3254 // Compute GIDs only if requested 3255 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3256 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3257 // Compute granted permissions only if package has requested permissions 3258 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3259 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3260 final PackageUserState state = ps.readUserState(userId); 3261 3262 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3263 && ps.isSystem()) { 3264 flags |= MATCH_ANY_USER; 3265 } 3266 3267 return PackageParser.generatePackageInfo(p, gids, flags, 3268 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3269 } 3270 3271 @Override 3272 public void checkPackageStartable(String packageName, int userId) { 3273 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3274 3275 synchronized (mPackages) { 3276 final PackageSetting ps = mSettings.mPackages.get(packageName); 3277 if (ps == null) { 3278 throw new SecurityException("Package " + packageName + " was not found!"); 3279 } 3280 3281 if (!ps.getInstalled(userId)) { 3282 throw new SecurityException( 3283 "Package " + packageName + " was not installed for user " + userId + "!"); 3284 } 3285 3286 if (mSafeMode && !ps.isSystem()) { 3287 throw new SecurityException("Package " + packageName + " not a system app!"); 3288 } 3289 3290 if (mFrozenPackages.contains(packageName)) { 3291 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3292 } 3293 3294 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3295 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3296 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3297 } 3298 } 3299 } 3300 3301 @Override 3302 public boolean isPackageAvailable(String packageName, int userId) { 3303 if (!sUserManager.exists(userId)) return false; 3304 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3305 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3306 synchronized (mPackages) { 3307 PackageParser.Package p = mPackages.get(packageName); 3308 if (p != null) { 3309 final PackageSetting ps = (PackageSetting) p.mExtras; 3310 if (ps != null) { 3311 final PackageUserState state = ps.readUserState(userId); 3312 if (state != null) { 3313 return PackageParser.isAvailable(state); 3314 } 3315 } 3316 } 3317 } 3318 return false; 3319 } 3320 3321 @Override 3322 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3323 if (!sUserManager.exists(userId)) return null; 3324 flags = updateFlagsForPackage(flags, userId, packageName); 3325 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3326 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3327 3328 // reader 3329 synchronized (mPackages) { 3330 // Normalize package name to hanlde renamed packages 3331 packageName = normalizePackageNameLPr(packageName); 3332 3333 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3334 PackageParser.Package p = null; 3335 if (matchFactoryOnly) { 3336 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3337 if (ps != null) { 3338 return generatePackageInfo(ps, flags, userId); 3339 } 3340 } 3341 if (p == null) { 3342 p = mPackages.get(packageName); 3343 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3344 return null; 3345 } 3346 } 3347 if (DEBUG_PACKAGE_INFO) 3348 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3349 if (p != null) { 3350 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3351 } 3352 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3353 final PackageSetting ps = mSettings.mPackages.get(packageName); 3354 return generatePackageInfo(ps, flags, userId); 3355 } 3356 } 3357 return null; 3358 } 3359 3360 @Override 3361 public String[] currentToCanonicalPackageNames(String[] names) { 3362 String[] out = new String[names.length]; 3363 // reader 3364 synchronized (mPackages) { 3365 for (int i=names.length-1; i>=0; i--) { 3366 PackageSetting ps = mSettings.mPackages.get(names[i]); 3367 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3368 } 3369 } 3370 return out; 3371 } 3372 3373 @Override 3374 public String[] canonicalToCurrentPackageNames(String[] names) { 3375 String[] out = new String[names.length]; 3376 // reader 3377 synchronized (mPackages) { 3378 for (int i=names.length-1; i>=0; i--) { 3379 String cur = mSettings.getRenamedPackageLPr(names[i]); 3380 out[i] = cur != null ? cur : names[i]; 3381 } 3382 } 3383 return out; 3384 } 3385 3386 @Override 3387 public int getPackageUid(String packageName, int flags, int userId) { 3388 if (!sUserManager.exists(userId)) return -1; 3389 flags = updateFlagsForPackage(flags, userId, packageName); 3390 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3391 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3392 3393 // reader 3394 synchronized (mPackages) { 3395 final PackageParser.Package p = mPackages.get(packageName); 3396 if (p != null && p.isMatch(flags)) { 3397 return UserHandle.getUid(userId, p.applicationInfo.uid); 3398 } 3399 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3400 final PackageSetting ps = mSettings.mPackages.get(packageName); 3401 if (ps != null && ps.isMatch(flags)) { 3402 return UserHandle.getUid(userId, ps.appId); 3403 } 3404 } 3405 } 3406 3407 return -1; 3408 } 3409 3410 @Override 3411 public int[] getPackageGids(String packageName, int flags, int userId) { 3412 if (!sUserManager.exists(userId)) return null; 3413 flags = updateFlagsForPackage(flags, userId, packageName); 3414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3415 false /* requireFullPermission */, false /* checkShell */, 3416 "getPackageGids"); 3417 3418 // reader 3419 synchronized (mPackages) { 3420 final PackageParser.Package p = mPackages.get(packageName); 3421 if (p != null && p.isMatch(flags)) { 3422 PackageSetting ps = (PackageSetting) p.mExtras; 3423 // TODO: Shouldn't this be checking for package installed state for userId and 3424 // return null? 3425 return ps.getPermissionsState().computeGids(userId); 3426 } 3427 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3428 final PackageSetting ps = mSettings.mPackages.get(packageName); 3429 if (ps != null && ps.isMatch(flags)) { 3430 return ps.getPermissionsState().computeGids(userId); 3431 } 3432 } 3433 } 3434 3435 return null; 3436 } 3437 3438 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3439 if (bp.perm != null) { 3440 return PackageParser.generatePermissionInfo(bp.perm, flags); 3441 } 3442 PermissionInfo pi = new PermissionInfo(); 3443 pi.name = bp.name; 3444 pi.packageName = bp.sourcePackage; 3445 pi.nonLocalizedLabel = bp.name; 3446 pi.protectionLevel = bp.protectionLevel; 3447 return pi; 3448 } 3449 3450 @Override 3451 public PermissionInfo getPermissionInfo(String name, int flags) { 3452 // reader 3453 synchronized (mPackages) { 3454 final BasePermission p = mSettings.mPermissions.get(name); 3455 if (p != null) { 3456 return generatePermissionInfo(p, flags); 3457 } 3458 return null; 3459 } 3460 } 3461 3462 @Override 3463 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3464 int flags) { 3465 // reader 3466 synchronized (mPackages) { 3467 if (group != null && !mPermissionGroups.containsKey(group)) { 3468 // This is thrown as NameNotFoundException 3469 return null; 3470 } 3471 3472 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3473 for (BasePermission p : mSettings.mPermissions.values()) { 3474 if (group == null) { 3475 if (p.perm == null || p.perm.info.group == null) { 3476 out.add(generatePermissionInfo(p, flags)); 3477 } 3478 } else { 3479 if (p.perm != null && group.equals(p.perm.info.group)) { 3480 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3481 } 3482 } 3483 } 3484 return new ParceledListSlice<>(out); 3485 } 3486 } 3487 3488 @Override 3489 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3490 // reader 3491 synchronized (mPackages) { 3492 return PackageParser.generatePermissionGroupInfo( 3493 mPermissionGroups.get(name), flags); 3494 } 3495 } 3496 3497 @Override 3498 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3499 // reader 3500 synchronized (mPackages) { 3501 final int N = mPermissionGroups.size(); 3502 ArrayList<PermissionGroupInfo> out 3503 = new ArrayList<PermissionGroupInfo>(N); 3504 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3505 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3506 } 3507 return new ParceledListSlice<>(out); 3508 } 3509 } 3510 3511 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3512 int userId) { 3513 if (!sUserManager.exists(userId)) return null; 3514 PackageSetting ps = mSettings.mPackages.get(packageName); 3515 if (ps != null) { 3516 if (ps.pkg == null) { 3517 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3518 if (pInfo != null) { 3519 return pInfo.applicationInfo; 3520 } 3521 return null; 3522 } 3523 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3524 ps.readUserState(userId), userId); 3525 } 3526 return null; 3527 } 3528 3529 @Override 3530 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3531 if (!sUserManager.exists(userId)) return null; 3532 flags = updateFlagsForApplication(flags, userId, packageName); 3533 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3534 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3535 3536 // writer 3537 synchronized (mPackages) { 3538 // Normalize package name to hanlde renamed packages 3539 packageName = normalizePackageNameLPr(packageName); 3540 3541 PackageParser.Package p = mPackages.get(packageName); 3542 if (DEBUG_PACKAGE_INFO) Log.v( 3543 TAG, "getApplicationInfo " + packageName 3544 + ": " + p); 3545 if (p != null) { 3546 PackageSetting ps = mSettings.mPackages.get(packageName); 3547 if (ps == null) return null; 3548 // Note: isEnabledLP() does not apply here - always return info 3549 return PackageParser.generateApplicationInfo( 3550 p, flags, ps.readUserState(userId), userId); 3551 } 3552 if ("android".equals(packageName)||"system".equals(packageName)) { 3553 return mAndroidApplication; 3554 } 3555 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3556 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3557 } 3558 } 3559 return null; 3560 } 3561 3562 private String normalizePackageNameLPr(String packageName) { 3563 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3564 return normalizedPackageName != null ? normalizedPackageName : packageName; 3565 } 3566 3567 @Override 3568 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3569 final IPackageDataObserver observer) { 3570 mContext.enforceCallingOrSelfPermission( 3571 android.Manifest.permission.CLEAR_APP_CACHE, null); 3572 // Queue up an async operation since clearing cache may take a little while. 3573 mHandler.post(new Runnable() { 3574 public void run() { 3575 mHandler.removeCallbacks(this); 3576 boolean success = true; 3577 synchronized (mInstallLock) { 3578 try { 3579 mInstaller.freeCache(volumeUuid, freeStorageSize); 3580 } catch (InstallerException e) { 3581 Slog.w(TAG, "Couldn't clear application caches: " + e); 3582 success = false; 3583 } 3584 } 3585 if (observer != null) { 3586 try { 3587 observer.onRemoveCompleted(null, success); 3588 } catch (RemoteException e) { 3589 Slog.w(TAG, "RemoveException when invoking call back"); 3590 } 3591 } 3592 } 3593 }); 3594 } 3595 3596 @Override 3597 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3598 final IntentSender pi) { 3599 mContext.enforceCallingOrSelfPermission( 3600 android.Manifest.permission.CLEAR_APP_CACHE, null); 3601 // Queue up an async operation since clearing cache may take a little while. 3602 mHandler.post(new Runnable() { 3603 public void run() { 3604 mHandler.removeCallbacks(this); 3605 boolean success = true; 3606 synchronized (mInstallLock) { 3607 try { 3608 mInstaller.freeCache(volumeUuid, freeStorageSize); 3609 } catch (InstallerException e) { 3610 Slog.w(TAG, "Couldn't clear application caches: " + e); 3611 success = false; 3612 } 3613 } 3614 if(pi != null) { 3615 try { 3616 // Callback via pending intent 3617 int code = success ? 1 : 0; 3618 pi.sendIntent(null, code, null, 3619 null, null); 3620 } catch (SendIntentException e1) { 3621 Slog.i(TAG, "Failed to send pending intent"); 3622 } 3623 } 3624 } 3625 }); 3626 } 3627 3628 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3629 synchronized (mInstallLock) { 3630 try { 3631 mInstaller.freeCache(volumeUuid, freeStorageSize); 3632 } catch (InstallerException e) { 3633 throw new IOException("Failed to free enough space", e); 3634 } 3635 } 3636 } 3637 3638 /** 3639 * Update given flags based on encryption status of current user. 3640 */ 3641 private int updateFlags(int flags, int userId) { 3642 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3643 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3644 // Caller expressed an explicit opinion about what encryption 3645 // aware/unaware components they want to see, so fall through and 3646 // give them what they want 3647 } else { 3648 // Caller expressed no opinion, so match based on user state 3649 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3650 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3651 } else { 3652 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3653 } 3654 } 3655 return flags; 3656 } 3657 3658 private UserManagerInternal getUserManagerInternal() { 3659 if (mUserManagerInternal == null) { 3660 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3661 } 3662 return mUserManagerInternal; 3663 } 3664 3665 /** 3666 * Update given flags when being used to request {@link PackageInfo}. 3667 */ 3668 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3669 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3670 boolean triaged = true; 3671 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3672 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3673 // Caller is asking for component details, so they'd better be 3674 // asking for specific encryption matching behavior, or be triaged 3675 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3676 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3677 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3678 triaged = false; 3679 } 3680 } 3681 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3682 | PackageManager.MATCH_SYSTEM_ONLY 3683 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3684 triaged = false; 3685 } 3686 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3687 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3688 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3689 + Debug.getCallers(5)); 3690 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3691 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3692 // If the caller wants all packages and has a restricted profile associated with it, 3693 // then match all users. This is to make sure that launchers that need to access work 3694 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3695 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3696 flags |= PackageManager.MATCH_ANY_USER; 3697 } 3698 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3699 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3700 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3701 } 3702 return updateFlags(flags, userId); 3703 } 3704 3705 /** 3706 * Update given flags when being used to request {@link ApplicationInfo}. 3707 */ 3708 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3709 return updateFlagsForPackage(flags, userId, cookie); 3710 } 3711 3712 /** 3713 * Update given flags when being used to request {@link ComponentInfo}. 3714 */ 3715 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3716 if (cookie instanceof Intent) { 3717 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3718 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3719 } 3720 } 3721 3722 boolean triaged = true; 3723 // Caller is asking for component details, so they'd better be 3724 // asking for specific encryption matching behavior, or be triaged 3725 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3726 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3727 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3728 triaged = false; 3729 } 3730 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3731 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3732 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3733 } 3734 3735 return updateFlags(flags, userId); 3736 } 3737 3738 /** 3739 * Update given flags when being used to request {@link ResolveInfo}. 3740 */ 3741 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3742 // Safe mode means we shouldn't match any third-party components 3743 if (mSafeMode) { 3744 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3745 } 3746 final int callingUid = Binder.getCallingUid(); 3747 if (callingUid == Process.SYSTEM_UID || callingUid == 0) { 3748 // The system sees all components 3749 flags |= PackageManager.MATCH_EPHEMERAL; 3750 } else if (getEphemeralPackageName(callingUid) != null) { 3751 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3752 flags |= PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3753 flags |= PackageManager.MATCH_EPHEMERAL; 3754 } else { 3755 // Otherwise, prevent leaking ephemeral components 3756 flags &= ~PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY; 3757 flags &= ~PackageManager.MATCH_EPHEMERAL; 3758 } 3759 return updateFlagsForComponent(flags, userId, cookie); 3760 } 3761 3762 @Override 3763 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3764 if (!sUserManager.exists(userId)) return null; 3765 flags = updateFlagsForComponent(flags, userId, component); 3766 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3767 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3768 synchronized (mPackages) { 3769 PackageParser.Activity a = mActivities.mActivities.get(component); 3770 3771 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3772 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3773 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3774 if (ps == null) return null; 3775 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3776 userId); 3777 } 3778 if (mResolveComponentName.equals(component)) { 3779 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3780 new PackageUserState(), userId); 3781 } 3782 } 3783 return null; 3784 } 3785 3786 @Override 3787 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3788 String resolvedType) { 3789 synchronized (mPackages) { 3790 if (component.equals(mResolveComponentName)) { 3791 // The resolver supports EVERYTHING! 3792 return true; 3793 } 3794 PackageParser.Activity a = mActivities.mActivities.get(component); 3795 if (a == null) { 3796 return false; 3797 } 3798 for (int i=0; i<a.intents.size(); i++) { 3799 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3800 intent.getData(), intent.getCategories(), TAG) >= 0) { 3801 return true; 3802 } 3803 } 3804 return false; 3805 } 3806 } 3807 3808 @Override 3809 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3810 if (!sUserManager.exists(userId)) return null; 3811 flags = updateFlagsForComponent(flags, userId, component); 3812 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3813 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3814 synchronized (mPackages) { 3815 PackageParser.Activity a = mReceivers.mActivities.get(component); 3816 if (DEBUG_PACKAGE_INFO) Log.v( 3817 TAG, "getReceiverInfo " + component + ": " + a); 3818 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3819 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3820 if (ps == null) return null; 3821 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3822 userId); 3823 } 3824 } 3825 return null; 3826 } 3827 3828 @Override 3829 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3830 if (!sUserManager.exists(userId)) return null; 3831 flags = updateFlagsForComponent(flags, userId, component); 3832 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3833 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3834 synchronized (mPackages) { 3835 PackageParser.Service s = mServices.mServices.get(component); 3836 if (DEBUG_PACKAGE_INFO) Log.v( 3837 TAG, "getServiceInfo " + component + ": " + s); 3838 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3839 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3840 if (ps == null) return null; 3841 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3842 userId); 3843 } 3844 } 3845 return null; 3846 } 3847 3848 @Override 3849 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3850 if (!sUserManager.exists(userId)) return null; 3851 flags = updateFlagsForComponent(flags, userId, component); 3852 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3853 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3854 synchronized (mPackages) { 3855 PackageParser.Provider p = mProviders.mProviders.get(component); 3856 if (DEBUG_PACKAGE_INFO) Log.v( 3857 TAG, "getProviderInfo " + component + ": " + p); 3858 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3859 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3860 if (ps == null) return null; 3861 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3862 userId); 3863 } 3864 } 3865 return null; 3866 } 3867 3868 @Override 3869 public String[] getSystemSharedLibraryNames() { 3870 Set<String> libSet; 3871 synchronized (mPackages) { 3872 libSet = mSharedLibraries.keySet(); 3873 int size = libSet.size(); 3874 if (size > 0) { 3875 String[] libs = new String[size]; 3876 libSet.toArray(libs); 3877 return libs; 3878 } 3879 } 3880 return null; 3881 } 3882 3883 @Override 3884 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3885 synchronized (mPackages) { 3886 return mServicesSystemSharedLibraryPackageName; 3887 } 3888 } 3889 3890 @Override 3891 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3892 synchronized (mPackages) { 3893 return mSharedSystemSharedLibraryPackageName; 3894 } 3895 } 3896 3897 @Override 3898 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3899 synchronized (mPackages) { 3900 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3901 3902 final FeatureInfo fi = new FeatureInfo(); 3903 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3904 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3905 res.add(fi); 3906 3907 return new ParceledListSlice<>(res); 3908 } 3909 } 3910 3911 @Override 3912 public boolean hasSystemFeature(String name, int version) { 3913 synchronized (mPackages) { 3914 final FeatureInfo feat = mAvailableFeatures.get(name); 3915 if (feat == null) { 3916 return false; 3917 } else { 3918 return feat.version >= version; 3919 } 3920 } 3921 } 3922 3923 @Override 3924 public int checkPermission(String permName, String pkgName, int userId) { 3925 if (!sUserManager.exists(userId)) { 3926 return PackageManager.PERMISSION_DENIED; 3927 } 3928 3929 synchronized (mPackages) { 3930 final PackageParser.Package p = mPackages.get(pkgName); 3931 if (p != null && p.mExtras != null) { 3932 final PackageSetting ps = (PackageSetting) p.mExtras; 3933 final PermissionsState permissionsState = ps.getPermissionsState(); 3934 if (permissionsState.hasPermission(permName, userId)) { 3935 return PackageManager.PERMISSION_GRANTED; 3936 } 3937 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3938 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3939 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3940 return PackageManager.PERMISSION_GRANTED; 3941 } 3942 } 3943 } 3944 3945 return PackageManager.PERMISSION_DENIED; 3946 } 3947 3948 @Override 3949 public int checkUidPermission(String permName, int uid) { 3950 final int userId = UserHandle.getUserId(uid); 3951 3952 if (!sUserManager.exists(userId)) { 3953 return PackageManager.PERMISSION_DENIED; 3954 } 3955 3956 synchronized (mPackages) { 3957 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3958 if (obj != null) { 3959 final SettingBase ps = (SettingBase) obj; 3960 final PermissionsState permissionsState = ps.getPermissionsState(); 3961 if (permissionsState.hasPermission(permName, userId)) { 3962 return PackageManager.PERMISSION_GRANTED; 3963 } 3964 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3965 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3966 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3967 return PackageManager.PERMISSION_GRANTED; 3968 } 3969 } else { 3970 ArraySet<String> perms = mSystemPermissions.get(uid); 3971 if (perms != null) { 3972 if (perms.contains(permName)) { 3973 return PackageManager.PERMISSION_GRANTED; 3974 } 3975 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3976 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3977 return PackageManager.PERMISSION_GRANTED; 3978 } 3979 } 3980 } 3981 } 3982 3983 return PackageManager.PERMISSION_DENIED; 3984 } 3985 3986 @Override 3987 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3988 if (UserHandle.getCallingUserId() != userId) { 3989 mContext.enforceCallingPermission( 3990 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3991 "isPermissionRevokedByPolicy for user " + userId); 3992 } 3993 3994 if (checkPermission(permission, packageName, userId) 3995 == PackageManager.PERMISSION_GRANTED) { 3996 return false; 3997 } 3998 3999 final long identity = Binder.clearCallingIdentity(); 4000 try { 4001 final int flags = getPermissionFlags(permission, packageName, userId); 4002 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4003 } finally { 4004 Binder.restoreCallingIdentity(identity); 4005 } 4006 } 4007 4008 @Override 4009 public String getPermissionControllerPackageName() { 4010 synchronized (mPackages) { 4011 return mRequiredInstallerPackage; 4012 } 4013 } 4014 4015 /** 4016 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4017 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4018 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4019 * @param message the message to log on security exception 4020 */ 4021 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4022 boolean checkShell, String message) { 4023 if (userId < 0) { 4024 throw new IllegalArgumentException("Invalid userId " + userId); 4025 } 4026 if (checkShell) { 4027 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4028 } 4029 if (userId == UserHandle.getUserId(callingUid)) return; 4030 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4031 if (requireFullPermission) { 4032 mContext.enforceCallingOrSelfPermission( 4033 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4034 } else { 4035 try { 4036 mContext.enforceCallingOrSelfPermission( 4037 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4038 } catch (SecurityException se) { 4039 mContext.enforceCallingOrSelfPermission( 4040 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4041 } 4042 } 4043 } 4044 } 4045 4046 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4047 if (callingUid == Process.SHELL_UID) { 4048 if (userHandle >= 0 4049 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4050 throw new SecurityException("Shell does not have permission to access user " 4051 + userHandle); 4052 } else if (userHandle < 0) { 4053 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4054 + Debug.getCallers(3)); 4055 } 4056 } 4057 } 4058 4059 private BasePermission findPermissionTreeLP(String permName) { 4060 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4061 if (permName.startsWith(bp.name) && 4062 permName.length() > bp.name.length() && 4063 permName.charAt(bp.name.length()) == '.') { 4064 return bp; 4065 } 4066 } 4067 return null; 4068 } 4069 4070 private BasePermission checkPermissionTreeLP(String permName) { 4071 if (permName != null) { 4072 BasePermission bp = findPermissionTreeLP(permName); 4073 if (bp != null) { 4074 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4075 return bp; 4076 } 4077 throw new SecurityException("Calling uid " 4078 + Binder.getCallingUid() 4079 + " is not allowed to add to permission tree " 4080 + bp.name + " owned by uid " + bp.uid); 4081 } 4082 } 4083 throw new SecurityException("No permission tree found for " + permName); 4084 } 4085 4086 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4087 if (s1 == null) { 4088 return s2 == null; 4089 } 4090 if (s2 == null) { 4091 return false; 4092 } 4093 if (s1.getClass() != s2.getClass()) { 4094 return false; 4095 } 4096 return s1.equals(s2); 4097 } 4098 4099 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4100 if (pi1.icon != pi2.icon) return false; 4101 if (pi1.logo != pi2.logo) return false; 4102 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4103 if (!compareStrings(pi1.name, pi2.name)) return false; 4104 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4105 // We'll take care of setting this one. 4106 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4107 // These are not currently stored in settings. 4108 //if (!compareStrings(pi1.group, pi2.group)) return false; 4109 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4110 //if (pi1.labelRes != pi2.labelRes) return false; 4111 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4112 return true; 4113 } 4114 4115 int permissionInfoFootprint(PermissionInfo info) { 4116 int size = info.name.length(); 4117 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4118 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4119 return size; 4120 } 4121 4122 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4123 int size = 0; 4124 for (BasePermission perm : mSettings.mPermissions.values()) { 4125 if (perm.uid == tree.uid) { 4126 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4127 } 4128 } 4129 return size; 4130 } 4131 4132 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4133 // We calculate the max size of permissions defined by this uid and throw 4134 // if that plus the size of 'info' would exceed our stated maximum. 4135 if (tree.uid != Process.SYSTEM_UID) { 4136 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4137 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4138 throw new SecurityException("Permission tree size cap exceeded"); 4139 } 4140 } 4141 } 4142 4143 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4144 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4145 throw new SecurityException("Label must be specified in permission"); 4146 } 4147 BasePermission tree = checkPermissionTreeLP(info.name); 4148 BasePermission bp = mSettings.mPermissions.get(info.name); 4149 boolean added = bp == null; 4150 boolean changed = true; 4151 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4152 if (added) { 4153 enforcePermissionCapLocked(info, tree); 4154 bp = new BasePermission(info.name, tree.sourcePackage, 4155 BasePermission.TYPE_DYNAMIC); 4156 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4157 throw new SecurityException( 4158 "Not allowed to modify non-dynamic permission " 4159 + info.name); 4160 } else { 4161 if (bp.protectionLevel == fixedLevel 4162 && bp.perm.owner.equals(tree.perm.owner) 4163 && bp.uid == tree.uid 4164 && comparePermissionInfos(bp.perm.info, info)) { 4165 changed = false; 4166 } 4167 } 4168 bp.protectionLevel = fixedLevel; 4169 info = new PermissionInfo(info); 4170 info.protectionLevel = fixedLevel; 4171 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4172 bp.perm.info.packageName = tree.perm.info.packageName; 4173 bp.uid = tree.uid; 4174 if (added) { 4175 mSettings.mPermissions.put(info.name, bp); 4176 } 4177 if (changed) { 4178 if (!async) { 4179 mSettings.writeLPr(); 4180 } else { 4181 scheduleWriteSettingsLocked(); 4182 } 4183 } 4184 return added; 4185 } 4186 4187 @Override 4188 public boolean addPermission(PermissionInfo info) { 4189 synchronized (mPackages) { 4190 return addPermissionLocked(info, false); 4191 } 4192 } 4193 4194 @Override 4195 public boolean addPermissionAsync(PermissionInfo info) { 4196 synchronized (mPackages) { 4197 return addPermissionLocked(info, true); 4198 } 4199 } 4200 4201 @Override 4202 public void removePermission(String name) { 4203 synchronized (mPackages) { 4204 checkPermissionTreeLP(name); 4205 BasePermission bp = mSettings.mPermissions.get(name); 4206 if (bp != null) { 4207 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4208 throw new SecurityException( 4209 "Not allowed to modify non-dynamic permission " 4210 + name); 4211 } 4212 mSettings.mPermissions.remove(name); 4213 mSettings.writeLPr(); 4214 } 4215 } 4216 } 4217 4218 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4219 BasePermission bp) { 4220 int index = pkg.requestedPermissions.indexOf(bp.name); 4221 if (index == -1) { 4222 throw new SecurityException("Package " + pkg.packageName 4223 + " has not requested permission " + bp.name); 4224 } 4225 if (!bp.isRuntime() && !bp.isDevelopment()) { 4226 throw new SecurityException("Permission " + bp.name 4227 + " is not a changeable permission type"); 4228 } 4229 } 4230 4231 @Override 4232 public void grantRuntimePermission(String packageName, String name, final int userId) { 4233 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4234 } 4235 4236 private void grantRuntimePermission(String packageName, String name, final int userId, 4237 boolean overridePolicy) { 4238 if (!sUserManager.exists(userId)) { 4239 Log.e(TAG, "No such user:" + userId); 4240 return; 4241 } 4242 4243 mContext.enforceCallingOrSelfPermission( 4244 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4245 "grantRuntimePermission"); 4246 4247 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4248 true /* requireFullPermission */, true /* checkShell */, 4249 "grantRuntimePermission"); 4250 4251 final int uid; 4252 final SettingBase sb; 4253 4254 synchronized (mPackages) { 4255 final PackageParser.Package pkg = mPackages.get(packageName); 4256 if (pkg == null) { 4257 throw new IllegalArgumentException("Unknown package: " + packageName); 4258 } 4259 4260 final BasePermission bp = mSettings.mPermissions.get(name); 4261 if (bp == null) { 4262 throw new IllegalArgumentException("Unknown permission: " + name); 4263 } 4264 4265 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4266 4267 // If a permission review is required for legacy apps we represent 4268 // their permissions as always granted runtime ones since we need 4269 // to keep the review required permission flag per user while an 4270 // install permission's state is shared across all users. 4271 if (mPermissionReviewRequired 4272 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4273 && bp.isRuntime()) { 4274 return; 4275 } 4276 4277 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4278 sb = (SettingBase) pkg.mExtras; 4279 if (sb == null) { 4280 throw new IllegalArgumentException("Unknown package: " + packageName); 4281 } 4282 4283 final PermissionsState permissionsState = sb.getPermissionsState(); 4284 4285 final int flags = permissionsState.getPermissionFlags(name, userId); 4286 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4287 throw new SecurityException("Cannot grant system fixed permission " 4288 + name + " for package " + packageName); 4289 } 4290 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4291 throw new SecurityException("Cannot grant policy fixed permission " 4292 + name + " for package " + packageName); 4293 } 4294 4295 if (bp.isDevelopment()) { 4296 // Development permissions must be handled specially, since they are not 4297 // normal runtime permissions. For now they apply to all users. 4298 if (permissionsState.grantInstallPermission(bp) != 4299 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4300 scheduleWriteSettingsLocked(); 4301 } 4302 return; 4303 } 4304 4305 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4306 throw new SecurityException("Cannot grant non-ephemeral permission" 4307 + name + " for package " + packageName); 4308 } 4309 4310 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4311 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4312 return; 4313 } 4314 4315 final int result = permissionsState.grantRuntimePermission(bp, userId); 4316 switch (result) { 4317 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4318 return; 4319 } 4320 4321 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4322 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4323 mHandler.post(new Runnable() { 4324 @Override 4325 public void run() { 4326 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4327 } 4328 }); 4329 } 4330 break; 4331 } 4332 4333 if (bp.isRuntime()) { 4334 logPermissionGranted(mContext, name, packageName); 4335 } 4336 4337 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4338 4339 // Not critical if that is lost - app has to request again. 4340 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4341 } 4342 4343 // Only need to do this if user is initialized. Otherwise it's a new user 4344 // and there are no processes running as the user yet and there's no need 4345 // to make an expensive call to remount processes for the changed permissions. 4346 if (READ_EXTERNAL_STORAGE.equals(name) 4347 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4348 final long token = Binder.clearCallingIdentity(); 4349 try { 4350 if (sUserManager.isInitialized(userId)) { 4351 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4352 StorageManagerInternal.class); 4353 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4354 } 4355 } finally { 4356 Binder.restoreCallingIdentity(token); 4357 } 4358 } 4359 } 4360 4361 @Override 4362 public void revokeRuntimePermission(String packageName, String name, int userId) { 4363 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4364 } 4365 4366 private void revokeRuntimePermission(String packageName, String name, int userId, 4367 boolean overridePolicy) { 4368 if (!sUserManager.exists(userId)) { 4369 Log.e(TAG, "No such user:" + userId); 4370 return; 4371 } 4372 4373 mContext.enforceCallingOrSelfPermission( 4374 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4375 "revokeRuntimePermission"); 4376 4377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4378 true /* requireFullPermission */, true /* checkShell */, 4379 "revokeRuntimePermission"); 4380 4381 final int appId; 4382 4383 synchronized (mPackages) { 4384 final PackageParser.Package pkg = mPackages.get(packageName); 4385 if (pkg == null) { 4386 throw new IllegalArgumentException("Unknown package: " + packageName); 4387 } 4388 4389 final BasePermission bp = mSettings.mPermissions.get(name); 4390 if (bp == null) { 4391 throw new IllegalArgumentException("Unknown permission: " + name); 4392 } 4393 4394 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4395 4396 // If a permission review is required for legacy apps we represent 4397 // their permissions as always granted runtime ones since we need 4398 // to keep the review required permission flag per user while an 4399 // install permission's state is shared across all users. 4400 if (mPermissionReviewRequired 4401 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4402 && bp.isRuntime()) { 4403 return; 4404 } 4405 4406 SettingBase sb = (SettingBase) pkg.mExtras; 4407 if (sb == null) { 4408 throw new IllegalArgumentException("Unknown package: " + packageName); 4409 } 4410 4411 final PermissionsState permissionsState = sb.getPermissionsState(); 4412 4413 final int flags = permissionsState.getPermissionFlags(name, userId); 4414 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4415 throw new SecurityException("Cannot revoke system fixed permission " 4416 + name + " for package " + packageName); 4417 } 4418 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4419 throw new SecurityException("Cannot revoke policy fixed permission " 4420 + name + " for package " + packageName); 4421 } 4422 4423 if (bp.isDevelopment()) { 4424 // Development permissions must be handled specially, since they are not 4425 // normal runtime permissions. For now they apply to all users. 4426 if (permissionsState.revokeInstallPermission(bp) != 4427 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4428 scheduleWriteSettingsLocked(); 4429 } 4430 return; 4431 } 4432 4433 if (permissionsState.revokeRuntimePermission(bp, userId) == 4434 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4435 return; 4436 } 4437 4438 if (bp.isRuntime()) { 4439 logPermissionRevoked(mContext, name, packageName); 4440 } 4441 4442 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4443 4444 // Critical, after this call app should never have the permission. 4445 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4446 4447 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4448 } 4449 4450 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4451 } 4452 4453 /** 4454 * Get the first event id for the permission. 4455 * 4456 * <p>There are four events for each permission: <ul> 4457 * <li>Request permission: first id + 0</li> 4458 * <li>Grant permission: first id + 1</li> 4459 * <li>Request for permission denied: first id + 2</li> 4460 * <li>Revoke permission: first id + 3</li> 4461 * </ul></p> 4462 * 4463 * @param name name of the permission 4464 * 4465 * @return The first event id for the permission 4466 */ 4467 private static int getBaseEventId(@NonNull String name) { 4468 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4469 4470 if (eventIdIndex == -1) { 4471 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4472 || "user".equals(Build.TYPE)) { 4473 Log.i(TAG, "Unknown permission " + name); 4474 4475 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4476 } else { 4477 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4478 // 4479 // Also update 4480 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4481 // - metrics_constants.proto 4482 throw new IllegalStateException("Unknown permission " + name); 4483 } 4484 } 4485 4486 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4487 } 4488 4489 /** 4490 * Log that a permission was revoked. 4491 * 4492 * @param context Context of the caller 4493 * @param name name of the permission 4494 * @param packageName package permission if for 4495 */ 4496 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4497 @NonNull String packageName) { 4498 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4499 } 4500 4501 /** 4502 * Log that a permission request was granted. 4503 * 4504 * @param context Context of the caller 4505 * @param name name of the permission 4506 * @param packageName package permission if for 4507 */ 4508 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4509 @NonNull String packageName) { 4510 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4511 } 4512 4513 @Override 4514 public void resetRuntimePermissions() { 4515 mContext.enforceCallingOrSelfPermission( 4516 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4517 "revokeRuntimePermission"); 4518 4519 int callingUid = Binder.getCallingUid(); 4520 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4521 mContext.enforceCallingOrSelfPermission( 4522 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4523 "resetRuntimePermissions"); 4524 } 4525 4526 synchronized (mPackages) { 4527 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4528 for (int userId : UserManagerService.getInstance().getUserIds()) { 4529 final int packageCount = mPackages.size(); 4530 for (int i = 0; i < packageCount; i++) { 4531 PackageParser.Package pkg = mPackages.valueAt(i); 4532 if (!(pkg.mExtras instanceof PackageSetting)) { 4533 continue; 4534 } 4535 PackageSetting ps = (PackageSetting) pkg.mExtras; 4536 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4537 } 4538 } 4539 } 4540 } 4541 4542 @Override 4543 public int getPermissionFlags(String name, String packageName, int userId) { 4544 if (!sUserManager.exists(userId)) { 4545 return 0; 4546 } 4547 4548 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4549 4550 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4551 true /* requireFullPermission */, false /* checkShell */, 4552 "getPermissionFlags"); 4553 4554 synchronized (mPackages) { 4555 final PackageParser.Package pkg = mPackages.get(packageName); 4556 if (pkg == null) { 4557 return 0; 4558 } 4559 4560 final BasePermission bp = mSettings.mPermissions.get(name); 4561 if (bp == null) { 4562 return 0; 4563 } 4564 4565 SettingBase sb = (SettingBase) pkg.mExtras; 4566 if (sb == null) { 4567 return 0; 4568 } 4569 4570 PermissionsState permissionsState = sb.getPermissionsState(); 4571 return permissionsState.getPermissionFlags(name, userId); 4572 } 4573 } 4574 4575 @Override 4576 public void updatePermissionFlags(String name, String packageName, int flagMask, 4577 int flagValues, int userId) { 4578 if (!sUserManager.exists(userId)) { 4579 return; 4580 } 4581 4582 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4583 4584 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4585 true /* requireFullPermission */, true /* checkShell */, 4586 "updatePermissionFlags"); 4587 4588 // Only the system can change these flags and nothing else. 4589 if (getCallingUid() != Process.SYSTEM_UID) { 4590 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4591 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4592 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4593 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4594 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4595 } 4596 4597 synchronized (mPackages) { 4598 final PackageParser.Package pkg = mPackages.get(packageName); 4599 if (pkg == null) { 4600 throw new IllegalArgumentException("Unknown package: " + packageName); 4601 } 4602 4603 final BasePermission bp = mSettings.mPermissions.get(name); 4604 if (bp == null) { 4605 throw new IllegalArgumentException("Unknown permission: " + name); 4606 } 4607 4608 SettingBase sb = (SettingBase) pkg.mExtras; 4609 if (sb == null) { 4610 throw new IllegalArgumentException("Unknown package: " + packageName); 4611 } 4612 4613 PermissionsState permissionsState = sb.getPermissionsState(); 4614 4615 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4616 4617 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4618 // Install and runtime permissions are stored in different places, 4619 // so figure out what permission changed and persist the change. 4620 if (permissionsState.getInstallPermissionState(name) != null) { 4621 scheduleWriteSettingsLocked(); 4622 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4623 || hadState) { 4624 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4625 } 4626 } 4627 } 4628 } 4629 4630 /** 4631 * Update the permission flags for all packages and runtime permissions of a user in order 4632 * to allow device or profile owner to remove POLICY_FIXED. 4633 */ 4634 @Override 4635 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4636 if (!sUserManager.exists(userId)) { 4637 return; 4638 } 4639 4640 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4641 4642 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4643 true /* requireFullPermission */, true /* checkShell */, 4644 "updatePermissionFlagsForAllApps"); 4645 4646 // Only the system can change system fixed flags. 4647 if (getCallingUid() != Process.SYSTEM_UID) { 4648 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4649 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4650 } 4651 4652 synchronized (mPackages) { 4653 boolean changed = false; 4654 final int packageCount = mPackages.size(); 4655 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4656 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4657 SettingBase sb = (SettingBase) pkg.mExtras; 4658 if (sb == null) { 4659 continue; 4660 } 4661 PermissionsState permissionsState = sb.getPermissionsState(); 4662 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4663 userId, flagMask, flagValues); 4664 } 4665 if (changed) { 4666 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4667 } 4668 } 4669 } 4670 4671 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4672 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4673 != PackageManager.PERMISSION_GRANTED 4674 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4675 != PackageManager.PERMISSION_GRANTED) { 4676 throw new SecurityException(message + " requires " 4677 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4678 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4679 } 4680 } 4681 4682 @Override 4683 public boolean shouldShowRequestPermissionRationale(String permissionName, 4684 String packageName, int userId) { 4685 if (UserHandle.getCallingUserId() != userId) { 4686 mContext.enforceCallingPermission( 4687 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4688 "canShowRequestPermissionRationale for user " + userId); 4689 } 4690 4691 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4692 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4693 return false; 4694 } 4695 4696 if (checkPermission(permissionName, packageName, userId) 4697 == PackageManager.PERMISSION_GRANTED) { 4698 return false; 4699 } 4700 4701 final int flags; 4702 4703 final long identity = Binder.clearCallingIdentity(); 4704 try { 4705 flags = getPermissionFlags(permissionName, 4706 packageName, userId); 4707 } finally { 4708 Binder.restoreCallingIdentity(identity); 4709 } 4710 4711 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4712 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4713 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4714 4715 if ((flags & fixedFlags) != 0) { 4716 return false; 4717 } 4718 4719 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4720 } 4721 4722 @Override 4723 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4724 mContext.enforceCallingOrSelfPermission( 4725 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4726 "addOnPermissionsChangeListener"); 4727 4728 synchronized (mPackages) { 4729 mOnPermissionChangeListeners.addListenerLocked(listener); 4730 } 4731 } 4732 4733 @Override 4734 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4735 synchronized (mPackages) { 4736 mOnPermissionChangeListeners.removeListenerLocked(listener); 4737 } 4738 } 4739 4740 @Override 4741 public boolean isProtectedBroadcast(String actionName) { 4742 synchronized (mPackages) { 4743 if (mProtectedBroadcasts.contains(actionName)) { 4744 return true; 4745 } else if (actionName != null) { 4746 // TODO: remove these terrible hacks 4747 if (actionName.startsWith("android.net.netmon.lingerExpired") 4748 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4749 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4750 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4751 return true; 4752 } 4753 } 4754 } 4755 return false; 4756 } 4757 4758 @Override 4759 public int checkSignatures(String pkg1, String pkg2) { 4760 synchronized (mPackages) { 4761 final PackageParser.Package p1 = mPackages.get(pkg1); 4762 final PackageParser.Package p2 = mPackages.get(pkg2); 4763 if (p1 == null || p1.mExtras == null 4764 || p2 == null || p2.mExtras == null) { 4765 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4766 } 4767 return compareSignatures(p1.mSignatures, p2.mSignatures); 4768 } 4769 } 4770 4771 @Override 4772 public int checkUidSignatures(int uid1, int uid2) { 4773 // Map to base uids. 4774 uid1 = UserHandle.getAppId(uid1); 4775 uid2 = UserHandle.getAppId(uid2); 4776 // reader 4777 synchronized (mPackages) { 4778 Signature[] s1; 4779 Signature[] s2; 4780 Object obj = mSettings.getUserIdLPr(uid1); 4781 if (obj != null) { 4782 if (obj instanceof SharedUserSetting) { 4783 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4784 } else if (obj instanceof PackageSetting) { 4785 s1 = ((PackageSetting)obj).signatures.mSignatures; 4786 } else { 4787 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4788 } 4789 } else { 4790 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4791 } 4792 obj = mSettings.getUserIdLPr(uid2); 4793 if (obj != null) { 4794 if (obj instanceof SharedUserSetting) { 4795 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4796 } else if (obj instanceof PackageSetting) { 4797 s2 = ((PackageSetting)obj).signatures.mSignatures; 4798 } else { 4799 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4800 } 4801 } else { 4802 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4803 } 4804 return compareSignatures(s1, s2); 4805 } 4806 } 4807 4808 /** 4809 * This method should typically only be used when granting or revoking 4810 * permissions, since the app may immediately restart after this call. 4811 * <p> 4812 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4813 * guard your work against the app being relaunched. 4814 */ 4815 private void killUid(int appId, int userId, String reason) { 4816 final long identity = Binder.clearCallingIdentity(); 4817 try { 4818 IActivityManager am = ActivityManager.getService(); 4819 if (am != null) { 4820 try { 4821 am.killUid(appId, userId, reason); 4822 } catch (RemoteException e) { 4823 /* ignore - same process */ 4824 } 4825 } 4826 } finally { 4827 Binder.restoreCallingIdentity(identity); 4828 } 4829 } 4830 4831 /** 4832 * Compares two sets of signatures. Returns: 4833 * <br /> 4834 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4835 * <br /> 4836 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4837 * <br /> 4838 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4839 * <br /> 4840 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4841 * <br /> 4842 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4843 */ 4844 static int compareSignatures(Signature[] s1, Signature[] s2) { 4845 if (s1 == null) { 4846 return s2 == null 4847 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4848 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4849 } 4850 4851 if (s2 == null) { 4852 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4853 } 4854 4855 if (s1.length != s2.length) { 4856 return PackageManager.SIGNATURE_NO_MATCH; 4857 } 4858 4859 // Since both signature sets are of size 1, we can compare without HashSets. 4860 if (s1.length == 1) { 4861 return s1[0].equals(s2[0]) ? 4862 PackageManager.SIGNATURE_MATCH : 4863 PackageManager.SIGNATURE_NO_MATCH; 4864 } 4865 4866 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4867 for (Signature sig : s1) { 4868 set1.add(sig); 4869 } 4870 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4871 for (Signature sig : s2) { 4872 set2.add(sig); 4873 } 4874 // Make sure s2 contains all signatures in s1. 4875 if (set1.equals(set2)) { 4876 return PackageManager.SIGNATURE_MATCH; 4877 } 4878 return PackageManager.SIGNATURE_NO_MATCH; 4879 } 4880 4881 /** 4882 * If the database version for this type of package (internal storage or 4883 * external storage) is less than the version where package signatures 4884 * were updated, return true. 4885 */ 4886 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4887 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4888 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4889 } 4890 4891 /** 4892 * Used for backward compatibility to make sure any packages with 4893 * certificate chains get upgraded to the new style. {@code existingSigs} 4894 * will be in the old format (since they were stored on disk from before the 4895 * system upgrade) and {@code scannedSigs} will be in the newer format. 4896 */ 4897 private int compareSignaturesCompat(PackageSignatures existingSigs, 4898 PackageParser.Package scannedPkg) { 4899 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4900 return PackageManager.SIGNATURE_NO_MATCH; 4901 } 4902 4903 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4904 for (Signature sig : existingSigs.mSignatures) { 4905 existingSet.add(sig); 4906 } 4907 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4908 for (Signature sig : scannedPkg.mSignatures) { 4909 try { 4910 Signature[] chainSignatures = sig.getChainSignatures(); 4911 for (Signature chainSig : chainSignatures) { 4912 scannedCompatSet.add(chainSig); 4913 } 4914 } catch (CertificateEncodingException e) { 4915 scannedCompatSet.add(sig); 4916 } 4917 } 4918 /* 4919 * Make sure the expanded scanned set contains all signatures in the 4920 * existing one. 4921 */ 4922 if (scannedCompatSet.equals(existingSet)) { 4923 // Migrate the old signatures to the new scheme. 4924 existingSigs.assignSignatures(scannedPkg.mSignatures); 4925 // The new KeySets will be re-added later in the scanning process. 4926 synchronized (mPackages) { 4927 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4928 } 4929 return PackageManager.SIGNATURE_MATCH; 4930 } 4931 return PackageManager.SIGNATURE_NO_MATCH; 4932 } 4933 4934 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4935 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4936 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4937 } 4938 4939 private int compareSignaturesRecover(PackageSignatures existingSigs, 4940 PackageParser.Package scannedPkg) { 4941 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4942 return PackageManager.SIGNATURE_NO_MATCH; 4943 } 4944 4945 String msg = null; 4946 try { 4947 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4948 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4949 + scannedPkg.packageName); 4950 return PackageManager.SIGNATURE_MATCH; 4951 } 4952 } catch (CertificateException e) { 4953 msg = e.getMessage(); 4954 } 4955 4956 logCriticalInfo(Log.INFO, 4957 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4958 return PackageManager.SIGNATURE_NO_MATCH; 4959 } 4960 4961 @Override 4962 public List<String> getAllPackages() { 4963 synchronized (mPackages) { 4964 return new ArrayList<String>(mPackages.keySet()); 4965 } 4966 } 4967 4968 @Override 4969 public String[] getPackagesForUid(int uid) { 4970 final int userId = UserHandle.getUserId(uid); 4971 uid = UserHandle.getAppId(uid); 4972 // reader 4973 synchronized (mPackages) { 4974 Object obj = mSettings.getUserIdLPr(uid); 4975 if (obj instanceof SharedUserSetting) { 4976 final SharedUserSetting sus = (SharedUserSetting) obj; 4977 final int N = sus.packages.size(); 4978 String[] res = new String[N]; 4979 final Iterator<PackageSetting> it = sus.packages.iterator(); 4980 int i = 0; 4981 while (it.hasNext()) { 4982 PackageSetting ps = it.next(); 4983 if (ps.getInstalled(userId)) { 4984 res[i++] = ps.name; 4985 } else { 4986 res = ArrayUtils.removeElement(String.class, res, res[i]); 4987 } 4988 } 4989 return res; 4990 } else if (obj instanceof PackageSetting) { 4991 final PackageSetting ps = (PackageSetting) obj; 4992 return new String[] { ps.name }; 4993 } 4994 } 4995 return null; 4996 } 4997 4998 @Override 4999 public String getNameForUid(int uid) { 5000 // reader 5001 synchronized (mPackages) { 5002 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5003 if (obj instanceof SharedUserSetting) { 5004 final SharedUserSetting sus = (SharedUserSetting) obj; 5005 return sus.name + ":" + sus.userId; 5006 } else if (obj instanceof PackageSetting) { 5007 final PackageSetting ps = (PackageSetting) obj; 5008 return ps.name; 5009 } 5010 } 5011 return null; 5012 } 5013 5014 @Override 5015 public int getUidForSharedUser(String sharedUserName) { 5016 if(sharedUserName == null) { 5017 return -1; 5018 } 5019 // reader 5020 synchronized (mPackages) { 5021 SharedUserSetting suid; 5022 try { 5023 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5024 if (suid != null) { 5025 return suid.userId; 5026 } 5027 } catch (PackageManagerException ignore) { 5028 // can't happen, but, still need to catch it 5029 } 5030 return -1; 5031 } 5032 } 5033 5034 @Override 5035 public int getFlagsForUid(int uid) { 5036 synchronized (mPackages) { 5037 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5038 if (obj instanceof SharedUserSetting) { 5039 final SharedUserSetting sus = (SharedUserSetting) obj; 5040 return sus.pkgFlags; 5041 } else if (obj instanceof PackageSetting) { 5042 final PackageSetting ps = (PackageSetting) obj; 5043 return ps.pkgFlags; 5044 } 5045 } 5046 return 0; 5047 } 5048 5049 @Override 5050 public int getPrivateFlagsForUid(int uid) { 5051 synchronized (mPackages) { 5052 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5053 if (obj instanceof SharedUserSetting) { 5054 final SharedUserSetting sus = (SharedUserSetting) obj; 5055 return sus.pkgPrivateFlags; 5056 } else if (obj instanceof PackageSetting) { 5057 final PackageSetting ps = (PackageSetting) obj; 5058 return ps.pkgPrivateFlags; 5059 } 5060 } 5061 return 0; 5062 } 5063 5064 @Override 5065 public boolean isUidPrivileged(int uid) { 5066 uid = UserHandle.getAppId(uid); 5067 // reader 5068 synchronized (mPackages) { 5069 Object obj = mSettings.getUserIdLPr(uid); 5070 if (obj instanceof SharedUserSetting) { 5071 final SharedUserSetting sus = (SharedUserSetting) obj; 5072 final Iterator<PackageSetting> it = sus.packages.iterator(); 5073 while (it.hasNext()) { 5074 if (it.next().isPrivileged()) { 5075 return true; 5076 } 5077 } 5078 } else if (obj instanceof PackageSetting) { 5079 final PackageSetting ps = (PackageSetting) obj; 5080 return ps.isPrivileged(); 5081 } 5082 } 5083 return false; 5084 } 5085 5086 @Override 5087 public String[] getAppOpPermissionPackages(String permissionName) { 5088 synchronized (mPackages) { 5089 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5090 if (pkgs == null) { 5091 return null; 5092 } 5093 return pkgs.toArray(new String[pkgs.size()]); 5094 } 5095 } 5096 5097 @Override 5098 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5099 int flags, int userId) { 5100 try { 5101 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5102 5103 if (!sUserManager.exists(userId)) return null; 5104 flags = updateFlagsForResolve(flags, userId, intent); 5105 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5106 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5107 5108 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5109 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5110 flags, userId); 5111 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5112 5113 final ResolveInfo bestChoice = 5114 chooseBestActivity(intent, resolvedType, flags, query, userId); 5115 return bestChoice; 5116 } finally { 5117 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5118 } 5119 } 5120 5121 @Override 5122 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5123 IntentFilter filter, int match, ComponentName activity) { 5124 final int userId = UserHandle.getCallingUserId(); 5125 if (DEBUG_PREFERRED) { 5126 Log.v(TAG, "setLastChosenActivity intent=" + intent 5127 + " resolvedType=" + resolvedType 5128 + " flags=" + flags 5129 + " filter=" + filter 5130 + " match=" + match 5131 + " activity=" + activity); 5132 filter.dump(new PrintStreamPrinter(System.out), " "); 5133 } 5134 intent.setComponent(null); 5135 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5136 userId); 5137 // Find any earlier preferred or last chosen entries and nuke them 5138 findPreferredActivity(intent, resolvedType, 5139 flags, query, 0, false, true, false, userId); 5140 // Add the new activity as the last chosen for this filter 5141 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5142 "Setting last chosen"); 5143 } 5144 5145 @Override 5146 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5147 final int userId = UserHandle.getCallingUserId(); 5148 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5149 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5150 userId); 5151 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5152 false, false, false, userId); 5153 } 5154 5155 private boolean isEphemeralDisabled() { 5156 // ephemeral apps have been disabled across the board 5157 if (DISABLE_EPHEMERAL_APPS) { 5158 return true; 5159 } 5160 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5161 if (!mSystemReady) { 5162 return true; 5163 } 5164 // we can't get a content resolver until the system is ready; these checks must happen last 5165 final ContentResolver resolver = mContext.getContentResolver(); 5166 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5167 return true; 5168 } 5169 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5170 } 5171 5172 private boolean isEphemeralAllowed( 5173 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5174 boolean skipPackageCheck) { 5175 // Short circuit and return early if possible. 5176 if (isEphemeralDisabled()) { 5177 return false; 5178 } 5179 final int callingUser = UserHandle.getCallingUserId(); 5180 if (callingUser != UserHandle.USER_SYSTEM) { 5181 return false; 5182 } 5183 if (mEphemeralResolverConnection == null) { 5184 return false; 5185 } 5186 if (mEphemeralInstallerComponent == null) { 5187 return false; 5188 } 5189 if (intent.getComponent() != null) { 5190 return false; 5191 } 5192 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5193 return false; 5194 } 5195 if (!skipPackageCheck && intent.getPackage() != null) { 5196 return false; 5197 } 5198 final boolean isWebUri = hasWebURI(intent); 5199 if (!isWebUri || intent.getData().getHost() == null) { 5200 return false; 5201 } 5202 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5203 synchronized (mPackages) { 5204 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5205 for (int n = 0; n < count; n++) { 5206 ResolveInfo info = resolvedActivities.get(n); 5207 String packageName = info.activityInfo.packageName; 5208 PackageSetting ps = mSettings.mPackages.get(packageName); 5209 if (ps != null) { 5210 // Try to get the status from User settings first 5211 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5212 int status = (int) (packedStatus >> 32); 5213 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5214 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5215 if (DEBUG_EPHEMERAL) { 5216 Slog.v(TAG, "DENY ephemeral apps;" 5217 + " pkg: " + packageName + ", status: " + status); 5218 } 5219 return false; 5220 } 5221 } 5222 } 5223 } 5224 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5225 return true; 5226 } 5227 5228 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5229 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5230 int userId) { 5231 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5232 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5233 callingPackage, userId)); 5234 mHandler.sendMessage(msg); 5235 } 5236 5237 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5238 int flags, List<ResolveInfo> query, int userId) { 5239 if (query != null) { 5240 final int N = query.size(); 5241 if (N == 1) { 5242 return query.get(0); 5243 } else if (N > 1) { 5244 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5245 // If there is more than one activity with the same priority, 5246 // then let the user decide between them. 5247 ResolveInfo r0 = query.get(0); 5248 ResolveInfo r1 = query.get(1); 5249 if (DEBUG_INTENT_MATCHING || debug) { 5250 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5251 + r1.activityInfo.name + "=" + r1.priority); 5252 } 5253 // If the first activity has a higher priority, or a different 5254 // default, then it is always desirable to pick it. 5255 if (r0.priority != r1.priority 5256 || r0.preferredOrder != r1.preferredOrder 5257 || r0.isDefault != r1.isDefault) { 5258 return query.get(0); 5259 } 5260 // If we have saved a preference for a preferred activity for 5261 // this Intent, use that. 5262 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5263 flags, query, r0.priority, true, false, debug, userId); 5264 if (ri != null) { 5265 return ri; 5266 } 5267 ri = new ResolveInfo(mResolveInfo); 5268 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5269 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5270 // If all of the options come from the same package, show the application's 5271 // label and icon instead of the generic resolver's. 5272 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5273 // and then throw away the ResolveInfo itself, meaning that the caller loses 5274 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5275 // a fallback for this case; we only set the target package's resources on 5276 // the ResolveInfo, not the ActivityInfo. 5277 final String intentPackage = intent.getPackage(); 5278 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5279 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5280 ri.resolvePackageName = intentPackage; 5281 if (userNeedsBadging(userId)) { 5282 ri.noResourceId = true; 5283 } else { 5284 ri.icon = appi.icon; 5285 } 5286 ri.iconResourceId = appi.icon; 5287 ri.labelRes = appi.labelRes; 5288 } 5289 ri.activityInfo.applicationInfo = new ApplicationInfo( 5290 ri.activityInfo.applicationInfo); 5291 if (userId != 0) { 5292 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5293 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5294 } 5295 // Make sure that the resolver is displayable in car mode 5296 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5297 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5298 return ri; 5299 } 5300 } 5301 return null; 5302 } 5303 5304 /** 5305 * Return true if the given list is not empty and all of its contents have 5306 * an activityInfo with the given package name. 5307 */ 5308 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5309 if (ArrayUtils.isEmpty(list)) { 5310 return false; 5311 } 5312 for (int i = 0, N = list.size(); i < N; i++) { 5313 final ResolveInfo ri = list.get(i); 5314 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5315 if (ai == null || !packageName.equals(ai.packageName)) { 5316 return false; 5317 } 5318 } 5319 return true; 5320 } 5321 5322 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5323 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5324 final int N = query.size(); 5325 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5326 .get(userId); 5327 // Get the list of persistent preferred activities that handle the intent 5328 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5329 List<PersistentPreferredActivity> pprefs = ppir != null 5330 ? ppir.queryIntent(intent, resolvedType, 5331 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5332 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5333 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5334 : null; 5335 if (pprefs != null && pprefs.size() > 0) { 5336 final int M = pprefs.size(); 5337 for (int i=0; i<M; i++) { 5338 final PersistentPreferredActivity ppa = pprefs.get(i); 5339 if (DEBUG_PREFERRED || debug) { 5340 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5341 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5342 + "\n component=" + ppa.mComponent); 5343 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5344 } 5345 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5346 flags | MATCH_DISABLED_COMPONENTS, userId); 5347 if (DEBUG_PREFERRED || debug) { 5348 Slog.v(TAG, "Found persistent preferred activity:"); 5349 if (ai != null) { 5350 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5351 } else { 5352 Slog.v(TAG, " null"); 5353 } 5354 } 5355 if (ai == null) { 5356 // This previously registered persistent preferred activity 5357 // component is no longer known. Ignore it and do NOT remove it. 5358 continue; 5359 } 5360 for (int j=0; j<N; j++) { 5361 final ResolveInfo ri = query.get(j); 5362 if (!ri.activityInfo.applicationInfo.packageName 5363 .equals(ai.applicationInfo.packageName)) { 5364 continue; 5365 } 5366 if (!ri.activityInfo.name.equals(ai.name)) { 5367 continue; 5368 } 5369 // Found a persistent preference that can handle the intent. 5370 if (DEBUG_PREFERRED || debug) { 5371 Slog.v(TAG, "Returning persistent preferred activity: " + 5372 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5373 } 5374 return ri; 5375 } 5376 } 5377 } 5378 return null; 5379 } 5380 5381 // TODO: handle preferred activities missing while user has amnesia 5382 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5383 List<ResolveInfo> query, int priority, boolean always, 5384 boolean removeMatches, boolean debug, int userId) { 5385 if (!sUserManager.exists(userId)) return null; 5386 flags = updateFlagsForResolve(flags, userId, intent); 5387 // writer 5388 synchronized (mPackages) { 5389 if (intent.getSelector() != null) { 5390 intent = intent.getSelector(); 5391 } 5392 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5393 5394 // Try to find a matching persistent preferred activity. 5395 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5396 debug, userId); 5397 5398 // If a persistent preferred activity matched, use it. 5399 if (pri != null) { 5400 return pri; 5401 } 5402 5403 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5404 // Get the list of preferred activities that handle the intent 5405 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5406 List<PreferredActivity> prefs = pir != null 5407 ? pir.queryIntent(intent, resolvedType, 5408 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5409 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 5410 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId) 5411 : null; 5412 if (prefs != null && prefs.size() > 0) { 5413 boolean changed = false; 5414 try { 5415 // First figure out how good the original match set is. 5416 // We will only allow preferred activities that came 5417 // from the same match quality. 5418 int match = 0; 5419 5420 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5421 5422 final int N = query.size(); 5423 for (int j=0; j<N; j++) { 5424 final ResolveInfo ri = query.get(j); 5425 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5426 + ": 0x" + Integer.toHexString(match)); 5427 if (ri.match > match) { 5428 match = ri.match; 5429 } 5430 } 5431 5432 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5433 + Integer.toHexString(match)); 5434 5435 match &= IntentFilter.MATCH_CATEGORY_MASK; 5436 final int M = prefs.size(); 5437 for (int i=0; i<M; i++) { 5438 final PreferredActivity pa = prefs.get(i); 5439 if (DEBUG_PREFERRED || debug) { 5440 Slog.v(TAG, "Checking PreferredActivity ds=" 5441 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5442 + "\n component=" + pa.mPref.mComponent); 5443 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5444 } 5445 if (pa.mPref.mMatch != match) { 5446 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5447 + Integer.toHexString(pa.mPref.mMatch)); 5448 continue; 5449 } 5450 // If it's not an "always" type preferred activity and that's what we're 5451 // looking for, skip it. 5452 if (always && !pa.mPref.mAlways) { 5453 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5454 continue; 5455 } 5456 final ActivityInfo ai = getActivityInfo( 5457 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5458 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5459 userId); 5460 if (DEBUG_PREFERRED || debug) { 5461 Slog.v(TAG, "Found preferred activity:"); 5462 if (ai != null) { 5463 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5464 } else { 5465 Slog.v(TAG, " null"); 5466 } 5467 } 5468 if (ai == null) { 5469 // This previously registered preferred activity 5470 // component is no longer known. Most likely an update 5471 // to the app was installed and in the new version this 5472 // component no longer exists. Clean it up by removing 5473 // it from the preferred activities list, and skip it. 5474 Slog.w(TAG, "Removing dangling preferred activity: " 5475 + pa.mPref.mComponent); 5476 pir.removeFilter(pa); 5477 changed = true; 5478 continue; 5479 } 5480 for (int j=0; j<N; j++) { 5481 final ResolveInfo ri = query.get(j); 5482 if (!ri.activityInfo.applicationInfo.packageName 5483 .equals(ai.applicationInfo.packageName)) { 5484 continue; 5485 } 5486 if (!ri.activityInfo.name.equals(ai.name)) { 5487 continue; 5488 } 5489 5490 if (removeMatches) { 5491 pir.removeFilter(pa); 5492 changed = true; 5493 if (DEBUG_PREFERRED) { 5494 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5495 } 5496 break; 5497 } 5498 5499 // Okay we found a previously set preferred or last chosen app. 5500 // If the result set is different from when this 5501 // was created, we need to clear it and re-ask the 5502 // user their preference, if we're looking for an "always" type entry. 5503 if (always && !pa.mPref.sameSet(query)) { 5504 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5505 + intent + " type " + resolvedType); 5506 if (DEBUG_PREFERRED) { 5507 Slog.v(TAG, "Removing preferred activity since set changed " 5508 + pa.mPref.mComponent); 5509 } 5510 pir.removeFilter(pa); 5511 // Re-add the filter as a "last chosen" entry (!always) 5512 PreferredActivity lastChosen = new PreferredActivity( 5513 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5514 pir.addFilter(lastChosen); 5515 changed = true; 5516 return null; 5517 } 5518 5519 // Yay! Either the set matched or we're looking for the last chosen 5520 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5521 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5522 return ri; 5523 } 5524 } 5525 } finally { 5526 if (changed) { 5527 if (DEBUG_PREFERRED) { 5528 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5529 } 5530 scheduleWritePackageRestrictionsLocked(userId); 5531 } 5532 } 5533 } 5534 } 5535 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5536 return null; 5537 } 5538 5539 /* 5540 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5541 */ 5542 @Override 5543 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5544 int targetUserId) { 5545 mContext.enforceCallingOrSelfPermission( 5546 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5547 List<CrossProfileIntentFilter> matches = 5548 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5549 if (matches != null) { 5550 int size = matches.size(); 5551 for (int i = 0; i < size; i++) { 5552 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5553 } 5554 } 5555 if (hasWebURI(intent)) { 5556 // cross-profile app linking works only towards the parent. 5557 final UserInfo parent = getProfileParent(sourceUserId); 5558 synchronized(mPackages) { 5559 int flags = updateFlagsForResolve(0, parent.id, intent); 5560 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5561 intent, resolvedType, flags, sourceUserId, parent.id); 5562 return xpDomainInfo != null; 5563 } 5564 } 5565 return false; 5566 } 5567 5568 private UserInfo getProfileParent(int userId) { 5569 final long identity = Binder.clearCallingIdentity(); 5570 try { 5571 return sUserManager.getProfileParent(userId); 5572 } finally { 5573 Binder.restoreCallingIdentity(identity); 5574 } 5575 } 5576 5577 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5578 String resolvedType, int userId) { 5579 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5580 if (resolver != null) { 5581 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, 5582 false /*visibleToEphemeral*/, false /*isEphemeral*/, userId); 5583 } 5584 return null; 5585 } 5586 5587 @Override 5588 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5589 String resolvedType, int flags, int userId) { 5590 try { 5591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5592 5593 return new ParceledListSlice<>( 5594 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5595 } finally { 5596 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5597 } 5598 } 5599 5600 /** 5601 * Returns the package name of the calling Uid if it's an ephemeral app. If it isn't 5602 * ephemeral, returns {@code null}. 5603 */ 5604 private String getEphemeralPackageName(int callingUid) { 5605 final int appId = UserHandle.getAppId(callingUid); 5606 synchronized (mPackages) { 5607 final Object obj = mSettings.getUserIdLPr(appId); 5608 if (obj instanceof PackageSetting) { 5609 final PackageSetting ps = (PackageSetting) obj; 5610 return ps.pkg.applicationInfo.isEphemeralApp() ? ps.pkg.packageName : null; 5611 } 5612 } 5613 return null; 5614 } 5615 5616 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5617 String resolvedType, int flags, int userId) { 5618 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5619 final String ephemeralPkgName = getEphemeralPackageName(Binder.getCallingUid()); 5620 flags = updateFlagsForResolve(flags, userId, intent); 5621 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5622 false /* requireFullPermission */, false /* checkShell */, 5623 "query intent activities"); 5624 ComponentName comp = intent.getComponent(); 5625 if (comp == null) { 5626 if (intent.getSelector() != null) { 5627 intent = intent.getSelector(); 5628 comp = intent.getComponent(); 5629 } 5630 } 5631 5632 if (comp != null) { 5633 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5634 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5635 if (ai != null) { 5636 // When specifying an explicit component, we prevent the activity from being 5637 // used when either 1) the calling package is normal and the activity is within 5638 // an ephemeral application or 2) the calling package is ephemeral and the 5639 // activity is not visible to ephemeral applications. 5640 boolean matchEphemeral = 5641 (flags & PackageManager.MATCH_EPHEMERAL) != 0; 5642 boolean ephemeralVisibleOnly = 5643 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 5644 boolean blockResolution = 5645 (!matchEphemeral && ephemeralPkgName == null 5646 && (ai.applicationInfo.privateFlags 5647 & ApplicationInfo.PRIVATE_FLAG_EPHEMERAL) != 0) 5648 || (ephemeralVisibleOnly && ephemeralPkgName != null 5649 && (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0); 5650 if (!blockResolution) { 5651 final ResolveInfo ri = new ResolveInfo(); 5652 ri.activityInfo = ai; 5653 list.add(ri); 5654 } 5655 } 5656 return list; 5657 } 5658 5659 // reader 5660 boolean sortResult = false; 5661 boolean addEphemeral = false; 5662 List<ResolveInfo> result; 5663 final String pkgName = intent.getPackage(); 5664 synchronized (mPackages) { 5665 if (pkgName == null) { 5666 List<CrossProfileIntentFilter> matchingFilters = 5667 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5668 // Check for results that need to skip the current profile. 5669 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5670 resolvedType, flags, userId); 5671 if (xpResolveInfo != null) { 5672 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5673 xpResult.add(xpResolveInfo); 5674 return filterForEphemeral( 5675 filterIfNotSystemUser(xpResult, userId), ephemeralPkgName); 5676 } 5677 5678 // Check for results in the current profile. 5679 result = filterIfNotSystemUser(mActivities.queryIntent( 5680 intent, resolvedType, flags, userId), userId); 5681 addEphemeral = 5682 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5683 5684 // Check for cross profile results. 5685 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5686 xpResolveInfo = queryCrossProfileIntents( 5687 matchingFilters, intent, resolvedType, flags, userId, 5688 hasNonNegativePriorityResult); 5689 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5690 boolean isVisibleToUser = filterIfNotSystemUser( 5691 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5692 if (isVisibleToUser) { 5693 result.add(xpResolveInfo); 5694 sortResult = true; 5695 } 5696 } 5697 if (hasWebURI(intent)) { 5698 CrossProfileDomainInfo xpDomainInfo = null; 5699 final UserInfo parent = getProfileParent(userId); 5700 if (parent != null) { 5701 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5702 flags, userId, parent.id); 5703 } 5704 if (xpDomainInfo != null) { 5705 if (xpResolveInfo != null) { 5706 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5707 // in the result. 5708 result.remove(xpResolveInfo); 5709 } 5710 if (result.size() == 0 && !addEphemeral) { 5711 // No result in current profile, but found candidate in parent user. 5712 // And we are not going to add emphemeral app, so we can return the 5713 // result straight away. 5714 result.add(xpDomainInfo.resolveInfo); 5715 return filterForEphemeral(result, ephemeralPkgName); 5716 } 5717 } else if (result.size() <= 1 && !addEphemeral) { 5718 // No result in parent user and <= 1 result in current profile, and we 5719 // are not going to add emphemeral app, so we can return the result without 5720 // further processing. 5721 return filterForEphemeral(result, ephemeralPkgName); 5722 } 5723 // We have more than one candidate (combining results from current and parent 5724 // profile), so we need filtering and sorting. 5725 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5726 intent, flags, result, xpDomainInfo, userId); 5727 sortResult = true; 5728 } 5729 } else { 5730 final PackageParser.Package pkg = mPackages.get(pkgName); 5731 if (pkg != null) { 5732 result = filterForEphemeral(filterIfNotSystemUser( 5733 mActivities.queryIntentForPackage( 5734 intent, resolvedType, flags, pkg.activities, userId), 5735 userId), ephemeralPkgName); 5736 } else { 5737 // the caller wants to resolve for a particular package; however, there 5738 // were no installed results, so, try to find an ephemeral result 5739 addEphemeral = isEphemeralAllowed( 5740 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5741 result = new ArrayList<ResolveInfo>(); 5742 } 5743 } 5744 } 5745 if (addEphemeral) { 5746 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5747 final EphemeralRequest requestObject = new EphemeralRequest( 5748 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5749 null /*launchIntent*/, null /*callingPackage*/, userId); 5750 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5751 mContext, mEphemeralResolverConnection, requestObject); 5752 if (intentInfo != null) { 5753 if (DEBUG_EPHEMERAL) { 5754 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5755 } 5756 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5757 ephemeralInstaller.ephemeralResponse = intentInfo; 5758 // make sure this resolver is the default 5759 ephemeralInstaller.isDefault = true; 5760 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5761 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5762 // add a non-generic filter 5763 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5764 ephemeralInstaller.filter.addDataPath( 5765 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5766 result.add(ephemeralInstaller); 5767 } 5768 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5769 } 5770 if (sortResult) { 5771 Collections.sort(result, mResolvePrioritySorter); 5772 } 5773 return filterForEphemeral(result, ephemeralPkgName); 5774 } 5775 5776 private static class CrossProfileDomainInfo { 5777 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5778 ResolveInfo resolveInfo; 5779 /* Best domain verification status of the activities found in the other profile */ 5780 int bestDomainVerificationStatus; 5781 } 5782 5783 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5784 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5785 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5786 sourceUserId)) { 5787 return null; 5788 } 5789 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5790 resolvedType, flags, parentUserId); 5791 5792 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5793 return null; 5794 } 5795 CrossProfileDomainInfo result = null; 5796 int size = resultTargetUser.size(); 5797 for (int i = 0; i < size; i++) { 5798 ResolveInfo riTargetUser = resultTargetUser.get(i); 5799 // Intent filter verification is only for filters that specify a host. So don't return 5800 // those that handle all web uris. 5801 if (riTargetUser.handleAllWebDataURI) { 5802 continue; 5803 } 5804 String packageName = riTargetUser.activityInfo.packageName; 5805 PackageSetting ps = mSettings.mPackages.get(packageName); 5806 if (ps == null) { 5807 continue; 5808 } 5809 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5810 int status = (int)(verificationState >> 32); 5811 if (result == null) { 5812 result = new CrossProfileDomainInfo(); 5813 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5814 sourceUserId, parentUserId); 5815 result.bestDomainVerificationStatus = status; 5816 } else { 5817 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5818 result.bestDomainVerificationStatus); 5819 } 5820 } 5821 // Don't consider matches with status NEVER across profiles. 5822 if (result != null && result.bestDomainVerificationStatus 5823 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5824 return null; 5825 } 5826 return result; 5827 } 5828 5829 /** 5830 * Verification statuses are ordered from the worse to the best, except for 5831 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5832 */ 5833 private int bestDomainVerificationStatus(int status1, int status2) { 5834 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5835 return status2; 5836 } 5837 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5838 return status1; 5839 } 5840 return (int) MathUtils.max(status1, status2); 5841 } 5842 5843 private boolean isUserEnabled(int userId) { 5844 long callingId = Binder.clearCallingIdentity(); 5845 try { 5846 UserInfo userInfo = sUserManager.getUserInfo(userId); 5847 return userInfo != null && userInfo.isEnabled(); 5848 } finally { 5849 Binder.restoreCallingIdentity(callingId); 5850 } 5851 } 5852 5853 /** 5854 * Filter out activities with systemUserOnly flag set, when current user is not System. 5855 * 5856 * @return filtered list 5857 */ 5858 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5859 if (userId == UserHandle.USER_SYSTEM) { 5860 return resolveInfos; 5861 } 5862 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5863 ResolveInfo info = resolveInfos.get(i); 5864 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5865 resolveInfos.remove(i); 5866 } 5867 } 5868 return resolveInfos; 5869 } 5870 5871 /** 5872 * Filters out ephemeral activities. 5873 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 5874 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 5875 * 5876 * @param resolveInfos The pre-filtered list of resolved activities 5877 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 5878 * is performed. 5879 * @return A filtered list of resolved activities. 5880 */ 5881 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 5882 String ephemeralPkgName) { 5883 if (ephemeralPkgName == null) { 5884 return resolveInfos; 5885 } 5886 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5887 ResolveInfo info = resolveInfos.get(i); 5888 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isEphemeralApp(); 5889 // allow activities that are defined in the provided package 5890 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 5891 continue; 5892 } 5893 // allow activities that have been explicitly exposed to ephemeral apps 5894 if (!isEphemeralApp 5895 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 5896 continue; 5897 } 5898 resolveInfos.remove(i); 5899 } 5900 return resolveInfos; 5901 } 5902 5903 /** 5904 * @param resolveInfos list of resolve infos in descending priority order 5905 * @return if the list contains a resolve info with non-negative priority 5906 */ 5907 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5908 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5909 } 5910 5911 private static boolean hasWebURI(Intent intent) { 5912 if (intent.getData() == null) { 5913 return false; 5914 } 5915 final String scheme = intent.getScheme(); 5916 if (TextUtils.isEmpty(scheme)) { 5917 return false; 5918 } 5919 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5920 } 5921 5922 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5923 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5924 int userId) { 5925 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5926 5927 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5928 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5929 candidates.size()); 5930 } 5931 5932 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5933 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5934 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5935 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5936 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5937 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5938 5939 synchronized (mPackages) { 5940 final int count = candidates.size(); 5941 // First, try to use linked apps. Partition the candidates into four lists: 5942 // one for the final results, one for the "do not use ever", one for "undefined status" 5943 // and finally one for "browser app type". 5944 for (int n=0; n<count; n++) { 5945 ResolveInfo info = candidates.get(n); 5946 String packageName = info.activityInfo.packageName; 5947 PackageSetting ps = mSettings.mPackages.get(packageName); 5948 if (ps != null) { 5949 // Add to the special match all list (Browser use case) 5950 if (info.handleAllWebDataURI) { 5951 matchAllList.add(info); 5952 continue; 5953 } 5954 // Try to get the status from User settings first 5955 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5956 int status = (int)(packedStatus >> 32); 5957 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5958 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5959 if (DEBUG_DOMAIN_VERIFICATION) { 5960 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5961 + " : linkgen=" + linkGeneration); 5962 } 5963 // Use link-enabled generation as preferredOrder, i.e. 5964 // prefer newly-enabled over earlier-enabled. 5965 info.preferredOrder = linkGeneration; 5966 alwaysList.add(info); 5967 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5968 if (DEBUG_DOMAIN_VERIFICATION) { 5969 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5970 } 5971 neverList.add(info); 5972 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5973 if (DEBUG_DOMAIN_VERIFICATION) { 5974 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5975 } 5976 alwaysAskList.add(info); 5977 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5978 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5979 if (DEBUG_DOMAIN_VERIFICATION) { 5980 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5981 } 5982 undefinedList.add(info); 5983 } 5984 } 5985 } 5986 5987 // We'll want to include browser possibilities in a few cases 5988 boolean includeBrowser = false; 5989 5990 // First try to add the "always" resolution(s) for the current user, if any 5991 if (alwaysList.size() > 0) { 5992 result.addAll(alwaysList); 5993 } else { 5994 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5995 result.addAll(undefinedList); 5996 // Maybe add one for the other profile. 5997 if (xpDomainInfo != null && ( 5998 xpDomainInfo.bestDomainVerificationStatus 5999 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6000 result.add(xpDomainInfo.resolveInfo); 6001 } 6002 includeBrowser = true; 6003 } 6004 6005 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6006 // If there were 'always' entries their preferred order has been set, so we also 6007 // back that off to make the alternatives equivalent 6008 if (alwaysAskList.size() > 0) { 6009 for (ResolveInfo i : result) { 6010 i.preferredOrder = 0; 6011 } 6012 result.addAll(alwaysAskList); 6013 includeBrowser = true; 6014 } 6015 6016 if (includeBrowser) { 6017 // Also add browsers (all of them or only the default one) 6018 if (DEBUG_DOMAIN_VERIFICATION) { 6019 Slog.v(TAG, " ...including browsers in candidate set"); 6020 } 6021 if ((matchFlags & MATCH_ALL) != 0) { 6022 result.addAll(matchAllList); 6023 } else { 6024 // Browser/generic handling case. If there's a default browser, go straight 6025 // to that (but only if there is no other higher-priority match). 6026 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6027 int maxMatchPrio = 0; 6028 ResolveInfo defaultBrowserMatch = null; 6029 final int numCandidates = matchAllList.size(); 6030 for (int n = 0; n < numCandidates; n++) { 6031 ResolveInfo info = matchAllList.get(n); 6032 // track the highest overall match priority... 6033 if (info.priority > maxMatchPrio) { 6034 maxMatchPrio = info.priority; 6035 } 6036 // ...and the highest-priority default browser match 6037 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6038 if (defaultBrowserMatch == null 6039 || (defaultBrowserMatch.priority < info.priority)) { 6040 if (debug) { 6041 Slog.v(TAG, "Considering default browser match " + info); 6042 } 6043 defaultBrowserMatch = info; 6044 } 6045 } 6046 } 6047 if (defaultBrowserMatch != null 6048 && defaultBrowserMatch.priority >= maxMatchPrio 6049 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6050 { 6051 if (debug) { 6052 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6053 } 6054 result.add(defaultBrowserMatch); 6055 } else { 6056 result.addAll(matchAllList); 6057 } 6058 } 6059 6060 // If there is nothing selected, add all candidates and remove the ones that the user 6061 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6062 if (result.size() == 0) { 6063 result.addAll(candidates); 6064 result.removeAll(neverList); 6065 } 6066 } 6067 } 6068 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6069 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6070 result.size()); 6071 for (ResolveInfo info : result) { 6072 Slog.v(TAG, " + " + info.activityInfo); 6073 } 6074 } 6075 return result; 6076 } 6077 6078 // Returns a packed value as a long: 6079 // 6080 // high 'int'-sized word: link status: undefined/ask/never/always. 6081 // low 'int'-sized word: relative priority among 'always' results. 6082 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6083 long result = ps.getDomainVerificationStatusForUser(userId); 6084 // if none available, get the master status 6085 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6086 if (ps.getIntentFilterVerificationInfo() != null) { 6087 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6088 } 6089 } 6090 return result; 6091 } 6092 6093 private ResolveInfo querySkipCurrentProfileIntents( 6094 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6095 int flags, int sourceUserId) { 6096 if (matchingFilters != null) { 6097 int size = matchingFilters.size(); 6098 for (int i = 0; i < size; i ++) { 6099 CrossProfileIntentFilter filter = matchingFilters.get(i); 6100 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6101 // Checking if there are activities in the target user that can handle the 6102 // intent. 6103 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6104 resolvedType, flags, sourceUserId); 6105 if (resolveInfo != null) { 6106 return resolveInfo; 6107 } 6108 } 6109 } 6110 } 6111 return null; 6112 } 6113 6114 // Return matching ResolveInfo in target user if any. 6115 private ResolveInfo queryCrossProfileIntents( 6116 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6117 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6118 if (matchingFilters != null) { 6119 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6120 // match the same intent. For performance reasons, it is better not to 6121 // run queryIntent twice for the same userId 6122 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6123 int size = matchingFilters.size(); 6124 for (int i = 0; i < size; i++) { 6125 CrossProfileIntentFilter filter = matchingFilters.get(i); 6126 int targetUserId = filter.getTargetUserId(); 6127 boolean skipCurrentProfile = 6128 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6129 boolean skipCurrentProfileIfNoMatchFound = 6130 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6131 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6132 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6133 // Checking if there are activities in the target user that can handle the 6134 // intent. 6135 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6136 resolvedType, flags, sourceUserId); 6137 if (resolveInfo != null) return resolveInfo; 6138 alreadyTriedUserIds.put(targetUserId, true); 6139 } 6140 } 6141 } 6142 return null; 6143 } 6144 6145 /** 6146 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6147 * will forward the intent to the filter's target user. 6148 * Otherwise, returns null. 6149 */ 6150 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6151 String resolvedType, int flags, int sourceUserId) { 6152 int targetUserId = filter.getTargetUserId(); 6153 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6154 resolvedType, flags, targetUserId); 6155 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6156 // If all the matches in the target profile are suspended, return null. 6157 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6158 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6159 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6160 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6161 targetUserId); 6162 } 6163 } 6164 } 6165 return null; 6166 } 6167 6168 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6169 int sourceUserId, int targetUserId) { 6170 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6171 long ident = Binder.clearCallingIdentity(); 6172 boolean targetIsProfile; 6173 try { 6174 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6175 } finally { 6176 Binder.restoreCallingIdentity(ident); 6177 } 6178 String className; 6179 if (targetIsProfile) { 6180 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6181 } else { 6182 className = FORWARD_INTENT_TO_PARENT; 6183 } 6184 ComponentName forwardingActivityComponentName = new ComponentName( 6185 mAndroidApplication.packageName, className); 6186 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6187 sourceUserId); 6188 if (!targetIsProfile) { 6189 forwardingActivityInfo.showUserIcon = targetUserId; 6190 forwardingResolveInfo.noResourceId = true; 6191 } 6192 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6193 forwardingResolveInfo.priority = 0; 6194 forwardingResolveInfo.preferredOrder = 0; 6195 forwardingResolveInfo.match = 0; 6196 forwardingResolveInfo.isDefault = true; 6197 forwardingResolveInfo.filter = filter; 6198 forwardingResolveInfo.targetUserId = targetUserId; 6199 return forwardingResolveInfo; 6200 } 6201 6202 @Override 6203 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6204 Intent[] specifics, String[] specificTypes, Intent intent, 6205 String resolvedType, int flags, int userId) { 6206 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6207 specificTypes, intent, resolvedType, flags, userId)); 6208 } 6209 6210 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6211 Intent[] specifics, String[] specificTypes, Intent intent, 6212 String resolvedType, int flags, int userId) { 6213 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6214 flags = updateFlagsForResolve(flags, userId, intent); 6215 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6216 false /* requireFullPermission */, false /* checkShell */, 6217 "query intent activity options"); 6218 final String resultsAction = intent.getAction(); 6219 6220 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6221 | PackageManager.GET_RESOLVED_FILTER, userId); 6222 6223 if (DEBUG_INTENT_MATCHING) { 6224 Log.v(TAG, "Query " + intent + ": " + results); 6225 } 6226 6227 int specificsPos = 0; 6228 int N; 6229 6230 // todo: note that the algorithm used here is O(N^2). This 6231 // isn't a problem in our current environment, but if we start running 6232 // into situations where we have more than 5 or 10 matches then this 6233 // should probably be changed to something smarter... 6234 6235 // First we go through and resolve each of the specific items 6236 // that were supplied, taking care of removing any corresponding 6237 // duplicate items in the generic resolve list. 6238 if (specifics != null) { 6239 for (int i=0; i<specifics.length; i++) { 6240 final Intent sintent = specifics[i]; 6241 if (sintent == null) { 6242 continue; 6243 } 6244 6245 if (DEBUG_INTENT_MATCHING) { 6246 Log.v(TAG, "Specific #" + i + ": " + sintent); 6247 } 6248 6249 String action = sintent.getAction(); 6250 if (resultsAction != null && resultsAction.equals(action)) { 6251 // If this action was explicitly requested, then don't 6252 // remove things that have it. 6253 action = null; 6254 } 6255 6256 ResolveInfo ri = null; 6257 ActivityInfo ai = null; 6258 6259 ComponentName comp = sintent.getComponent(); 6260 if (comp == null) { 6261 ri = resolveIntent( 6262 sintent, 6263 specificTypes != null ? specificTypes[i] : null, 6264 flags, userId); 6265 if (ri == null) { 6266 continue; 6267 } 6268 if (ri == mResolveInfo) { 6269 // ACK! Must do something better with this. 6270 } 6271 ai = ri.activityInfo; 6272 comp = new ComponentName(ai.applicationInfo.packageName, 6273 ai.name); 6274 } else { 6275 ai = getActivityInfo(comp, flags, userId); 6276 if (ai == null) { 6277 continue; 6278 } 6279 } 6280 6281 // Look for any generic query activities that are duplicates 6282 // of this specific one, and remove them from the results. 6283 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6284 N = results.size(); 6285 int j; 6286 for (j=specificsPos; j<N; j++) { 6287 ResolveInfo sri = results.get(j); 6288 if ((sri.activityInfo.name.equals(comp.getClassName()) 6289 && sri.activityInfo.applicationInfo.packageName.equals( 6290 comp.getPackageName())) 6291 || (action != null && sri.filter.matchAction(action))) { 6292 results.remove(j); 6293 if (DEBUG_INTENT_MATCHING) Log.v( 6294 TAG, "Removing duplicate item from " + j 6295 + " due to specific " + specificsPos); 6296 if (ri == null) { 6297 ri = sri; 6298 } 6299 j--; 6300 N--; 6301 } 6302 } 6303 6304 // Add this specific item to its proper place. 6305 if (ri == null) { 6306 ri = new ResolveInfo(); 6307 ri.activityInfo = ai; 6308 } 6309 results.add(specificsPos, ri); 6310 ri.specificIndex = i; 6311 specificsPos++; 6312 } 6313 } 6314 6315 // Now we go through the remaining generic results and remove any 6316 // duplicate actions that are found here. 6317 N = results.size(); 6318 for (int i=specificsPos; i<N-1; i++) { 6319 final ResolveInfo rii = results.get(i); 6320 if (rii.filter == null) { 6321 continue; 6322 } 6323 6324 // Iterate over all of the actions of this result's intent 6325 // filter... typically this should be just one. 6326 final Iterator<String> it = rii.filter.actionsIterator(); 6327 if (it == null) { 6328 continue; 6329 } 6330 while (it.hasNext()) { 6331 final String action = it.next(); 6332 if (resultsAction != null && resultsAction.equals(action)) { 6333 // If this action was explicitly requested, then don't 6334 // remove things that have it. 6335 continue; 6336 } 6337 for (int j=i+1; j<N; j++) { 6338 final ResolveInfo rij = results.get(j); 6339 if (rij.filter != null && rij.filter.hasAction(action)) { 6340 results.remove(j); 6341 if (DEBUG_INTENT_MATCHING) Log.v( 6342 TAG, "Removing duplicate item from " + j 6343 + " due to action " + action + " at " + i); 6344 j--; 6345 N--; 6346 } 6347 } 6348 } 6349 6350 // If the caller didn't request filter information, drop it now 6351 // so we don't have to marshall/unmarshall it. 6352 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6353 rii.filter = null; 6354 } 6355 } 6356 6357 // Filter out the caller activity if so requested. 6358 if (caller != null) { 6359 N = results.size(); 6360 for (int i=0; i<N; i++) { 6361 ActivityInfo ainfo = results.get(i).activityInfo; 6362 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6363 && caller.getClassName().equals(ainfo.name)) { 6364 results.remove(i); 6365 break; 6366 } 6367 } 6368 } 6369 6370 // If the caller didn't request filter information, 6371 // drop them now so we don't have to 6372 // marshall/unmarshall it. 6373 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6374 N = results.size(); 6375 for (int i=0; i<N; i++) { 6376 results.get(i).filter = null; 6377 } 6378 } 6379 6380 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6381 return results; 6382 } 6383 6384 @Override 6385 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6386 String resolvedType, int flags, int userId) { 6387 return new ParceledListSlice<>( 6388 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6389 } 6390 6391 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6392 String resolvedType, int flags, int userId) { 6393 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6394 flags = updateFlagsForResolve(flags, userId, intent); 6395 ComponentName comp = intent.getComponent(); 6396 if (comp == null) { 6397 if (intent.getSelector() != null) { 6398 intent = intent.getSelector(); 6399 comp = intent.getComponent(); 6400 } 6401 } 6402 if (comp != null) { 6403 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6404 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6405 if (ai != null) { 6406 ResolveInfo ri = new ResolveInfo(); 6407 ri.activityInfo = ai; 6408 list.add(ri); 6409 } 6410 return list; 6411 } 6412 6413 // reader 6414 synchronized (mPackages) { 6415 String pkgName = intent.getPackage(); 6416 if (pkgName == null) { 6417 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6418 } 6419 final PackageParser.Package pkg = mPackages.get(pkgName); 6420 if (pkg != null) { 6421 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6422 userId); 6423 } 6424 return Collections.emptyList(); 6425 } 6426 } 6427 6428 @Override 6429 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6430 if (!sUserManager.exists(userId)) return null; 6431 flags = updateFlagsForResolve(flags, userId, intent); 6432 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6433 if (query != null) { 6434 if (query.size() >= 1) { 6435 // If there is more than one service with the same priority, 6436 // just arbitrarily pick the first one. 6437 return query.get(0); 6438 } 6439 } 6440 return null; 6441 } 6442 6443 @Override 6444 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6445 String resolvedType, int flags, int userId) { 6446 return new ParceledListSlice<>( 6447 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6448 } 6449 6450 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6451 String resolvedType, int flags, int userId) { 6452 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6453 flags = updateFlagsForResolve(flags, userId, intent); 6454 ComponentName comp = intent.getComponent(); 6455 if (comp == null) { 6456 if (intent.getSelector() != null) { 6457 intent = intent.getSelector(); 6458 comp = intent.getComponent(); 6459 } 6460 } 6461 if (comp != null) { 6462 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6463 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6464 if (si != null) { 6465 final ResolveInfo ri = new ResolveInfo(); 6466 ri.serviceInfo = si; 6467 list.add(ri); 6468 } 6469 return list; 6470 } 6471 6472 // reader 6473 synchronized (mPackages) { 6474 String pkgName = intent.getPackage(); 6475 if (pkgName == null) { 6476 return mServices.queryIntent(intent, resolvedType, flags, userId); 6477 } 6478 final PackageParser.Package pkg = mPackages.get(pkgName); 6479 if (pkg != null) { 6480 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6481 userId); 6482 } 6483 return Collections.emptyList(); 6484 } 6485 } 6486 6487 @Override 6488 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6489 String resolvedType, int flags, int userId) { 6490 return new ParceledListSlice<>( 6491 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6492 } 6493 6494 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6495 Intent intent, String resolvedType, int flags, int userId) { 6496 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6497 flags = updateFlagsForResolve(flags, userId, intent); 6498 ComponentName comp = intent.getComponent(); 6499 if (comp == null) { 6500 if (intent.getSelector() != null) { 6501 intent = intent.getSelector(); 6502 comp = intent.getComponent(); 6503 } 6504 } 6505 if (comp != null) { 6506 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6507 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6508 if (pi != null) { 6509 final ResolveInfo ri = new ResolveInfo(); 6510 ri.providerInfo = pi; 6511 list.add(ri); 6512 } 6513 return list; 6514 } 6515 6516 // reader 6517 synchronized (mPackages) { 6518 String pkgName = intent.getPackage(); 6519 if (pkgName == null) { 6520 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6521 } 6522 final PackageParser.Package pkg = mPackages.get(pkgName); 6523 if (pkg != null) { 6524 return mProviders.queryIntentForPackage( 6525 intent, resolvedType, flags, pkg.providers, userId); 6526 } 6527 return Collections.emptyList(); 6528 } 6529 } 6530 6531 @Override 6532 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6533 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6534 flags = updateFlagsForPackage(flags, userId, null); 6535 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6536 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6537 true /* requireFullPermission */, false /* checkShell */, 6538 "get installed packages"); 6539 6540 // writer 6541 synchronized (mPackages) { 6542 ArrayList<PackageInfo> list; 6543 if (listUninstalled) { 6544 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6545 for (PackageSetting ps : mSettings.mPackages.values()) { 6546 final PackageInfo pi; 6547 if (ps.pkg != null) { 6548 pi = generatePackageInfo(ps, flags, userId); 6549 } else { 6550 pi = generatePackageInfo(ps, flags, userId); 6551 } 6552 if (pi != null) { 6553 list.add(pi); 6554 } 6555 } 6556 } else { 6557 list = new ArrayList<PackageInfo>(mPackages.size()); 6558 for (PackageParser.Package p : mPackages.values()) { 6559 final PackageInfo pi = 6560 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6561 if (pi != null) { 6562 list.add(pi); 6563 } 6564 } 6565 } 6566 6567 return new ParceledListSlice<PackageInfo>(list); 6568 } 6569 } 6570 6571 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6572 String[] permissions, boolean[] tmp, int flags, int userId) { 6573 int numMatch = 0; 6574 final PermissionsState permissionsState = ps.getPermissionsState(); 6575 for (int i=0; i<permissions.length; i++) { 6576 final String permission = permissions[i]; 6577 if (permissionsState.hasPermission(permission, userId)) { 6578 tmp[i] = true; 6579 numMatch++; 6580 } else { 6581 tmp[i] = false; 6582 } 6583 } 6584 if (numMatch == 0) { 6585 return; 6586 } 6587 final PackageInfo pi; 6588 if (ps.pkg != null) { 6589 pi = generatePackageInfo(ps, flags, userId); 6590 } else { 6591 pi = generatePackageInfo(ps, flags, userId); 6592 } 6593 // The above might return null in cases of uninstalled apps or install-state 6594 // skew across users/profiles. 6595 if (pi != null) { 6596 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6597 if (numMatch == permissions.length) { 6598 pi.requestedPermissions = permissions; 6599 } else { 6600 pi.requestedPermissions = new String[numMatch]; 6601 numMatch = 0; 6602 for (int i=0; i<permissions.length; i++) { 6603 if (tmp[i]) { 6604 pi.requestedPermissions[numMatch] = permissions[i]; 6605 numMatch++; 6606 } 6607 } 6608 } 6609 } 6610 list.add(pi); 6611 } 6612 } 6613 6614 @Override 6615 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6616 String[] permissions, int flags, int userId) { 6617 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6618 flags = updateFlagsForPackage(flags, userId, permissions); 6619 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6620 true /* requireFullPermission */, false /* checkShell */, 6621 "get packages holding permissions"); 6622 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6623 6624 // writer 6625 synchronized (mPackages) { 6626 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6627 boolean[] tmpBools = new boolean[permissions.length]; 6628 if (listUninstalled) { 6629 for (PackageSetting ps : mSettings.mPackages.values()) { 6630 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6631 userId); 6632 } 6633 } else { 6634 for (PackageParser.Package pkg : mPackages.values()) { 6635 PackageSetting ps = (PackageSetting)pkg.mExtras; 6636 if (ps != null) { 6637 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6638 userId); 6639 } 6640 } 6641 } 6642 6643 return new ParceledListSlice<PackageInfo>(list); 6644 } 6645 } 6646 6647 @Override 6648 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6649 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6650 flags = updateFlagsForApplication(flags, userId, null); 6651 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6652 6653 // writer 6654 synchronized (mPackages) { 6655 ArrayList<ApplicationInfo> list; 6656 if (listUninstalled) { 6657 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6658 for (PackageSetting ps : mSettings.mPackages.values()) { 6659 ApplicationInfo ai; 6660 int effectiveFlags = flags; 6661 if (ps.isSystem()) { 6662 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6663 } 6664 if (ps.pkg != null) { 6665 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6666 ps.readUserState(userId), userId); 6667 } else { 6668 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6669 userId); 6670 } 6671 if (ai != null) { 6672 list.add(ai); 6673 } 6674 } 6675 } else { 6676 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6677 for (PackageParser.Package p : mPackages.values()) { 6678 if (p.mExtras != null) { 6679 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6680 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6681 if (ai != null) { 6682 list.add(ai); 6683 } 6684 } 6685 } 6686 } 6687 6688 return new ParceledListSlice<ApplicationInfo>(list); 6689 } 6690 } 6691 6692 @Override 6693 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6694 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6695 return null; 6696 } 6697 6698 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6699 "getEphemeralApplications"); 6700 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6701 true /* requireFullPermission */, false /* checkShell */, 6702 "getEphemeralApplications"); 6703 synchronized (mPackages) { 6704 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6705 .getEphemeralApplicationsLPw(userId); 6706 if (ephemeralApps != null) { 6707 return new ParceledListSlice<>(ephemeralApps); 6708 } 6709 } 6710 return null; 6711 } 6712 6713 @Override 6714 public boolean isEphemeralApplication(String packageName, int userId) { 6715 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6716 true /* requireFullPermission */, false /* checkShell */, 6717 "isEphemeral"); 6718 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6719 return false; 6720 } 6721 6722 if (!isCallerSameApp(packageName)) { 6723 return false; 6724 } 6725 synchronized (mPackages) { 6726 PackageParser.Package pkg = mPackages.get(packageName); 6727 if (pkg != null) { 6728 return pkg.applicationInfo.isEphemeralApp(); 6729 } 6730 } 6731 return false; 6732 } 6733 6734 @Override 6735 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6736 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6737 return null; 6738 } 6739 6740 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6741 true /* requireFullPermission */, false /* checkShell */, 6742 "getCookie"); 6743 if (!isCallerSameApp(packageName)) { 6744 return null; 6745 } 6746 synchronized (mPackages) { 6747 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6748 packageName, userId); 6749 } 6750 } 6751 6752 @Override 6753 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6754 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6755 return true; 6756 } 6757 6758 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6759 true /* requireFullPermission */, true /* checkShell */, 6760 "setCookie"); 6761 if (!isCallerSameApp(packageName)) { 6762 return false; 6763 } 6764 synchronized (mPackages) { 6765 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6766 packageName, cookie, userId); 6767 } 6768 } 6769 6770 @Override 6771 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6772 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6773 return null; 6774 } 6775 6776 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6777 "getEphemeralApplicationIcon"); 6778 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6779 true /* requireFullPermission */, false /* checkShell */, 6780 "getEphemeralApplicationIcon"); 6781 synchronized (mPackages) { 6782 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6783 packageName, userId); 6784 } 6785 } 6786 6787 private boolean isCallerSameApp(String packageName) { 6788 PackageParser.Package pkg = mPackages.get(packageName); 6789 return pkg != null 6790 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6791 } 6792 6793 @Override 6794 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6795 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6796 } 6797 6798 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6799 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6800 6801 // reader 6802 synchronized (mPackages) { 6803 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6804 final int userId = UserHandle.getCallingUserId(); 6805 while (i.hasNext()) { 6806 final PackageParser.Package p = i.next(); 6807 if (p.applicationInfo == null) continue; 6808 6809 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6810 && !p.applicationInfo.isDirectBootAware(); 6811 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6812 && p.applicationInfo.isDirectBootAware(); 6813 6814 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6815 && (!mSafeMode || isSystemApp(p)) 6816 && (matchesUnaware || matchesAware)) { 6817 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6818 if (ps != null) { 6819 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6820 ps.readUserState(userId), userId); 6821 if (ai != null) { 6822 finalList.add(ai); 6823 } 6824 } 6825 } 6826 } 6827 } 6828 6829 return finalList; 6830 } 6831 6832 @Override 6833 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6834 if (!sUserManager.exists(userId)) return null; 6835 flags = updateFlagsForComponent(flags, userId, name); 6836 // reader 6837 synchronized (mPackages) { 6838 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6839 PackageSetting ps = provider != null 6840 ? mSettings.mPackages.get(provider.owner.packageName) 6841 : null; 6842 return ps != null 6843 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6844 ? PackageParser.generateProviderInfo(provider, flags, 6845 ps.readUserState(userId), userId) 6846 : null; 6847 } 6848 } 6849 6850 /** 6851 * @deprecated 6852 */ 6853 @Deprecated 6854 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6855 // reader 6856 synchronized (mPackages) { 6857 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6858 .entrySet().iterator(); 6859 final int userId = UserHandle.getCallingUserId(); 6860 while (i.hasNext()) { 6861 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6862 PackageParser.Provider p = entry.getValue(); 6863 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6864 6865 if (ps != null && p.syncable 6866 && (!mSafeMode || (p.info.applicationInfo.flags 6867 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6868 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6869 ps.readUserState(userId), userId); 6870 if (info != null) { 6871 outNames.add(entry.getKey()); 6872 outInfo.add(info); 6873 } 6874 } 6875 } 6876 } 6877 } 6878 6879 @Override 6880 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6881 int uid, int flags) { 6882 final int userId = processName != null ? UserHandle.getUserId(uid) 6883 : UserHandle.getCallingUserId(); 6884 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6885 flags = updateFlagsForComponent(flags, userId, processName); 6886 6887 ArrayList<ProviderInfo> finalList = null; 6888 // reader 6889 synchronized (mPackages) { 6890 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6891 while (i.hasNext()) { 6892 final PackageParser.Provider p = i.next(); 6893 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6894 if (ps != null && p.info.authority != null 6895 && (processName == null 6896 || (p.info.processName.equals(processName) 6897 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6898 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6899 if (finalList == null) { 6900 finalList = new ArrayList<ProviderInfo>(3); 6901 } 6902 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6903 ps.readUserState(userId), userId); 6904 if (info != null) { 6905 finalList.add(info); 6906 } 6907 } 6908 } 6909 } 6910 6911 if (finalList != null) { 6912 Collections.sort(finalList, mProviderInitOrderSorter); 6913 return new ParceledListSlice<ProviderInfo>(finalList); 6914 } 6915 6916 return ParceledListSlice.emptyList(); 6917 } 6918 6919 @Override 6920 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6921 // reader 6922 synchronized (mPackages) { 6923 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6924 return PackageParser.generateInstrumentationInfo(i, flags); 6925 } 6926 } 6927 6928 @Override 6929 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6930 String targetPackage, int flags) { 6931 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6932 } 6933 6934 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6935 int flags) { 6936 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6937 6938 // reader 6939 synchronized (mPackages) { 6940 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6941 while (i.hasNext()) { 6942 final PackageParser.Instrumentation p = i.next(); 6943 if (targetPackage == null 6944 || targetPackage.equals(p.info.targetPackage)) { 6945 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6946 flags); 6947 if (ii != null) { 6948 finalList.add(ii); 6949 } 6950 } 6951 } 6952 } 6953 6954 return finalList; 6955 } 6956 6957 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6958 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6959 if (overlays == null) { 6960 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6961 return; 6962 } 6963 for (PackageParser.Package opkg : overlays.values()) { 6964 // Not much to do if idmap fails: we already logged the error 6965 // and we certainly don't want to abort installation of pkg simply 6966 // because an overlay didn't fit properly. For these reasons, 6967 // ignore the return value of createIdmapForPackagePairLI. 6968 createIdmapForPackagePairLI(pkg, opkg); 6969 } 6970 } 6971 6972 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6973 PackageParser.Package opkg) { 6974 if (!opkg.mTrustedOverlay) { 6975 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6976 opkg.baseCodePath + ": overlay not trusted"); 6977 return false; 6978 } 6979 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6980 if (overlaySet == null) { 6981 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6982 opkg.baseCodePath + " but target package has no known overlays"); 6983 return false; 6984 } 6985 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6986 // TODO: generate idmap for split APKs 6987 try { 6988 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6989 } catch (InstallerException e) { 6990 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6991 + opkg.baseCodePath); 6992 return false; 6993 } 6994 PackageParser.Package[] overlayArray = 6995 overlaySet.values().toArray(new PackageParser.Package[0]); 6996 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6997 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6998 return p1.mOverlayPriority - p2.mOverlayPriority; 6999 } 7000 }; 7001 Arrays.sort(overlayArray, cmp); 7002 7003 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7004 int i = 0; 7005 for (PackageParser.Package p : overlayArray) { 7006 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7007 } 7008 return true; 7009 } 7010 7011 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7012 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7013 try { 7014 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7015 } finally { 7016 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7017 } 7018 } 7019 7020 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7021 final File[] files = dir.listFiles(); 7022 if (ArrayUtils.isEmpty(files)) { 7023 Log.d(TAG, "No files in app dir " + dir); 7024 return; 7025 } 7026 7027 if (DEBUG_PACKAGE_SCANNING) { 7028 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7029 + " flags=0x" + Integer.toHexString(parseFlags)); 7030 } 7031 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7032 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7033 7034 // Submit files for parsing in parallel 7035 int fileCount = 0; 7036 for (File file : files) { 7037 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7038 && !PackageInstallerService.isStageName(file.getName()); 7039 if (!isPackage) { 7040 // Ignore entries which are not packages 7041 continue; 7042 } 7043 parallelPackageParser.submit(file, parseFlags); 7044 fileCount++; 7045 } 7046 7047 // Process results one by one 7048 for (; fileCount > 0; fileCount--) { 7049 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7050 Throwable throwable = parseResult.throwable; 7051 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7052 7053 if (throwable == null) { 7054 try { 7055 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7056 currentTime, null); 7057 } catch (PackageManagerException e) { 7058 errorCode = e.error; 7059 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7060 } 7061 } else if (throwable instanceof PackageParser.PackageParserException) { 7062 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7063 throwable; 7064 errorCode = e.error; 7065 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7066 } else { 7067 throw new IllegalStateException("Unexpected exception occurred while parsing " 7068 + parseResult.scanFile, throwable); 7069 } 7070 7071 // Delete invalid userdata apps 7072 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7073 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7074 logCriticalInfo(Log.WARN, 7075 "Deleting invalid package at " + parseResult.scanFile); 7076 removeCodePathLI(parseResult.scanFile); 7077 } 7078 } 7079 parallelPackageParser.close(); 7080 } 7081 7082 private static File getSettingsProblemFile() { 7083 File dataDir = Environment.getDataDirectory(); 7084 File systemDir = new File(dataDir, "system"); 7085 File fname = new File(systemDir, "uiderrors.txt"); 7086 return fname; 7087 } 7088 7089 static void reportSettingsProblem(int priority, String msg) { 7090 logCriticalInfo(priority, msg); 7091 } 7092 7093 static void logCriticalInfo(int priority, String msg) { 7094 Slog.println(priority, TAG, msg); 7095 EventLogTags.writePmCriticalInfo(msg); 7096 try { 7097 File fname = getSettingsProblemFile(); 7098 FileOutputStream out = new FileOutputStream(fname, true); 7099 PrintWriter pw = new FastPrintWriter(out); 7100 SimpleDateFormat formatter = new SimpleDateFormat(); 7101 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7102 pw.println(dateString + ": " + msg); 7103 pw.close(); 7104 FileUtils.setPermissions( 7105 fname.toString(), 7106 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7107 -1, -1); 7108 } catch (java.io.IOException e) { 7109 } 7110 } 7111 7112 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7113 if (srcFile.isDirectory()) { 7114 final File baseFile = new File(pkg.baseCodePath); 7115 long maxModifiedTime = baseFile.lastModified(); 7116 if (pkg.splitCodePaths != null) { 7117 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7118 final File splitFile = new File(pkg.splitCodePaths[i]); 7119 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7120 } 7121 } 7122 return maxModifiedTime; 7123 } 7124 return srcFile.lastModified(); 7125 } 7126 7127 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7128 final int policyFlags) throws PackageManagerException { 7129 // When upgrading from pre-N MR1, verify the package time stamp using the package 7130 // directory and not the APK file. 7131 final long lastModifiedTime = mIsPreNMR1Upgrade 7132 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7133 if (ps != null 7134 && ps.codePath.equals(srcFile) 7135 && ps.timeStamp == lastModifiedTime 7136 && !isCompatSignatureUpdateNeeded(pkg) 7137 && !isRecoverSignatureUpdateNeeded(pkg)) { 7138 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7139 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7140 ArraySet<PublicKey> signingKs; 7141 synchronized (mPackages) { 7142 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7143 } 7144 if (ps.signatures.mSignatures != null 7145 && ps.signatures.mSignatures.length != 0 7146 && signingKs != null) { 7147 // Optimization: reuse the existing cached certificates 7148 // if the package appears to be unchanged. 7149 pkg.mSignatures = ps.signatures.mSignatures; 7150 pkg.mSigningKeys = signingKs; 7151 return; 7152 } 7153 7154 Slog.w(TAG, "PackageSetting for " + ps.name 7155 + " is missing signatures. Collecting certs again to recover them."); 7156 } else { 7157 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7158 } 7159 7160 try { 7161 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7162 PackageParser.collectCertificates(pkg, policyFlags); 7163 } catch (PackageParserException e) { 7164 throw PackageManagerException.from(e); 7165 } finally { 7166 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7167 } 7168 } 7169 7170 /** 7171 * Traces a package scan. 7172 * @see #scanPackageLI(File, int, int, long, UserHandle) 7173 */ 7174 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7175 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7176 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7177 try { 7178 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7179 } finally { 7180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7181 } 7182 } 7183 7184 /** 7185 * Scans a package and returns the newly parsed package. 7186 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7187 */ 7188 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7189 long currentTime, UserHandle user) throws PackageManagerException { 7190 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7191 PackageParser pp = new PackageParser(); 7192 pp.setSeparateProcesses(mSeparateProcesses); 7193 pp.setOnlyCoreApps(mOnlyCore); 7194 pp.setDisplayMetrics(mMetrics); 7195 7196 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7197 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7198 } 7199 7200 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7201 final PackageParser.Package pkg; 7202 try { 7203 pkg = pp.parsePackage(scanFile, parseFlags); 7204 } catch (PackageParserException e) { 7205 throw PackageManagerException.from(e); 7206 } finally { 7207 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7208 } 7209 7210 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7211 } 7212 7213 /** 7214 * Scans a package and returns the newly parsed package. 7215 * @throws PackageManagerException on a parse error. 7216 */ 7217 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7218 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7219 throws PackageManagerException { 7220 // If the package has children and this is the first dive in the function 7221 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7222 // packages (parent and children) would be successfully scanned before the 7223 // actual scan since scanning mutates internal state and we want to atomically 7224 // install the package and its children. 7225 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7226 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7227 scanFlags |= SCAN_CHECK_ONLY; 7228 } 7229 } else { 7230 scanFlags &= ~SCAN_CHECK_ONLY; 7231 } 7232 7233 // Scan the parent 7234 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7235 scanFlags, currentTime, user); 7236 7237 // Scan the children 7238 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7239 for (int i = 0; i < childCount; i++) { 7240 PackageParser.Package childPackage = pkg.childPackages.get(i); 7241 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7242 currentTime, user); 7243 } 7244 7245 7246 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7247 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7248 } 7249 7250 return scannedPkg; 7251 } 7252 7253 /** 7254 * Scans a package and returns the newly parsed package. 7255 * @throws PackageManagerException on a parse error. 7256 */ 7257 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7258 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7259 throws PackageManagerException { 7260 PackageSetting ps = null; 7261 PackageSetting updatedPkg; 7262 // reader 7263 synchronized (mPackages) { 7264 // Look to see if we already know about this package. 7265 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7266 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7267 // This package has been renamed to its original name. Let's 7268 // use that. 7269 ps = mSettings.getPackageLPr(oldName); 7270 } 7271 // If there was no original package, see one for the real package name. 7272 if (ps == null) { 7273 ps = mSettings.getPackageLPr(pkg.packageName); 7274 } 7275 // Check to see if this package could be hiding/updating a system 7276 // package. Must look for it either under the original or real 7277 // package name depending on our state. 7278 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7279 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7280 7281 // If this is a package we don't know about on the system partition, we 7282 // may need to remove disabled child packages on the system partition 7283 // or may need to not add child packages if the parent apk is updated 7284 // on the data partition and no longer defines this child package. 7285 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7286 // If this is a parent package for an updated system app and this system 7287 // app got an OTA update which no longer defines some of the child packages 7288 // we have to prune them from the disabled system packages. 7289 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7290 if (disabledPs != null) { 7291 final int scannedChildCount = (pkg.childPackages != null) 7292 ? pkg.childPackages.size() : 0; 7293 final int disabledChildCount = disabledPs.childPackageNames != null 7294 ? disabledPs.childPackageNames.size() : 0; 7295 for (int i = 0; i < disabledChildCount; i++) { 7296 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7297 boolean disabledPackageAvailable = false; 7298 for (int j = 0; j < scannedChildCount; j++) { 7299 PackageParser.Package childPkg = pkg.childPackages.get(j); 7300 if (childPkg.packageName.equals(disabledChildPackageName)) { 7301 disabledPackageAvailable = true; 7302 break; 7303 } 7304 } 7305 if (!disabledPackageAvailable) { 7306 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7307 } 7308 } 7309 } 7310 } 7311 } 7312 7313 boolean updatedPkgBetter = false; 7314 // First check if this is a system package that may involve an update 7315 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7316 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7317 // it needs to drop FLAG_PRIVILEGED. 7318 if (locationIsPrivileged(scanFile)) { 7319 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7320 } else { 7321 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7322 } 7323 7324 if (ps != null && !ps.codePath.equals(scanFile)) { 7325 // The path has changed from what was last scanned... check the 7326 // version of the new path against what we have stored to determine 7327 // what to do. 7328 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7329 if (pkg.mVersionCode <= ps.versionCode) { 7330 // The system package has been updated and the code path does not match 7331 // Ignore entry. Skip it. 7332 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7333 + " ignored: updated version " + ps.versionCode 7334 + " better than this " + pkg.mVersionCode); 7335 if (!updatedPkg.codePath.equals(scanFile)) { 7336 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7337 + ps.name + " changing from " + updatedPkg.codePathString 7338 + " to " + scanFile); 7339 updatedPkg.codePath = scanFile; 7340 updatedPkg.codePathString = scanFile.toString(); 7341 updatedPkg.resourcePath = scanFile; 7342 updatedPkg.resourcePathString = scanFile.toString(); 7343 } 7344 updatedPkg.pkg = pkg; 7345 updatedPkg.versionCode = pkg.mVersionCode; 7346 7347 // Update the disabled system child packages to point to the package too. 7348 final int childCount = updatedPkg.childPackageNames != null 7349 ? updatedPkg.childPackageNames.size() : 0; 7350 for (int i = 0; i < childCount; i++) { 7351 String childPackageName = updatedPkg.childPackageNames.get(i); 7352 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7353 childPackageName); 7354 if (updatedChildPkg != null) { 7355 updatedChildPkg.pkg = pkg; 7356 updatedChildPkg.versionCode = pkg.mVersionCode; 7357 } 7358 } 7359 7360 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7361 + scanFile + " ignored: updated version " + ps.versionCode 7362 + " better than this " + pkg.mVersionCode); 7363 } else { 7364 // The current app on the system partition is better than 7365 // what we have updated to on the data partition; switch 7366 // back to the system partition version. 7367 // At this point, its safely assumed that package installation for 7368 // apps in system partition will go through. If not there won't be a working 7369 // version of the app 7370 // writer 7371 synchronized (mPackages) { 7372 // Just remove the loaded entries from package lists. 7373 mPackages.remove(ps.name); 7374 } 7375 7376 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7377 + " reverting from " + ps.codePathString 7378 + ": new version " + pkg.mVersionCode 7379 + " better than installed " + ps.versionCode); 7380 7381 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7382 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7383 synchronized (mInstallLock) { 7384 args.cleanUpResourcesLI(); 7385 } 7386 synchronized (mPackages) { 7387 mSettings.enableSystemPackageLPw(ps.name); 7388 } 7389 updatedPkgBetter = true; 7390 } 7391 } 7392 } 7393 7394 if (updatedPkg != null) { 7395 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7396 // initially 7397 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7398 7399 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7400 // flag set initially 7401 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7402 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7403 } 7404 } 7405 7406 // Verify certificates against what was last scanned 7407 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7408 7409 /* 7410 * A new system app appeared, but we already had a non-system one of the 7411 * same name installed earlier. 7412 */ 7413 boolean shouldHideSystemApp = false; 7414 if (updatedPkg == null && ps != null 7415 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7416 /* 7417 * Check to make sure the signatures match first. If they don't, 7418 * wipe the installed application and its data. 7419 */ 7420 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7421 != PackageManager.SIGNATURE_MATCH) { 7422 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7423 + " signatures don't match existing userdata copy; removing"); 7424 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7425 "scanPackageInternalLI")) { 7426 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7427 } 7428 ps = null; 7429 } else { 7430 /* 7431 * If the newly-added system app is an older version than the 7432 * already installed version, hide it. It will be scanned later 7433 * and re-added like an update. 7434 */ 7435 if (pkg.mVersionCode <= ps.versionCode) { 7436 shouldHideSystemApp = true; 7437 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7438 + " but new version " + pkg.mVersionCode + " better than installed " 7439 + ps.versionCode + "; hiding system"); 7440 } else { 7441 /* 7442 * The newly found system app is a newer version that the 7443 * one previously installed. Simply remove the 7444 * already-installed application and replace it with our own 7445 * while keeping the application data. 7446 */ 7447 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7448 + " reverting from " + ps.codePathString + ": new version " 7449 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7450 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7451 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7452 synchronized (mInstallLock) { 7453 args.cleanUpResourcesLI(); 7454 } 7455 } 7456 } 7457 } 7458 7459 // The apk is forward locked (not public) if its code and resources 7460 // are kept in different files. (except for app in either system or 7461 // vendor path). 7462 // TODO grab this value from PackageSettings 7463 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7464 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7465 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7466 } 7467 } 7468 7469 // TODO: extend to support forward-locked splits 7470 String resourcePath = null; 7471 String baseResourcePath = null; 7472 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7473 if (ps != null && ps.resourcePathString != null) { 7474 resourcePath = ps.resourcePathString; 7475 baseResourcePath = ps.resourcePathString; 7476 } else { 7477 // Should not happen at all. Just log an error. 7478 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7479 } 7480 } else { 7481 resourcePath = pkg.codePath; 7482 baseResourcePath = pkg.baseCodePath; 7483 } 7484 7485 // Set application objects path explicitly. 7486 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7487 pkg.setApplicationInfoCodePath(pkg.codePath); 7488 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7489 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7490 pkg.setApplicationInfoResourcePath(resourcePath); 7491 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7492 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7493 7494 // Note that we invoke the following method only if we are about to unpack an application 7495 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7496 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7497 7498 /* 7499 * If the system app should be overridden by a previously installed 7500 * data, hide the system app now and let the /data/app scan pick it up 7501 * again. 7502 */ 7503 if (shouldHideSystemApp) { 7504 synchronized (mPackages) { 7505 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7506 } 7507 } 7508 7509 return scannedPkg; 7510 } 7511 7512 private static String fixProcessName(String defProcessName, 7513 String processName) { 7514 if (processName == null) { 7515 return defProcessName; 7516 } 7517 return processName; 7518 } 7519 7520 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7521 throws PackageManagerException { 7522 if (pkgSetting.signatures.mSignatures != null) { 7523 // Already existing package. Make sure signatures match 7524 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7525 == PackageManager.SIGNATURE_MATCH; 7526 if (!match) { 7527 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7528 == PackageManager.SIGNATURE_MATCH; 7529 } 7530 if (!match) { 7531 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7532 == PackageManager.SIGNATURE_MATCH; 7533 } 7534 if (!match) { 7535 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7536 + pkg.packageName + " signatures do not match the " 7537 + "previously installed version; ignoring!"); 7538 } 7539 } 7540 7541 // Check for shared user signatures 7542 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7543 // Already existing package. Make sure signatures match 7544 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7545 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7546 if (!match) { 7547 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7548 == PackageManager.SIGNATURE_MATCH; 7549 } 7550 if (!match) { 7551 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7552 == PackageManager.SIGNATURE_MATCH; 7553 } 7554 if (!match) { 7555 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7556 "Package " + pkg.packageName 7557 + " has no signatures that match those in shared user " 7558 + pkgSetting.sharedUser.name + "; ignoring!"); 7559 } 7560 } 7561 } 7562 7563 /** 7564 * Enforces that only the system UID or root's UID can call a method exposed 7565 * via Binder. 7566 * 7567 * @param message used as message if SecurityException is thrown 7568 * @throws SecurityException if the caller is not system or root 7569 */ 7570 private static final void enforceSystemOrRoot(String message) { 7571 final int uid = Binder.getCallingUid(); 7572 if (uid != Process.SYSTEM_UID && uid != 0) { 7573 throw new SecurityException(message); 7574 } 7575 } 7576 7577 @Override 7578 public void performFstrimIfNeeded() { 7579 enforceSystemOrRoot("Only the system can request fstrim"); 7580 7581 // Before everything else, see whether we need to fstrim. 7582 try { 7583 IStorageManager sm = PackageHelper.getStorageManager(); 7584 if (sm != null) { 7585 boolean doTrim = false; 7586 final long interval = android.provider.Settings.Global.getLong( 7587 mContext.getContentResolver(), 7588 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7589 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7590 if (interval > 0) { 7591 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7592 if (timeSinceLast > interval) { 7593 doTrim = true; 7594 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7595 + "; running immediately"); 7596 } 7597 } 7598 if (doTrim) { 7599 final boolean dexOptDialogShown; 7600 synchronized (mPackages) { 7601 dexOptDialogShown = mDexOptDialogShown; 7602 } 7603 if (!isFirstBoot() && dexOptDialogShown) { 7604 try { 7605 ActivityManager.getService().showBootMessage( 7606 mContext.getResources().getString( 7607 R.string.android_upgrading_fstrim), true); 7608 } catch (RemoteException e) { 7609 } 7610 } 7611 sm.runMaintenance(); 7612 } 7613 } else { 7614 Slog.e(TAG, "storageManager service unavailable!"); 7615 } 7616 } catch (RemoteException e) { 7617 // Can't happen; StorageManagerService is local 7618 } 7619 } 7620 7621 @Override 7622 public void updatePackagesIfNeeded() { 7623 enforceSystemOrRoot("Only the system can request package update"); 7624 7625 // We need to re-extract after an OTA. 7626 boolean causeUpgrade = isUpgrade(); 7627 7628 // First boot or factory reset. 7629 // Note: we also handle devices that are upgrading to N right now as if it is their 7630 // first boot, as they do not have profile data. 7631 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7632 7633 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7634 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7635 7636 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7637 return; 7638 } 7639 7640 List<PackageParser.Package> pkgs; 7641 synchronized (mPackages) { 7642 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7643 } 7644 7645 final long startTime = System.nanoTime(); 7646 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7647 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7648 7649 final int elapsedTimeSeconds = 7650 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7651 7652 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7653 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7654 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7655 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7656 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7657 } 7658 7659 /** 7660 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7661 * containing statistics about the invocation. The array consists of three elements, 7662 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7663 * and {@code numberOfPackagesFailed}. 7664 */ 7665 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7666 String compilerFilter) { 7667 7668 int numberOfPackagesVisited = 0; 7669 int numberOfPackagesOptimized = 0; 7670 int numberOfPackagesSkipped = 0; 7671 int numberOfPackagesFailed = 0; 7672 final int numberOfPackagesToDexopt = pkgs.size(); 7673 7674 for (PackageParser.Package pkg : pkgs) { 7675 numberOfPackagesVisited++; 7676 7677 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7678 if (DEBUG_DEXOPT) { 7679 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7680 } 7681 numberOfPackagesSkipped++; 7682 continue; 7683 } 7684 7685 if (DEBUG_DEXOPT) { 7686 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7687 numberOfPackagesToDexopt + ": " + pkg.packageName); 7688 } 7689 7690 if (showDialog) { 7691 try { 7692 ActivityManager.getService().showBootMessage( 7693 mContext.getResources().getString(R.string.android_upgrading_apk, 7694 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7695 } catch (RemoteException e) { 7696 } 7697 synchronized (mPackages) { 7698 mDexOptDialogShown = true; 7699 } 7700 } 7701 7702 // If the OTA updates a system app which was previously preopted to a non-preopted state 7703 // the app might end up being verified at runtime. That's because by default the apps 7704 // are verify-profile but for preopted apps there's no profile. 7705 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7706 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7707 // filter (by default interpret-only). 7708 // Note that at this stage unused apps are already filtered. 7709 if (isSystemApp(pkg) && 7710 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7711 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7712 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7713 } 7714 7715 // checkProfiles is false to avoid merging profiles during boot which 7716 // might interfere with background compilation (b/28612421). 7717 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7718 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7719 // trade-off worth doing to save boot time work. 7720 int dexOptStatus = performDexOptTraced(pkg.packageName, 7721 false /* checkProfiles */, 7722 compilerFilter, 7723 false /* force */); 7724 switch (dexOptStatus) { 7725 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7726 numberOfPackagesOptimized++; 7727 break; 7728 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7729 numberOfPackagesSkipped++; 7730 break; 7731 case PackageDexOptimizer.DEX_OPT_FAILED: 7732 numberOfPackagesFailed++; 7733 break; 7734 default: 7735 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7736 break; 7737 } 7738 } 7739 7740 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7741 numberOfPackagesFailed }; 7742 } 7743 7744 @Override 7745 public void notifyPackageUse(String packageName, int reason) { 7746 synchronized (mPackages) { 7747 PackageParser.Package p = mPackages.get(packageName); 7748 if (p == null) { 7749 return; 7750 } 7751 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7752 } 7753 } 7754 7755 @Override 7756 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 7757 int userId = UserHandle.getCallingUserId(); 7758 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 7759 if (ai == null) { 7760 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 7761 + loadingPackageName + ", user=" + userId); 7762 return; 7763 } 7764 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 7765 } 7766 7767 // TODO: this is not used nor needed. Delete it. 7768 @Override 7769 public boolean performDexOptIfNeeded(String packageName) { 7770 int dexOptStatus = performDexOptTraced(packageName, 7771 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7772 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7773 } 7774 7775 @Override 7776 public boolean performDexOpt(String packageName, 7777 boolean checkProfiles, int compileReason, boolean force) { 7778 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7779 getCompilerFilterForReason(compileReason), force); 7780 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7781 } 7782 7783 @Override 7784 public boolean performDexOptMode(String packageName, 7785 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7786 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7787 targetCompilerFilter, force); 7788 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7789 } 7790 7791 private int performDexOptTraced(String packageName, 7792 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7793 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7794 try { 7795 return performDexOptInternal(packageName, checkProfiles, 7796 targetCompilerFilter, force); 7797 } finally { 7798 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7799 } 7800 } 7801 7802 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7803 // if the package can now be considered up to date for the given filter. 7804 private int performDexOptInternal(String packageName, 7805 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7806 PackageParser.Package p; 7807 synchronized (mPackages) { 7808 p = mPackages.get(packageName); 7809 if (p == null) { 7810 // Package could not be found. Report failure. 7811 return PackageDexOptimizer.DEX_OPT_FAILED; 7812 } 7813 mPackageUsage.maybeWriteAsync(mPackages); 7814 mCompilerStats.maybeWriteAsync(); 7815 } 7816 long callingId = Binder.clearCallingIdentity(); 7817 try { 7818 synchronized (mInstallLock) { 7819 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7820 targetCompilerFilter, force); 7821 } 7822 } finally { 7823 Binder.restoreCallingIdentity(callingId); 7824 } 7825 } 7826 7827 public ArraySet<String> getOptimizablePackages() { 7828 ArraySet<String> pkgs = new ArraySet<String>(); 7829 synchronized (mPackages) { 7830 for (PackageParser.Package p : mPackages.values()) { 7831 if (PackageDexOptimizer.canOptimizePackage(p)) { 7832 pkgs.add(p.packageName); 7833 } 7834 } 7835 } 7836 return pkgs; 7837 } 7838 7839 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7840 boolean checkProfiles, String targetCompilerFilter, 7841 boolean force) { 7842 // Select the dex optimizer based on the force parameter. 7843 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7844 // allocate an object here. 7845 PackageDexOptimizer pdo = force 7846 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7847 : mPackageDexOptimizer; 7848 7849 // Optimize all dependencies first. Note: we ignore the return value and march on 7850 // on errors. 7851 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7852 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7853 if (!deps.isEmpty()) { 7854 for (PackageParser.Package depPackage : deps) { 7855 // TODO: Analyze and investigate if we (should) profile libraries. 7856 // Currently this will do a full compilation of the library by default. 7857 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7858 false /* checkProfiles */, 7859 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7860 getOrCreateCompilerPackageStats(depPackage)); 7861 } 7862 } 7863 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7864 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7865 } 7866 7867 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7868 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7869 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7870 Set<String> collectedNames = new HashSet<>(); 7871 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7872 7873 retValue.remove(p); 7874 7875 return retValue; 7876 } else { 7877 return Collections.emptyList(); 7878 } 7879 } 7880 7881 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7882 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7883 if (!collectedNames.contains(p.packageName)) { 7884 collectedNames.add(p.packageName); 7885 collected.add(p); 7886 7887 if (p.usesLibraries != null) { 7888 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7889 } 7890 if (p.usesOptionalLibraries != null) { 7891 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7892 collectedNames); 7893 } 7894 } 7895 } 7896 7897 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7898 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7899 for (String libName : libs) { 7900 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7901 if (libPkg != null) { 7902 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7903 } 7904 } 7905 } 7906 7907 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7908 synchronized (mPackages) { 7909 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7910 if (lib != null && lib.apk != null) { 7911 return mPackages.get(lib.apk); 7912 } 7913 } 7914 return null; 7915 } 7916 7917 public void shutdown() { 7918 mPackageUsage.writeNow(mPackages); 7919 mCompilerStats.writeNow(); 7920 } 7921 7922 @Override 7923 public void dumpProfiles(String packageName) { 7924 PackageParser.Package pkg; 7925 synchronized (mPackages) { 7926 pkg = mPackages.get(packageName); 7927 if (pkg == null) { 7928 throw new IllegalArgumentException("Unknown package: " + packageName); 7929 } 7930 } 7931 /* Only the shell, root, or the app user should be able to dump profiles. */ 7932 int callingUid = Binder.getCallingUid(); 7933 if (callingUid != Process.SHELL_UID && 7934 callingUid != Process.ROOT_UID && 7935 callingUid != pkg.applicationInfo.uid) { 7936 throw new SecurityException("dumpProfiles"); 7937 } 7938 7939 synchronized (mInstallLock) { 7940 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7941 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7942 try { 7943 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7944 String codePaths = TextUtils.join(";", allCodePaths); 7945 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 7946 } catch (InstallerException e) { 7947 Slog.w(TAG, "Failed to dump profiles", e); 7948 } 7949 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7950 } 7951 } 7952 7953 @Override 7954 public void forceDexOpt(String packageName) { 7955 enforceSystemOrRoot("forceDexOpt"); 7956 7957 PackageParser.Package pkg; 7958 synchronized (mPackages) { 7959 pkg = mPackages.get(packageName); 7960 if (pkg == null) { 7961 throw new IllegalArgumentException("Unknown package: " + packageName); 7962 } 7963 } 7964 7965 synchronized (mInstallLock) { 7966 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7967 7968 // Whoever is calling forceDexOpt wants a fully compiled package. 7969 // Don't use profiles since that may cause compilation to be skipped. 7970 final int res = performDexOptInternalWithDependenciesLI(pkg, 7971 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7972 true /* force */); 7973 7974 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7975 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7976 throw new IllegalStateException("Failed to dexopt: " + res); 7977 } 7978 } 7979 } 7980 7981 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7982 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7983 Slog.w(TAG, "Unable to update from " + oldPkg.name 7984 + " to " + newPkg.packageName 7985 + ": old package not in system partition"); 7986 return false; 7987 } else if (mPackages.get(oldPkg.name) != null) { 7988 Slog.w(TAG, "Unable to update from " + oldPkg.name 7989 + " to " + newPkg.packageName 7990 + ": old package still exists"); 7991 return false; 7992 } 7993 return true; 7994 } 7995 7996 void removeCodePathLI(File codePath) { 7997 if (codePath.isDirectory()) { 7998 try { 7999 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8000 } catch (InstallerException e) { 8001 Slog.w(TAG, "Failed to remove code path", e); 8002 } 8003 } else { 8004 codePath.delete(); 8005 } 8006 } 8007 8008 private int[] resolveUserIds(int userId) { 8009 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8010 } 8011 8012 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8013 if (pkg == null) { 8014 Slog.wtf(TAG, "Package was null!", new Throwable()); 8015 return; 8016 } 8017 clearAppDataLeafLIF(pkg, userId, flags); 8018 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8019 for (int i = 0; i < childCount; i++) { 8020 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8021 } 8022 } 8023 8024 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8025 final PackageSetting ps; 8026 synchronized (mPackages) { 8027 ps = mSettings.mPackages.get(pkg.packageName); 8028 } 8029 for (int realUserId : resolveUserIds(userId)) { 8030 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8031 try { 8032 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8033 ceDataInode); 8034 } catch (InstallerException e) { 8035 Slog.w(TAG, String.valueOf(e)); 8036 } 8037 } 8038 } 8039 8040 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8041 if (pkg == null) { 8042 Slog.wtf(TAG, "Package was null!", new Throwable()); 8043 return; 8044 } 8045 destroyAppDataLeafLIF(pkg, userId, flags); 8046 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8047 for (int i = 0; i < childCount; i++) { 8048 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8049 } 8050 } 8051 8052 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8053 final PackageSetting ps; 8054 synchronized (mPackages) { 8055 ps = mSettings.mPackages.get(pkg.packageName); 8056 } 8057 for (int realUserId : resolveUserIds(userId)) { 8058 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8059 try { 8060 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8061 ceDataInode); 8062 } catch (InstallerException e) { 8063 Slog.w(TAG, String.valueOf(e)); 8064 } 8065 } 8066 } 8067 8068 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8069 if (pkg == null) { 8070 Slog.wtf(TAG, "Package was null!", new Throwable()); 8071 return; 8072 } 8073 destroyAppProfilesLeafLIF(pkg); 8074 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8075 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8076 for (int i = 0; i < childCount; i++) { 8077 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8078 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8079 true /* removeBaseMarker */); 8080 } 8081 } 8082 8083 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8084 boolean removeBaseMarker) { 8085 if (pkg.isForwardLocked()) { 8086 return; 8087 } 8088 8089 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8090 try { 8091 path = PackageManagerServiceUtils.realpath(new File(path)); 8092 } catch (IOException e) { 8093 // TODO: Should we return early here ? 8094 Slog.w(TAG, "Failed to get canonical path", e); 8095 continue; 8096 } 8097 8098 final String useMarker = path.replace('/', '@'); 8099 for (int realUserId : resolveUserIds(userId)) { 8100 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8101 if (removeBaseMarker) { 8102 File foreignUseMark = new File(profileDir, useMarker); 8103 if (foreignUseMark.exists()) { 8104 if (!foreignUseMark.delete()) { 8105 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8106 + pkg.packageName); 8107 } 8108 } 8109 } 8110 8111 File[] markers = profileDir.listFiles(); 8112 if (markers != null) { 8113 final String searchString = "@" + pkg.packageName + "@"; 8114 // We also delete all markers that contain the package name we're 8115 // uninstalling. These are associated with secondary dex-files belonging 8116 // to the package. Reconstructing the path of these dex files is messy 8117 // in general. 8118 for (File marker : markers) { 8119 if (marker.getName().indexOf(searchString) > 0) { 8120 if (!marker.delete()) { 8121 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8122 + pkg.packageName); 8123 } 8124 } 8125 } 8126 } 8127 } 8128 } 8129 } 8130 8131 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8132 try { 8133 mInstaller.destroyAppProfiles(pkg.packageName); 8134 } catch (InstallerException e) { 8135 Slog.w(TAG, String.valueOf(e)); 8136 } 8137 } 8138 8139 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8140 if (pkg == null) { 8141 Slog.wtf(TAG, "Package was null!", new Throwable()); 8142 return; 8143 } 8144 clearAppProfilesLeafLIF(pkg); 8145 // We don't remove the base foreign use marker when clearing profiles because 8146 // we will rename it when the app is updated. Unlike the actual profile contents, 8147 // the foreign use marker is good across installs. 8148 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8149 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8150 for (int i = 0; i < childCount; i++) { 8151 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8152 } 8153 } 8154 8155 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8156 try { 8157 mInstaller.clearAppProfiles(pkg.packageName); 8158 } catch (InstallerException e) { 8159 Slog.w(TAG, String.valueOf(e)); 8160 } 8161 } 8162 8163 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8164 long lastUpdateTime) { 8165 // Set parent install/update time 8166 PackageSetting ps = (PackageSetting) pkg.mExtras; 8167 if (ps != null) { 8168 ps.firstInstallTime = firstInstallTime; 8169 ps.lastUpdateTime = lastUpdateTime; 8170 } 8171 // Set children install/update time 8172 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8173 for (int i = 0; i < childCount; i++) { 8174 PackageParser.Package childPkg = pkg.childPackages.get(i); 8175 ps = (PackageSetting) childPkg.mExtras; 8176 if (ps != null) { 8177 ps.firstInstallTime = firstInstallTime; 8178 ps.lastUpdateTime = lastUpdateTime; 8179 } 8180 } 8181 } 8182 8183 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8184 PackageParser.Package changingLib) { 8185 if (file.path != null) { 8186 usesLibraryFiles.add(file.path); 8187 return; 8188 } 8189 PackageParser.Package p = mPackages.get(file.apk); 8190 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8191 // If we are doing this while in the middle of updating a library apk, 8192 // then we need to make sure to use that new apk for determining the 8193 // dependencies here. (We haven't yet finished committing the new apk 8194 // to the package manager state.) 8195 if (p == null || p.packageName.equals(changingLib.packageName)) { 8196 p = changingLib; 8197 } 8198 } 8199 if (p != null) { 8200 usesLibraryFiles.addAll(p.getAllCodePaths()); 8201 } 8202 } 8203 8204 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8205 PackageParser.Package changingLib) throws PackageManagerException { 8206 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8207 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8208 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8209 for (int i=0; i<N; i++) { 8210 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8211 if (file == null) { 8212 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8213 "Package " + pkg.packageName + " requires unavailable shared library " 8214 + pkg.usesLibraries.get(i) + "; failing!"); 8215 } 8216 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8217 } 8218 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8219 for (int i=0; i<N; i++) { 8220 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8221 if (file == null) { 8222 Slog.w(TAG, "Package " + pkg.packageName 8223 + " desires unavailable shared library " 8224 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8225 } else { 8226 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8227 } 8228 } 8229 N = usesLibraryFiles.size(); 8230 if (N > 0) { 8231 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8232 } else { 8233 pkg.usesLibraryFiles = null; 8234 } 8235 } 8236 } 8237 8238 private static boolean hasString(List<String> list, List<String> which) { 8239 if (list == null) { 8240 return false; 8241 } 8242 for (int i=list.size()-1; i>=0; i--) { 8243 for (int j=which.size()-1; j>=0; j--) { 8244 if (which.get(j).equals(list.get(i))) { 8245 return true; 8246 } 8247 } 8248 } 8249 return false; 8250 } 8251 8252 private void updateAllSharedLibrariesLPw() { 8253 for (PackageParser.Package pkg : mPackages.values()) { 8254 try { 8255 updateSharedLibrariesLPr(pkg, null); 8256 } catch (PackageManagerException e) { 8257 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8258 } 8259 } 8260 } 8261 8262 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8263 PackageParser.Package changingPkg) { 8264 ArrayList<PackageParser.Package> res = null; 8265 for (PackageParser.Package pkg : mPackages.values()) { 8266 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8267 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8268 if (res == null) { 8269 res = new ArrayList<PackageParser.Package>(); 8270 } 8271 res.add(pkg); 8272 try { 8273 updateSharedLibrariesLPr(pkg, changingPkg); 8274 } catch (PackageManagerException e) { 8275 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8276 } 8277 } 8278 } 8279 return res; 8280 } 8281 8282 /** 8283 * Derive the value of the {@code cpuAbiOverride} based on the provided 8284 * value and an optional stored value from the package settings. 8285 */ 8286 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8287 String cpuAbiOverride = null; 8288 8289 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8290 cpuAbiOverride = null; 8291 } else if (abiOverride != null) { 8292 cpuAbiOverride = abiOverride; 8293 } else if (settings != null) { 8294 cpuAbiOverride = settings.cpuAbiOverrideString; 8295 } 8296 8297 return cpuAbiOverride; 8298 } 8299 8300 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8301 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8302 throws PackageManagerException { 8303 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8304 // If the package has children and this is the first dive in the function 8305 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8306 // whether all packages (parent and children) would be successfully scanned 8307 // before the actual scan since scanning mutates internal state and we want 8308 // to atomically install the package and its children. 8309 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8310 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8311 scanFlags |= SCAN_CHECK_ONLY; 8312 } 8313 } else { 8314 scanFlags &= ~SCAN_CHECK_ONLY; 8315 } 8316 8317 final PackageParser.Package scannedPkg; 8318 try { 8319 // Scan the parent 8320 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8321 // Scan the children 8322 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8323 for (int i = 0; i < childCount; i++) { 8324 PackageParser.Package childPkg = pkg.childPackages.get(i); 8325 scanPackageLI(childPkg, policyFlags, 8326 scanFlags, currentTime, user); 8327 } 8328 } finally { 8329 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8330 } 8331 8332 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8333 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8334 } 8335 8336 return scannedPkg; 8337 } 8338 8339 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8340 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8341 boolean success = false; 8342 try { 8343 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8344 currentTime, user); 8345 success = true; 8346 return res; 8347 } finally { 8348 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8349 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8350 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8351 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8352 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8353 } 8354 } 8355 } 8356 8357 /** 8358 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8359 */ 8360 private static boolean apkHasCode(String fileName) { 8361 StrictJarFile jarFile = null; 8362 try { 8363 jarFile = new StrictJarFile(fileName, 8364 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8365 return jarFile.findEntry("classes.dex") != null; 8366 } catch (IOException ignore) { 8367 } finally { 8368 try { 8369 if (jarFile != null) { 8370 jarFile.close(); 8371 } 8372 } catch (IOException ignore) {} 8373 } 8374 return false; 8375 } 8376 8377 /** 8378 * Enforces code policy for the package. This ensures that if an APK has 8379 * declared hasCode="true" in its manifest that the APK actually contains 8380 * code. 8381 * 8382 * @throws PackageManagerException If bytecode could not be found when it should exist 8383 */ 8384 private static void assertCodePolicy(PackageParser.Package pkg) 8385 throws PackageManagerException { 8386 final boolean shouldHaveCode = 8387 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8388 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8389 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8390 "Package " + pkg.baseCodePath + " code is missing"); 8391 } 8392 8393 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8394 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8395 final boolean splitShouldHaveCode = 8396 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8397 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8398 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8399 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8400 } 8401 } 8402 } 8403 } 8404 8405 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8406 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8407 throws PackageManagerException { 8408 if (DEBUG_PACKAGE_SCANNING) { 8409 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8410 Log.d(TAG, "Scanning package " + pkg.packageName); 8411 } 8412 8413 applyPolicy(pkg, policyFlags); 8414 8415 assertPackageIsValid(pkg, policyFlags, scanFlags); 8416 8417 // Initialize package source and resource directories 8418 final File scanFile = new File(pkg.codePath); 8419 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8420 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8421 8422 SharedUserSetting suid = null; 8423 PackageSetting pkgSetting = null; 8424 8425 // Getting the package setting may have a side-effect, so if we 8426 // are only checking if scan would succeed, stash a copy of the 8427 // old setting to restore at the end. 8428 PackageSetting nonMutatedPs = null; 8429 8430 // We keep references to the derived CPU Abis from settings in oder to reuse 8431 // them in the case where we're not upgrading or booting for the first time. 8432 String primaryCpuAbiFromSettings = null; 8433 String secondaryCpuAbiFromSettings = null; 8434 8435 // writer 8436 synchronized (mPackages) { 8437 if (pkg.mSharedUserId != null) { 8438 // SIDE EFFECTS; may potentially allocate a new shared user 8439 suid = mSettings.getSharedUserLPw( 8440 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8441 if (DEBUG_PACKAGE_SCANNING) { 8442 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8443 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8444 + "): packages=" + suid.packages); 8445 } 8446 } 8447 8448 // Check if we are renaming from an original package name. 8449 PackageSetting origPackage = null; 8450 String realName = null; 8451 if (pkg.mOriginalPackages != null) { 8452 // This package may need to be renamed to a previously 8453 // installed name. Let's check on that... 8454 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8455 if (pkg.mOriginalPackages.contains(renamed)) { 8456 // This package had originally been installed as the 8457 // original name, and we have already taken care of 8458 // transitioning to the new one. Just update the new 8459 // one to continue using the old name. 8460 realName = pkg.mRealPackage; 8461 if (!pkg.packageName.equals(renamed)) { 8462 // Callers into this function may have already taken 8463 // care of renaming the package; only do it here if 8464 // it is not already done. 8465 pkg.setPackageName(renamed); 8466 } 8467 } else { 8468 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8469 if ((origPackage = mSettings.getPackageLPr( 8470 pkg.mOriginalPackages.get(i))) != null) { 8471 // We do have the package already installed under its 8472 // original name... should we use it? 8473 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8474 // New package is not compatible with original. 8475 origPackage = null; 8476 continue; 8477 } else if (origPackage.sharedUser != null) { 8478 // Make sure uid is compatible between packages. 8479 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8480 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8481 + " to " + pkg.packageName + ": old uid " 8482 + origPackage.sharedUser.name 8483 + " differs from " + pkg.mSharedUserId); 8484 origPackage = null; 8485 continue; 8486 } 8487 // TODO: Add case when shared user id is added [b/28144775] 8488 } else { 8489 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8490 + pkg.packageName + " to old name " + origPackage.name); 8491 } 8492 break; 8493 } 8494 } 8495 } 8496 } 8497 8498 if (mTransferedPackages.contains(pkg.packageName)) { 8499 Slog.w(TAG, "Package " + pkg.packageName 8500 + " was transferred to another, but its .apk remains"); 8501 } 8502 8503 // See comments in nonMutatedPs declaration 8504 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8505 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8506 if (foundPs != null) { 8507 nonMutatedPs = new PackageSetting(foundPs); 8508 } 8509 } 8510 8511 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8512 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8513 if (foundPs != null) { 8514 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8515 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8516 } 8517 } 8518 8519 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8520 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8521 PackageManagerService.reportSettingsProblem(Log.WARN, 8522 "Package " + pkg.packageName + " shared user changed from " 8523 + (pkgSetting.sharedUser != null 8524 ? pkgSetting.sharedUser.name : "<nothing>") 8525 + " to " 8526 + (suid != null ? suid.name : "<nothing>") 8527 + "; replacing with new"); 8528 pkgSetting = null; 8529 } 8530 final PackageSetting oldPkgSetting = 8531 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8532 final PackageSetting disabledPkgSetting = 8533 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8534 if (pkgSetting == null) { 8535 final String parentPackageName = (pkg.parentPackage != null) 8536 ? pkg.parentPackage.packageName : null; 8537 // REMOVE SharedUserSetting from method; update in a separate call 8538 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8539 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8540 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8541 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8542 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8543 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8544 UserManagerService.getInstance()); 8545 // SIDE EFFECTS; updates system state; move elsewhere 8546 if (origPackage != null) { 8547 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8548 } 8549 mSettings.addUserToSettingLPw(pkgSetting); 8550 } else { 8551 // REMOVE SharedUserSetting from method; update in a separate call. 8552 // 8553 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8554 // secondaryCpuAbi are not known at this point so we always update them 8555 // to null here, only to reset them at a later point. 8556 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8557 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8558 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8559 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8560 UserManagerService.getInstance()); 8561 } 8562 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8563 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8564 8565 // SIDE EFFECTS; modifies system state; move elsewhere 8566 if (pkgSetting.origPackage != null) { 8567 // If we are first transitioning from an original package, 8568 // fix up the new package's name now. We need to do this after 8569 // looking up the package under its new name, so getPackageLP 8570 // can take care of fiddling things correctly. 8571 pkg.setPackageName(origPackage.name); 8572 8573 // File a report about this. 8574 String msg = "New package " + pkgSetting.realName 8575 + " renamed to replace old package " + pkgSetting.name; 8576 reportSettingsProblem(Log.WARN, msg); 8577 8578 // Make a note of it. 8579 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8580 mTransferedPackages.add(origPackage.name); 8581 } 8582 8583 // No longer need to retain this. 8584 pkgSetting.origPackage = null; 8585 } 8586 8587 // SIDE EFFECTS; modifies system state; move elsewhere 8588 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8589 // Make a note of it. 8590 mTransferedPackages.add(pkg.packageName); 8591 } 8592 8593 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8594 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8595 } 8596 8597 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8598 // Check all shared libraries and map to their actual file path. 8599 // We only do this here for apps not on a system dir, because those 8600 // are the only ones that can fail an install due to this. We 8601 // will take care of the system apps by updating all of their 8602 // library paths after the scan is done. 8603 updateSharedLibrariesLPr(pkg, null); 8604 } 8605 8606 if (mFoundPolicyFile) { 8607 SELinuxMMAC.assignSeinfoValue(pkg); 8608 } 8609 8610 pkg.applicationInfo.uid = pkgSetting.appId; 8611 pkg.mExtras = pkgSetting; 8612 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8613 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8614 // We just determined the app is signed correctly, so bring 8615 // over the latest parsed certs. 8616 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8617 } else { 8618 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8619 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8620 "Package " + pkg.packageName + " upgrade keys do not match the " 8621 + "previously installed version"); 8622 } else { 8623 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8624 String msg = "System package " + pkg.packageName 8625 + " signature changed; retaining data."; 8626 reportSettingsProblem(Log.WARN, msg); 8627 } 8628 } 8629 } else { 8630 try { 8631 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8632 verifySignaturesLP(pkgSetting, pkg); 8633 // We just determined the app is signed correctly, so bring 8634 // over the latest parsed certs. 8635 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8636 } catch (PackageManagerException e) { 8637 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8638 throw e; 8639 } 8640 // The signature has changed, but this package is in the system 8641 // image... let's recover! 8642 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8643 // However... if this package is part of a shared user, but it 8644 // doesn't match the signature of the shared user, let's fail. 8645 // What this means is that you can't change the signatures 8646 // associated with an overall shared user, which doesn't seem all 8647 // that unreasonable. 8648 if (pkgSetting.sharedUser != null) { 8649 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8650 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8651 throw new PackageManagerException( 8652 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8653 "Signature mismatch for shared user: " 8654 + pkgSetting.sharedUser); 8655 } 8656 } 8657 // File a report about this. 8658 String msg = "System package " + pkg.packageName 8659 + " signature changed; retaining data."; 8660 reportSettingsProblem(Log.WARN, msg); 8661 } 8662 } 8663 8664 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8665 // This package wants to adopt ownership of permissions from 8666 // another package. 8667 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8668 final String origName = pkg.mAdoptPermissions.get(i); 8669 final PackageSetting orig = mSettings.getPackageLPr(origName); 8670 if (orig != null) { 8671 if (verifyPackageUpdateLPr(orig, pkg)) { 8672 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8673 + pkg.packageName); 8674 // SIDE EFFECTS; updates permissions system state; move elsewhere 8675 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8676 } 8677 } 8678 } 8679 } 8680 } 8681 8682 pkg.applicationInfo.processName = fixProcessName( 8683 pkg.applicationInfo.packageName, 8684 pkg.applicationInfo.processName); 8685 8686 if (pkg != mPlatformPackage) { 8687 // Get all of our default paths setup 8688 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8689 } 8690 8691 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8692 8693 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8694 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8695 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8696 derivePackageAbi( 8697 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8698 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8699 8700 // Some system apps still use directory structure for native libraries 8701 // in which case we might end up not detecting abi solely based on apk 8702 // structure. Try to detect abi based on directory structure. 8703 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8704 pkg.applicationInfo.primaryCpuAbi == null) { 8705 setBundledAppAbisAndRoots(pkg, pkgSetting); 8706 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8707 } 8708 } else { 8709 // This is not a first boot or an upgrade, don't bother deriving the 8710 // ABI during the scan. Instead, trust the value that was stored in the 8711 // package setting. 8712 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8713 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8714 8715 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8716 8717 if (DEBUG_ABI_SELECTION) { 8718 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8719 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8720 pkg.applicationInfo.secondaryCpuAbi); 8721 } 8722 } 8723 } else { 8724 if ((scanFlags & SCAN_MOVE) != 0) { 8725 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8726 // but we already have this packages package info in the PackageSetting. We just 8727 // use that and derive the native library path based on the new codepath. 8728 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8729 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8730 } 8731 8732 // Set native library paths again. For moves, the path will be updated based on the 8733 // ABIs we've determined above. For non-moves, the path will be updated based on the 8734 // ABIs we determined during compilation, but the path will depend on the final 8735 // package path (after the rename away from the stage path). 8736 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8737 } 8738 8739 // This is a special case for the "system" package, where the ABI is 8740 // dictated by the zygote configuration (and init.rc). We should keep track 8741 // of this ABI so that we can deal with "normal" applications that run under 8742 // the same UID correctly. 8743 if (mPlatformPackage == pkg) { 8744 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8745 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8746 } 8747 8748 // If there's a mismatch between the abi-override in the package setting 8749 // and the abiOverride specified for the install. Warn about this because we 8750 // would've already compiled the app without taking the package setting into 8751 // account. 8752 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8753 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8754 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8755 " for package " + pkg.packageName); 8756 } 8757 } 8758 8759 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8760 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8761 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8762 8763 // Copy the derived override back to the parsed package, so that we can 8764 // update the package settings accordingly. 8765 pkg.cpuAbiOverride = cpuAbiOverride; 8766 8767 if (DEBUG_ABI_SELECTION) { 8768 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8769 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8770 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8771 } 8772 8773 // Push the derived path down into PackageSettings so we know what to 8774 // clean up at uninstall time. 8775 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8776 8777 if (DEBUG_ABI_SELECTION) { 8778 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8779 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8780 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8781 } 8782 8783 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8784 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8785 // We don't do this here during boot because we can do it all 8786 // at once after scanning all existing packages. 8787 // 8788 // We also do this *before* we perform dexopt on this package, so that 8789 // we can avoid redundant dexopts, and also to make sure we've got the 8790 // code and package path correct. 8791 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8792 } 8793 8794 if (mFactoryTest && pkg.requestedPermissions.contains( 8795 android.Manifest.permission.FACTORY_TEST)) { 8796 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8797 } 8798 8799 if (isSystemApp(pkg)) { 8800 pkgSetting.isOrphaned = true; 8801 } 8802 8803 // Take care of first install / last update times. 8804 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8805 if (currentTime != 0) { 8806 if (pkgSetting.firstInstallTime == 0) { 8807 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8808 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8809 pkgSetting.lastUpdateTime = currentTime; 8810 } 8811 } else if (pkgSetting.firstInstallTime == 0) { 8812 // We need *something*. Take time time stamp of the file. 8813 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8814 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8815 if (scanFileTime != pkgSetting.timeStamp) { 8816 // A package on the system image has changed; consider this 8817 // to be an update. 8818 pkgSetting.lastUpdateTime = scanFileTime; 8819 } 8820 } 8821 pkgSetting.setTimeStamp(scanFileTime); 8822 8823 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8824 if (nonMutatedPs != null) { 8825 synchronized (mPackages) { 8826 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8827 } 8828 } 8829 } else { 8830 // Modify state for the given package setting 8831 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8832 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8833 } 8834 return pkg; 8835 } 8836 8837 /** 8838 * Applies policy to the parsed package based upon the given policy flags. 8839 * Ensures the package is in a good state. 8840 * <p> 8841 * Implementation detail: This method must NOT have any side effect. It would 8842 * ideally be static, but, it requires locks to read system state. 8843 */ 8844 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8845 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8846 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8847 if (pkg.applicationInfo.isDirectBootAware()) { 8848 // we're direct boot aware; set for all components 8849 for (PackageParser.Service s : pkg.services) { 8850 s.info.encryptionAware = s.info.directBootAware = true; 8851 } 8852 for (PackageParser.Provider p : pkg.providers) { 8853 p.info.encryptionAware = p.info.directBootAware = true; 8854 } 8855 for (PackageParser.Activity a : pkg.activities) { 8856 a.info.encryptionAware = a.info.directBootAware = true; 8857 } 8858 for (PackageParser.Activity r : pkg.receivers) { 8859 r.info.encryptionAware = r.info.directBootAware = true; 8860 } 8861 } 8862 } else { 8863 // Only allow system apps to be flagged as core apps. 8864 pkg.coreApp = false; 8865 // clear flags not applicable to regular apps 8866 pkg.applicationInfo.privateFlags &= 8867 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8868 pkg.applicationInfo.privateFlags &= 8869 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8870 } 8871 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8872 8873 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8874 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8875 } 8876 8877 if (!isSystemApp(pkg)) { 8878 // Only system apps can use these features. 8879 pkg.mOriginalPackages = null; 8880 pkg.mRealPackage = null; 8881 pkg.mAdoptPermissions = null; 8882 } 8883 } 8884 8885 /** 8886 * Asserts the parsed package is valid according to teh given policy. If the 8887 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8888 * <p> 8889 * Implementation detail: This method must NOT have any side effects. It would 8890 * ideally be static, but, it requires locks to read system state. 8891 * 8892 * @throws PackageManagerException If the package fails any of the validation checks 8893 */ 8894 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8895 throws PackageManagerException { 8896 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8897 assertCodePolicy(pkg); 8898 } 8899 8900 if (pkg.applicationInfo.getCodePath() == null || 8901 pkg.applicationInfo.getResourcePath() == null) { 8902 // Bail out. The resource and code paths haven't been set. 8903 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8904 "Code and resource paths haven't been set correctly"); 8905 } 8906 8907 // Make sure we're not adding any bogus keyset info 8908 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8909 ksms.assertScannedPackageValid(pkg); 8910 8911 synchronized (mPackages) { 8912 // The special "android" package can only be defined once 8913 if (pkg.packageName.equals("android")) { 8914 if (mAndroidApplication != null) { 8915 Slog.w(TAG, "*************************************************"); 8916 Slog.w(TAG, "Core android package being redefined. Skipping."); 8917 Slog.w(TAG, " codePath=" + pkg.codePath); 8918 Slog.w(TAG, "*************************************************"); 8919 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8920 "Core android package being redefined. Skipping."); 8921 } 8922 } 8923 8924 // A package name must be unique; don't allow duplicates 8925 if (mPackages.containsKey(pkg.packageName) 8926 || mSharedLibraries.containsKey(pkg.packageName)) { 8927 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8928 "Application package " + pkg.packageName 8929 + " already installed. Skipping duplicate."); 8930 } 8931 8932 // Only privileged apps and updated privileged apps can add child packages. 8933 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8934 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8935 throw new PackageManagerException("Only privileged apps can add child " 8936 + "packages. Ignoring package " + pkg.packageName); 8937 } 8938 final int childCount = pkg.childPackages.size(); 8939 for (int i = 0; i < childCount; i++) { 8940 PackageParser.Package childPkg = pkg.childPackages.get(i); 8941 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8942 childPkg.packageName)) { 8943 throw new PackageManagerException("Can't override child of " 8944 + "another disabled app. Ignoring package " + pkg.packageName); 8945 } 8946 } 8947 } 8948 8949 // If we're only installing presumed-existing packages, require that the 8950 // scanned APK is both already known and at the path previously established 8951 // for it. Previously unknown packages we pick up normally, but if we have an 8952 // a priori expectation about this package's install presence, enforce it. 8953 // With a singular exception for new system packages. When an OTA contains 8954 // a new system package, we allow the codepath to change from a system location 8955 // to the user-installed location. If we don't allow this change, any newer, 8956 // user-installed version of the application will be ignored. 8957 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8958 if (mExpectingBetter.containsKey(pkg.packageName)) { 8959 logCriticalInfo(Log.WARN, 8960 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8961 } else { 8962 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8963 if (known != null) { 8964 if (DEBUG_PACKAGE_SCANNING) { 8965 Log.d(TAG, "Examining " + pkg.codePath 8966 + " and requiring known paths " + known.codePathString 8967 + " & " + known.resourcePathString); 8968 } 8969 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8970 || !pkg.applicationInfo.getResourcePath().equals( 8971 known.resourcePathString)) { 8972 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8973 "Application package " + pkg.packageName 8974 + " found at " + pkg.applicationInfo.getCodePath() 8975 + " but expected at " + known.codePathString 8976 + "; ignoring."); 8977 } 8978 } 8979 } 8980 } 8981 8982 // Verify that this new package doesn't have any content providers 8983 // that conflict with existing packages. Only do this if the 8984 // package isn't already installed, since we don't want to break 8985 // things that are installed. 8986 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8987 final int N = pkg.providers.size(); 8988 int i; 8989 for (i=0; i<N; i++) { 8990 PackageParser.Provider p = pkg.providers.get(i); 8991 if (p.info.authority != null) { 8992 String names[] = p.info.authority.split(";"); 8993 for (int j = 0; j < names.length; j++) { 8994 if (mProvidersByAuthority.containsKey(names[j])) { 8995 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8996 final String otherPackageName = 8997 ((other != null && other.getComponentName() != null) ? 8998 other.getComponentName().getPackageName() : "?"); 8999 throw new PackageManagerException( 9000 INSTALL_FAILED_CONFLICTING_PROVIDER, 9001 "Can't install because provider name " + names[j] 9002 + " (in package " + pkg.applicationInfo.packageName 9003 + ") is already used by " + otherPackageName); 9004 } 9005 } 9006 } 9007 } 9008 } 9009 } 9010 } 9011 9012 /** 9013 * Adds a scanned package to the system. When this method is finished, the package will 9014 * be available for query, resolution, etc... 9015 */ 9016 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9017 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9018 final String pkgName = pkg.packageName; 9019 if (mCustomResolverComponentName != null && 9020 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9021 setUpCustomResolverActivity(pkg); 9022 } 9023 9024 if (pkg.packageName.equals("android")) { 9025 synchronized (mPackages) { 9026 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9027 // Set up information for our fall-back user intent resolution activity. 9028 mPlatformPackage = pkg; 9029 pkg.mVersionCode = mSdkVersion; 9030 mAndroidApplication = pkg.applicationInfo; 9031 9032 if (!mResolverReplaced) { 9033 mResolveActivity.applicationInfo = mAndroidApplication; 9034 mResolveActivity.name = ResolverActivity.class.getName(); 9035 mResolveActivity.packageName = mAndroidApplication.packageName; 9036 mResolveActivity.processName = "system:ui"; 9037 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9038 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9039 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9040 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9041 mResolveActivity.exported = true; 9042 mResolveActivity.enabled = true; 9043 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9044 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9045 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9046 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9047 | ActivityInfo.CONFIG_ORIENTATION 9048 | ActivityInfo.CONFIG_KEYBOARD 9049 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9050 mResolveInfo.activityInfo = mResolveActivity; 9051 mResolveInfo.priority = 0; 9052 mResolveInfo.preferredOrder = 0; 9053 mResolveInfo.match = 0; 9054 mResolveComponentName = new ComponentName( 9055 mAndroidApplication.packageName, mResolveActivity.name); 9056 } 9057 } 9058 } 9059 } 9060 9061 ArrayList<PackageParser.Package> clientLibPkgs = null; 9062 // writer 9063 synchronized (mPackages) { 9064 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9065 // Only system apps can add new shared libraries. 9066 if (pkg.libraryNames != null) { 9067 for (int i=0; i<pkg.libraryNames.size(); i++) { 9068 String name = pkg.libraryNames.get(i); 9069 boolean allowed = false; 9070 if (pkg.isUpdatedSystemApp()) { 9071 // New library entries can only be added through the 9072 // system image. This is important to get rid of a lot 9073 // of nasty edge cases: for example if we allowed a non- 9074 // system update of the app to add a library, then uninstalling 9075 // the update would make the library go away, and assumptions 9076 // we made such as through app install filtering would now 9077 // have allowed apps on the device which aren't compatible 9078 // with it. Better to just have the restriction here, be 9079 // conservative, and create many fewer cases that can negatively 9080 // impact the user experience. 9081 final PackageSetting sysPs = mSettings 9082 .getDisabledSystemPkgLPr(pkg.packageName); 9083 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9084 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 9085 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9086 allowed = true; 9087 break; 9088 } 9089 } 9090 } 9091 } else { 9092 allowed = true; 9093 } 9094 if (allowed) { 9095 if (!mSharedLibraries.containsKey(name)) { 9096 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 9097 } else if (!name.equals(pkg.packageName)) { 9098 Slog.w(TAG, "Package " + pkg.packageName + " library " 9099 + name + " already exists; skipping"); 9100 } 9101 } else { 9102 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9103 + name + " that is not declared on system image; skipping"); 9104 } 9105 } 9106 if ((scanFlags & SCAN_BOOTING) == 0) { 9107 // If we are not booting, we need to update any applications 9108 // that are clients of our shared library. If we are booting, 9109 // this will all be done once the scan is complete. 9110 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9111 } 9112 } 9113 } 9114 } 9115 9116 if ((scanFlags & SCAN_BOOTING) != 0) { 9117 // No apps can run during boot scan, so they don't need to be frozen 9118 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9119 // Caller asked to not kill app, so it's probably not frozen 9120 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9121 // Caller asked us to ignore frozen check for some reason; they 9122 // probably didn't know the package name 9123 } else { 9124 // We're doing major surgery on this package, so it better be frozen 9125 // right now to keep it from launching 9126 checkPackageFrozen(pkgName); 9127 } 9128 9129 // Also need to kill any apps that are dependent on the library. 9130 if (clientLibPkgs != null) { 9131 for (int i=0; i<clientLibPkgs.size(); i++) { 9132 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9133 killApplication(clientPkg.applicationInfo.packageName, 9134 clientPkg.applicationInfo.uid, "update lib"); 9135 } 9136 } 9137 9138 // writer 9139 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9140 9141 boolean createIdmapFailed = false; 9142 synchronized (mPackages) { 9143 // We don't expect installation to fail beyond this point 9144 9145 if (pkgSetting.pkg != null) { 9146 // Note that |user| might be null during the initial boot scan. If a codePath 9147 // for an app has changed during a boot scan, it's due to an app update that's 9148 // part of the system partition and marker changes must be applied to all users. 9149 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9150 final int[] userIds = resolveUserIds(userId); 9151 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9152 } 9153 9154 // Add the new setting to mSettings 9155 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9156 // Add the new setting to mPackages 9157 mPackages.put(pkg.applicationInfo.packageName, pkg); 9158 // Make sure we don't accidentally delete its data. 9159 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9160 while (iter.hasNext()) { 9161 PackageCleanItem item = iter.next(); 9162 if (pkgName.equals(item.packageName)) { 9163 iter.remove(); 9164 } 9165 } 9166 9167 // Add the package's KeySets to the global KeySetManagerService 9168 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9169 ksms.addScannedPackageLPw(pkg); 9170 9171 int N = pkg.providers.size(); 9172 StringBuilder r = null; 9173 int i; 9174 for (i=0; i<N; i++) { 9175 PackageParser.Provider p = pkg.providers.get(i); 9176 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9177 p.info.processName); 9178 mProviders.addProvider(p); 9179 p.syncable = p.info.isSyncable; 9180 if (p.info.authority != null) { 9181 String names[] = p.info.authority.split(";"); 9182 p.info.authority = null; 9183 for (int j = 0; j < names.length; j++) { 9184 if (j == 1 && p.syncable) { 9185 // We only want the first authority for a provider to possibly be 9186 // syncable, so if we already added this provider using a different 9187 // authority clear the syncable flag. We copy the provider before 9188 // changing it because the mProviders object contains a reference 9189 // to a provider that we don't want to change. 9190 // Only do this for the second authority since the resulting provider 9191 // object can be the same for all future authorities for this provider. 9192 p = new PackageParser.Provider(p); 9193 p.syncable = false; 9194 } 9195 if (!mProvidersByAuthority.containsKey(names[j])) { 9196 mProvidersByAuthority.put(names[j], p); 9197 if (p.info.authority == null) { 9198 p.info.authority = names[j]; 9199 } else { 9200 p.info.authority = p.info.authority + ";" + names[j]; 9201 } 9202 if (DEBUG_PACKAGE_SCANNING) { 9203 if (chatty) 9204 Log.d(TAG, "Registered content provider: " + names[j] 9205 + ", className = " + p.info.name + ", isSyncable = " 9206 + p.info.isSyncable); 9207 } 9208 } else { 9209 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9210 Slog.w(TAG, "Skipping provider name " + names[j] + 9211 " (in package " + pkg.applicationInfo.packageName + 9212 "): name already used by " 9213 + ((other != null && other.getComponentName() != null) 9214 ? other.getComponentName().getPackageName() : "?")); 9215 } 9216 } 9217 } 9218 if (chatty) { 9219 if (r == null) { 9220 r = new StringBuilder(256); 9221 } else { 9222 r.append(' '); 9223 } 9224 r.append(p.info.name); 9225 } 9226 } 9227 if (r != null) { 9228 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9229 } 9230 9231 N = pkg.services.size(); 9232 r = null; 9233 for (i=0; i<N; i++) { 9234 PackageParser.Service s = pkg.services.get(i); 9235 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9236 s.info.processName); 9237 mServices.addService(s); 9238 if (chatty) { 9239 if (r == null) { 9240 r = new StringBuilder(256); 9241 } else { 9242 r.append(' '); 9243 } 9244 r.append(s.info.name); 9245 } 9246 } 9247 if (r != null) { 9248 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9249 } 9250 9251 N = pkg.receivers.size(); 9252 r = null; 9253 for (i=0; i<N; i++) { 9254 PackageParser.Activity a = pkg.receivers.get(i); 9255 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9256 a.info.processName); 9257 mReceivers.addActivity(a, "receiver"); 9258 if (chatty) { 9259 if (r == null) { 9260 r = new StringBuilder(256); 9261 } else { 9262 r.append(' '); 9263 } 9264 r.append(a.info.name); 9265 } 9266 } 9267 if (r != null) { 9268 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9269 } 9270 9271 N = pkg.activities.size(); 9272 r = null; 9273 for (i=0; i<N; i++) { 9274 PackageParser.Activity a = pkg.activities.get(i); 9275 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9276 a.info.processName); 9277 mActivities.addActivity(a, "activity"); 9278 if (chatty) { 9279 if (r == null) { 9280 r = new StringBuilder(256); 9281 } else { 9282 r.append(' '); 9283 } 9284 r.append(a.info.name); 9285 } 9286 } 9287 if (r != null) { 9288 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9289 } 9290 9291 N = pkg.permissionGroups.size(); 9292 r = null; 9293 for (i=0; i<N; i++) { 9294 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9295 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9296 final String curPackageName = cur == null ? null : cur.info.packageName; 9297 // Dont allow ephemeral apps to define new permission groups. 9298 if (pkg.applicationInfo.isEphemeralApp()) { 9299 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9300 + pg.info.packageName 9301 + " ignored: ephemeral apps cannot define new permission groups."); 9302 continue; 9303 } 9304 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9305 if (cur == null || isPackageUpdate) { 9306 mPermissionGroups.put(pg.info.name, pg); 9307 if (chatty) { 9308 if (r == null) { 9309 r = new StringBuilder(256); 9310 } else { 9311 r.append(' '); 9312 } 9313 if (isPackageUpdate) { 9314 r.append("UPD:"); 9315 } 9316 r.append(pg.info.name); 9317 } 9318 } else { 9319 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9320 + pg.info.packageName + " ignored: original from " 9321 + cur.info.packageName); 9322 if (chatty) { 9323 if (r == null) { 9324 r = new StringBuilder(256); 9325 } else { 9326 r.append(' '); 9327 } 9328 r.append("DUP:"); 9329 r.append(pg.info.name); 9330 } 9331 } 9332 } 9333 if (r != null) { 9334 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9335 } 9336 9337 N = pkg.permissions.size(); 9338 r = null; 9339 for (i=0; i<N; i++) { 9340 PackageParser.Permission p = pkg.permissions.get(i); 9341 9342 // Dont allow ephemeral apps to define new permissions. 9343 if (pkg.applicationInfo.isEphemeralApp()) { 9344 Slog.w(TAG, "Permission " + p.info.name + " from package " 9345 + p.info.packageName 9346 + " ignored: ephemeral apps cannot define new permissions."); 9347 continue; 9348 } 9349 9350 // Assume by default that we did not install this permission into the system. 9351 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9352 9353 // Now that permission groups have a special meaning, we ignore permission 9354 // groups for legacy apps to prevent unexpected behavior. In particular, 9355 // permissions for one app being granted to someone just becase they happen 9356 // to be in a group defined by another app (before this had no implications). 9357 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9358 p.group = mPermissionGroups.get(p.info.group); 9359 // Warn for a permission in an unknown group. 9360 if (p.info.group != null && p.group == null) { 9361 Slog.w(TAG, "Permission " + p.info.name + " from package " 9362 + p.info.packageName + " in an unknown group " + p.info.group); 9363 } 9364 } 9365 9366 ArrayMap<String, BasePermission> permissionMap = 9367 p.tree ? mSettings.mPermissionTrees 9368 : mSettings.mPermissions; 9369 BasePermission bp = permissionMap.get(p.info.name); 9370 9371 // Allow system apps to redefine non-system permissions 9372 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9373 final boolean currentOwnerIsSystem = (bp.perm != null 9374 && isSystemApp(bp.perm.owner)); 9375 if (isSystemApp(p.owner)) { 9376 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9377 // It's a built-in permission and no owner, take ownership now 9378 bp.packageSetting = pkgSetting; 9379 bp.perm = p; 9380 bp.uid = pkg.applicationInfo.uid; 9381 bp.sourcePackage = p.info.packageName; 9382 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9383 } else if (!currentOwnerIsSystem) { 9384 String msg = "New decl " + p.owner + " of permission " 9385 + p.info.name + " is system; overriding " + bp.sourcePackage; 9386 reportSettingsProblem(Log.WARN, msg); 9387 bp = null; 9388 } 9389 } 9390 } 9391 9392 if (bp == null) { 9393 bp = new BasePermission(p.info.name, p.info.packageName, 9394 BasePermission.TYPE_NORMAL); 9395 permissionMap.put(p.info.name, bp); 9396 } 9397 9398 if (bp.perm == null) { 9399 if (bp.sourcePackage == null 9400 || bp.sourcePackage.equals(p.info.packageName)) { 9401 BasePermission tree = findPermissionTreeLP(p.info.name); 9402 if (tree == null 9403 || tree.sourcePackage.equals(p.info.packageName)) { 9404 bp.packageSetting = pkgSetting; 9405 bp.perm = p; 9406 bp.uid = pkg.applicationInfo.uid; 9407 bp.sourcePackage = p.info.packageName; 9408 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9409 if (chatty) { 9410 if (r == null) { 9411 r = new StringBuilder(256); 9412 } else { 9413 r.append(' '); 9414 } 9415 r.append(p.info.name); 9416 } 9417 } else { 9418 Slog.w(TAG, "Permission " + p.info.name + " from package " 9419 + p.info.packageName + " ignored: base tree " 9420 + tree.name + " is from package " 9421 + tree.sourcePackage); 9422 } 9423 } else { 9424 Slog.w(TAG, "Permission " + p.info.name + " from package " 9425 + p.info.packageName + " ignored: original from " 9426 + bp.sourcePackage); 9427 } 9428 } else if (chatty) { 9429 if (r == null) { 9430 r = new StringBuilder(256); 9431 } else { 9432 r.append(' '); 9433 } 9434 r.append("DUP:"); 9435 r.append(p.info.name); 9436 } 9437 if (bp.perm == p) { 9438 bp.protectionLevel = p.info.protectionLevel; 9439 } 9440 } 9441 9442 if (r != null) { 9443 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9444 } 9445 9446 N = pkg.instrumentation.size(); 9447 r = null; 9448 for (i=0; i<N; i++) { 9449 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9450 a.info.packageName = pkg.applicationInfo.packageName; 9451 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9452 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9453 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9454 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9455 a.info.dataDir = pkg.applicationInfo.dataDir; 9456 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9457 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9458 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9459 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9460 mInstrumentation.put(a.getComponentName(), a); 9461 if (chatty) { 9462 if (r == null) { 9463 r = new StringBuilder(256); 9464 } else { 9465 r.append(' '); 9466 } 9467 r.append(a.info.name); 9468 } 9469 } 9470 if (r != null) { 9471 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9472 } 9473 9474 if (pkg.protectedBroadcasts != null) { 9475 N = pkg.protectedBroadcasts.size(); 9476 for (i=0; i<N; i++) { 9477 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9478 } 9479 } 9480 9481 // Create idmap files for pairs of (packages, overlay packages). 9482 // Note: "android", ie framework-res.apk, is handled by native layers. 9483 if (pkg.mOverlayTarget != null) { 9484 // This is an overlay package. 9485 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9486 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9487 mOverlays.put(pkg.mOverlayTarget, 9488 new ArrayMap<String, PackageParser.Package>()); 9489 } 9490 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9491 map.put(pkg.packageName, pkg); 9492 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9493 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9494 createIdmapFailed = true; 9495 } 9496 } 9497 } else if (mOverlays.containsKey(pkg.packageName) && 9498 !pkg.packageName.equals("android")) { 9499 // This is a regular package, with one or more known overlay packages. 9500 createIdmapsForPackageLI(pkg); 9501 } 9502 } 9503 9504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9505 9506 if (createIdmapFailed) { 9507 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9508 "scanPackageLI failed to createIdmap"); 9509 } 9510 } 9511 9512 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9513 PackageParser.Package update, int[] userIds) { 9514 if (existing.applicationInfo == null || update.applicationInfo == null) { 9515 // This isn't due to an app installation. 9516 return; 9517 } 9518 9519 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9520 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9521 9522 // The codePath hasn't changed, so there's nothing for us to do. 9523 if (Objects.equals(oldCodePath, newCodePath)) { 9524 return; 9525 } 9526 9527 File canonicalNewCodePath; 9528 try { 9529 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9530 } catch (IOException e) { 9531 Slog.w(TAG, "Failed to get canonical path.", e); 9532 return; 9533 } 9534 9535 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9536 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9537 // that the last component of the path (i.e, the name) doesn't need canonicalization 9538 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9539 // but may change in the future. Hopefully this function won't exist at that point. 9540 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9541 oldCodePath.getName()); 9542 9543 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9544 // with "@". 9545 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9546 if (!oldMarkerPrefix.endsWith("@")) { 9547 oldMarkerPrefix += "@"; 9548 } 9549 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9550 if (!newMarkerPrefix.endsWith("@")) { 9551 newMarkerPrefix += "@"; 9552 } 9553 9554 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9555 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9556 for (String updatedPath : updatedPaths) { 9557 String updatedPathName = new File(updatedPath).getName(); 9558 markerSuffixes.add(updatedPathName.replace('/', '@')); 9559 } 9560 9561 for (int userId : userIds) { 9562 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9563 9564 for (String markerSuffix : markerSuffixes) { 9565 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9566 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9567 if (oldForeignUseMark.exists()) { 9568 try { 9569 Os.rename(oldForeignUseMark.getAbsolutePath(), 9570 newForeignUseMark.getAbsolutePath()); 9571 } catch (ErrnoException e) { 9572 Slog.w(TAG, "Failed to rename foreign use marker", e); 9573 oldForeignUseMark.delete(); 9574 } 9575 } 9576 } 9577 } 9578 } 9579 9580 /** 9581 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9582 * is derived purely on the basis of the contents of {@code scanFile} and 9583 * {@code cpuAbiOverride}. 9584 * 9585 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9586 */ 9587 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9588 String cpuAbiOverride, boolean extractLibs, 9589 File appLib32InstallDir) 9590 throws PackageManagerException { 9591 // Give ourselves some initial paths; we'll come back for another 9592 // pass once we've determined ABI below. 9593 setNativeLibraryPaths(pkg, appLib32InstallDir); 9594 9595 // We would never need to extract libs for forward-locked and external packages, 9596 // since the container service will do it for us. We shouldn't attempt to 9597 // extract libs from system app when it was not updated. 9598 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9599 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9600 extractLibs = false; 9601 } 9602 9603 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9604 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9605 9606 NativeLibraryHelper.Handle handle = null; 9607 try { 9608 handle = NativeLibraryHelper.Handle.create(pkg); 9609 // TODO(multiArch): This can be null for apps that didn't go through the 9610 // usual installation process. We can calculate it again, like we 9611 // do during install time. 9612 // 9613 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9614 // unnecessary. 9615 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9616 9617 // Null out the abis so that they can be recalculated. 9618 pkg.applicationInfo.primaryCpuAbi = null; 9619 pkg.applicationInfo.secondaryCpuAbi = null; 9620 if (isMultiArch(pkg.applicationInfo)) { 9621 // Warn if we've set an abiOverride for multi-lib packages.. 9622 // By definition, we need to copy both 32 and 64 bit libraries for 9623 // such packages. 9624 if (pkg.cpuAbiOverride != null 9625 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9626 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9627 } 9628 9629 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9630 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9631 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9632 if (extractLibs) { 9633 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9634 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9635 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9636 useIsaSpecificSubdirs); 9637 } else { 9638 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9639 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9640 } 9641 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9642 } 9643 9644 maybeThrowExceptionForMultiArchCopy( 9645 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9646 9647 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9648 if (extractLibs) { 9649 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9650 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9651 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9652 useIsaSpecificSubdirs); 9653 } else { 9654 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9655 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9656 } 9657 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9658 } 9659 9660 maybeThrowExceptionForMultiArchCopy( 9661 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9662 9663 if (abi64 >= 0) { 9664 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9665 } 9666 9667 if (abi32 >= 0) { 9668 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9669 if (abi64 >= 0) { 9670 if (pkg.use32bitAbi) { 9671 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9672 pkg.applicationInfo.primaryCpuAbi = abi; 9673 } else { 9674 pkg.applicationInfo.secondaryCpuAbi = abi; 9675 } 9676 } else { 9677 pkg.applicationInfo.primaryCpuAbi = abi; 9678 } 9679 } 9680 9681 } else { 9682 String[] abiList = (cpuAbiOverride != null) ? 9683 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9684 9685 // Enable gross and lame hacks for apps that are built with old 9686 // SDK tools. We must scan their APKs for renderscript bitcode and 9687 // not launch them if it's present. Don't bother checking on devices 9688 // that don't have 64 bit support. 9689 boolean needsRenderScriptOverride = false; 9690 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9691 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9692 abiList = Build.SUPPORTED_32_BIT_ABIS; 9693 needsRenderScriptOverride = true; 9694 } 9695 9696 final int copyRet; 9697 if (extractLibs) { 9698 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9699 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9700 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9701 } else { 9702 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9703 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9704 } 9705 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9706 9707 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9708 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9709 "Error unpackaging native libs for app, errorCode=" + copyRet); 9710 } 9711 9712 if (copyRet >= 0) { 9713 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9714 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9715 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9716 } else if (needsRenderScriptOverride) { 9717 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9718 } 9719 } 9720 } catch (IOException ioe) { 9721 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9722 } finally { 9723 IoUtils.closeQuietly(handle); 9724 } 9725 9726 // Now that we've calculated the ABIs and determined if it's an internal app, 9727 // we will go ahead and populate the nativeLibraryPath. 9728 setNativeLibraryPaths(pkg, appLib32InstallDir); 9729 } 9730 9731 /** 9732 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9733 * i.e, so that all packages can be run inside a single process if required. 9734 * 9735 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9736 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9737 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9738 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9739 * updating a package that belongs to a shared user. 9740 * 9741 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9742 * adds unnecessary complexity. 9743 */ 9744 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9745 PackageParser.Package scannedPackage) { 9746 String requiredInstructionSet = null; 9747 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9748 requiredInstructionSet = VMRuntime.getInstructionSet( 9749 scannedPackage.applicationInfo.primaryCpuAbi); 9750 } 9751 9752 PackageSetting requirer = null; 9753 for (PackageSetting ps : packagesForUser) { 9754 // If packagesForUser contains scannedPackage, we skip it. This will happen 9755 // when scannedPackage is an update of an existing package. Without this check, 9756 // we will never be able to change the ABI of any package belonging to a shared 9757 // user, even if it's compatible with other packages. 9758 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9759 if (ps.primaryCpuAbiString == null) { 9760 continue; 9761 } 9762 9763 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9764 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9765 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9766 // this but there's not much we can do. 9767 String errorMessage = "Instruction set mismatch, " 9768 + ((requirer == null) ? "[caller]" : requirer) 9769 + " requires " + requiredInstructionSet + " whereas " + ps 9770 + " requires " + instructionSet; 9771 Slog.w(TAG, errorMessage); 9772 } 9773 9774 if (requiredInstructionSet == null) { 9775 requiredInstructionSet = instructionSet; 9776 requirer = ps; 9777 } 9778 } 9779 } 9780 9781 if (requiredInstructionSet != null) { 9782 String adjustedAbi; 9783 if (requirer != null) { 9784 // requirer != null implies that either scannedPackage was null or that scannedPackage 9785 // did not require an ABI, in which case we have to adjust scannedPackage to match 9786 // the ABI of the set (which is the same as requirer's ABI) 9787 adjustedAbi = requirer.primaryCpuAbiString; 9788 if (scannedPackage != null) { 9789 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9790 } 9791 } else { 9792 // requirer == null implies that we're updating all ABIs in the set to 9793 // match scannedPackage. 9794 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9795 } 9796 9797 for (PackageSetting ps : packagesForUser) { 9798 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9799 if (ps.primaryCpuAbiString != null) { 9800 continue; 9801 } 9802 9803 ps.primaryCpuAbiString = adjustedAbi; 9804 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9805 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9806 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9807 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9808 + " (requirer=" 9809 + (requirer == null ? "null" : requirer.pkg.packageName) 9810 + ", scannedPackage=" 9811 + (scannedPackage != null ? scannedPackage.packageName : "null") 9812 + ")"); 9813 try { 9814 mInstaller.rmdex(ps.codePathString, 9815 getDexCodeInstructionSet(getPreferredInstructionSet())); 9816 } catch (InstallerException ignored) { 9817 } 9818 } 9819 } 9820 } 9821 } 9822 } 9823 9824 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9825 synchronized (mPackages) { 9826 mResolverReplaced = true; 9827 // Set up information for custom user intent resolution activity. 9828 mResolveActivity.applicationInfo = pkg.applicationInfo; 9829 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9830 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9831 mResolveActivity.processName = pkg.applicationInfo.packageName; 9832 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9833 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9834 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9835 mResolveActivity.theme = 0; 9836 mResolveActivity.exported = true; 9837 mResolveActivity.enabled = true; 9838 mResolveInfo.activityInfo = mResolveActivity; 9839 mResolveInfo.priority = 0; 9840 mResolveInfo.preferredOrder = 0; 9841 mResolveInfo.match = 0; 9842 mResolveComponentName = mCustomResolverComponentName; 9843 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9844 mResolveComponentName); 9845 } 9846 } 9847 9848 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9849 if (installerComponent == null) { 9850 if (DEBUG_EPHEMERAL) { 9851 Slog.d(TAG, "Clear ephemeral installer activity"); 9852 } 9853 mEphemeralInstallerActivity.applicationInfo = null; 9854 return; 9855 } 9856 9857 if (DEBUG_EPHEMERAL) { 9858 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9859 } 9860 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9861 // Set up information for ephemeral installer activity 9862 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9863 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9864 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9865 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9866 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9867 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9868 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9869 mEphemeralInstallerActivity.theme = 0; 9870 mEphemeralInstallerActivity.exported = true; 9871 mEphemeralInstallerActivity.enabled = true; 9872 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9873 mEphemeralInstallerInfo.priority = 0; 9874 mEphemeralInstallerInfo.preferredOrder = 1; 9875 mEphemeralInstallerInfo.isDefault = true; 9876 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9877 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9878 } 9879 9880 private static String calculateBundledApkRoot(final String codePathString) { 9881 final File codePath = new File(codePathString); 9882 final File codeRoot; 9883 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9884 codeRoot = Environment.getRootDirectory(); 9885 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9886 codeRoot = Environment.getOemDirectory(); 9887 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9888 codeRoot = Environment.getVendorDirectory(); 9889 } else { 9890 // Unrecognized code path; take its top real segment as the apk root: 9891 // e.g. /something/app/blah.apk => /something 9892 try { 9893 File f = codePath.getCanonicalFile(); 9894 File parent = f.getParentFile(); // non-null because codePath is a file 9895 File tmp; 9896 while ((tmp = parent.getParentFile()) != null) { 9897 f = parent; 9898 parent = tmp; 9899 } 9900 codeRoot = f; 9901 Slog.w(TAG, "Unrecognized code path " 9902 + codePath + " - using " + codeRoot); 9903 } catch (IOException e) { 9904 // Can't canonicalize the code path -- shenanigans? 9905 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9906 return Environment.getRootDirectory().getPath(); 9907 } 9908 } 9909 return codeRoot.getPath(); 9910 } 9911 9912 /** 9913 * Derive and set the location of native libraries for the given package, 9914 * which varies depending on where and how the package was installed. 9915 */ 9916 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9917 final ApplicationInfo info = pkg.applicationInfo; 9918 final String codePath = pkg.codePath; 9919 final File codeFile = new File(codePath); 9920 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9921 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9922 9923 info.nativeLibraryRootDir = null; 9924 info.nativeLibraryRootRequiresIsa = false; 9925 info.nativeLibraryDir = null; 9926 info.secondaryNativeLibraryDir = null; 9927 9928 if (isApkFile(codeFile)) { 9929 // Monolithic install 9930 if (bundledApp) { 9931 // If "/system/lib64/apkname" exists, assume that is the per-package 9932 // native library directory to use; otherwise use "/system/lib/apkname". 9933 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9934 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9935 getPrimaryInstructionSet(info)); 9936 9937 // This is a bundled system app so choose the path based on the ABI. 9938 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9939 // is just the default path. 9940 final String apkName = deriveCodePathName(codePath); 9941 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9942 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9943 apkName).getAbsolutePath(); 9944 9945 if (info.secondaryCpuAbi != null) { 9946 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9947 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9948 secondaryLibDir, apkName).getAbsolutePath(); 9949 } 9950 } else if (asecApp) { 9951 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9952 .getAbsolutePath(); 9953 } else { 9954 final String apkName = deriveCodePathName(codePath); 9955 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9956 .getAbsolutePath(); 9957 } 9958 9959 info.nativeLibraryRootRequiresIsa = false; 9960 info.nativeLibraryDir = info.nativeLibraryRootDir; 9961 } else { 9962 // Cluster install 9963 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9964 info.nativeLibraryRootRequiresIsa = true; 9965 9966 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9967 getPrimaryInstructionSet(info)).getAbsolutePath(); 9968 9969 if (info.secondaryCpuAbi != null) { 9970 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9971 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9972 } 9973 } 9974 } 9975 9976 /** 9977 * Calculate the abis and roots for a bundled app. These can uniquely 9978 * be determined from the contents of the system partition, i.e whether 9979 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9980 * of this information, and instead assume that the system was built 9981 * sensibly. 9982 */ 9983 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9984 PackageSetting pkgSetting) { 9985 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9986 9987 // If "/system/lib64/apkname" exists, assume that is the per-package 9988 // native library directory to use; otherwise use "/system/lib/apkname". 9989 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9990 setBundledAppAbi(pkg, apkRoot, apkName); 9991 // pkgSetting might be null during rescan following uninstall of updates 9992 // to a bundled app, so accommodate that possibility. The settings in 9993 // that case will be established later from the parsed package. 9994 // 9995 // If the settings aren't null, sync them up with what we've just derived. 9996 // note that apkRoot isn't stored in the package settings. 9997 if (pkgSetting != null) { 9998 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9999 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10000 } 10001 } 10002 10003 /** 10004 * Deduces the ABI of a bundled app and sets the relevant fields on the 10005 * parsed pkg object. 10006 * 10007 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10008 * under which system libraries are installed. 10009 * @param apkName the name of the installed package. 10010 */ 10011 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10012 final File codeFile = new File(pkg.codePath); 10013 10014 final boolean has64BitLibs; 10015 final boolean has32BitLibs; 10016 if (isApkFile(codeFile)) { 10017 // Monolithic install 10018 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10019 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10020 } else { 10021 // Cluster install 10022 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10023 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10024 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10025 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10026 has64BitLibs = (new File(rootDir, isa)).exists(); 10027 } else { 10028 has64BitLibs = false; 10029 } 10030 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10031 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10032 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10033 has32BitLibs = (new File(rootDir, isa)).exists(); 10034 } else { 10035 has32BitLibs = false; 10036 } 10037 } 10038 10039 if (has64BitLibs && !has32BitLibs) { 10040 // The package has 64 bit libs, but not 32 bit libs. Its primary 10041 // ABI should be 64 bit. We can safely assume here that the bundled 10042 // native libraries correspond to the most preferred ABI in the list. 10043 10044 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10045 pkg.applicationInfo.secondaryCpuAbi = null; 10046 } else if (has32BitLibs && !has64BitLibs) { 10047 // The package has 32 bit libs but not 64 bit libs. Its primary 10048 // ABI should be 32 bit. 10049 10050 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10051 pkg.applicationInfo.secondaryCpuAbi = null; 10052 } else if (has32BitLibs && has64BitLibs) { 10053 // The application has both 64 and 32 bit bundled libraries. We check 10054 // here that the app declares multiArch support, and warn if it doesn't. 10055 // 10056 // We will be lenient here and record both ABIs. The primary will be the 10057 // ABI that's higher on the list, i.e, a device that's configured to prefer 10058 // 64 bit apps will see a 64 bit primary ABI, 10059 10060 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10061 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10062 } 10063 10064 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10065 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10066 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10067 } else { 10068 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10069 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10070 } 10071 } else { 10072 pkg.applicationInfo.primaryCpuAbi = null; 10073 pkg.applicationInfo.secondaryCpuAbi = null; 10074 } 10075 } 10076 10077 private void killApplication(String pkgName, int appId, String reason) { 10078 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10079 } 10080 10081 private void killApplication(String pkgName, int appId, int userId, String reason) { 10082 // Request the ActivityManager to kill the process(only for existing packages) 10083 // so that we do not end up in a confused state while the user is still using the older 10084 // version of the application while the new one gets installed. 10085 final long token = Binder.clearCallingIdentity(); 10086 try { 10087 IActivityManager am = ActivityManager.getService(); 10088 if (am != null) { 10089 try { 10090 am.killApplication(pkgName, appId, userId, reason); 10091 } catch (RemoteException e) { 10092 } 10093 } 10094 } finally { 10095 Binder.restoreCallingIdentity(token); 10096 } 10097 } 10098 10099 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10100 // Remove the parent package setting 10101 PackageSetting ps = (PackageSetting) pkg.mExtras; 10102 if (ps != null) { 10103 removePackageLI(ps, chatty); 10104 } 10105 // Remove the child package setting 10106 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10107 for (int i = 0; i < childCount; i++) { 10108 PackageParser.Package childPkg = pkg.childPackages.get(i); 10109 ps = (PackageSetting) childPkg.mExtras; 10110 if (ps != null) { 10111 removePackageLI(ps, chatty); 10112 } 10113 } 10114 } 10115 10116 void removePackageLI(PackageSetting ps, boolean chatty) { 10117 if (DEBUG_INSTALL) { 10118 if (chatty) 10119 Log.d(TAG, "Removing package " + ps.name); 10120 } 10121 10122 // writer 10123 synchronized (mPackages) { 10124 mPackages.remove(ps.name); 10125 final PackageParser.Package pkg = ps.pkg; 10126 if (pkg != null) { 10127 cleanPackageDataStructuresLILPw(pkg, chatty); 10128 } 10129 } 10130 } 10131 10132 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10133 if (DEBUG_INSTALL) { 10134 if (chatty) 10135 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10136 } 10137 10138 // writer 10139 synchronized (mPackages) { 10140 // Remove the parent package 10141 mPackages.remove(pkg.applicationInfo.packageName); 10142 cleanPackageDataStructuresLILPw(pkg, chatty); 10143 10144 // Remove the child packages 10145 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10146 for (int i = 0; i < childCount; i++) { 10147 PackageParser.Package childPkg = pkg.childPackages.get(i); 10148 mPackages.remove(childPkg.applicationInfo.packageName); 10149 cleanPackageDataStructuresLILPw(childPkg, chatty); 10150 } 10151 } 10152 } 10153 10154 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10155 int N = pkg.providers.size(); 10156 StringBuilder r = null; 10157 int i; 10158 for (i=0; i<N; i++) { 10159 PackageParser.Provider p = pkg.providers.get(i); 10160 mProviders.removeProvider(p); 10161 if (p.info.authority == null) { 10162 10163 /* There was another ContentProvider with this authority when 10164 * this app was installed so this authority is null, 10165 * Ignore it as we don't have to unregister the provider. 10166 */ 10167 continue; 10168 } 10169 String names[] = p.info.authority.split(";"); 10170 for (int j = 0; j < names.length; j++) { 10171 if (mProvidersByAuthority.get(names[j]) == p) { 10172 mProvidersByAuthority.remove(names[j]); 10173 if (DEBUG_REMOVE) { 10174 if (chatty) 10175 Log.d(TAG, "Unregistered content provider: " + names[j] 10176 + ", className = " + p.info.name + ", isSyncable = " 10177 + p.info.isSyncable); 10178 } 10179 } 10180 } 10181 if (DEBUG_REMOVE && chatty) { 10182 if (r == null) { 10183 r = new StringBuilder(256); 10184 } else { 10185 r.append(' '); 10186 } 10187 r.append(p.info.name); 10188 } 10189 } 10190 if (r != null) { 10191 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10192 } 10193 10194 N = pkg.services.size(); 10195 r = null; 10196 for (i=0; i<N; i++) { 10197 PackageParser.Service s = pkg.services.get(i); 10198 mServices.removeService(s); 10199 if (chatty) { 10200 if (r == null) { 10201 r = new StringBuilder(256); 10202 } else { 10203 r.append(' '); 10204 } 10205 r.append(s.info.name); 10206 } 10207 } 10208 if (r != null) { 10209 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10210 } 10211 10212 N = pkg.receivers.size(); 10213 r = null; 10214 for (i=0; i<N; i++) { 10215 PackageParser.Activity a = pkg.receivers.get(i); 10216 mReceivers.removeActivity(a, "receiver"); 10217 if (DEBUG_REMOVE && chatty) { 10218 if (r == null) { 10219 r = new StringBuilder(256); 10220 } else { 10221 r.append(' '); 10222 } 10223 r.append(a.info.name); 10224 } 10225 } 10226 if (r != null) { 10227 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10228 } 10229 10230 N = pkg.activities.size(); 10231 r = null; 10232 for (i=0; i<N; i++) { 10233 PackageParser.Activity a = pkg.activities.get(i); 10234 mActivities.removeActivity(a, "activity"); 10235 if (DEBUG_REMOVE && chatty) { 10236 if (r == null) { 10237 r = new StringBuilder(256); 10238 } else { 10239 r.append(' '); 10240 } 10241 r.append(a.info.name); 10242 } 10243 } 10244 if (r != null) { 10245 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10246 } 10247 10248 N = pkg.permissions.size(); 10249 r = null; 10250 for (i=0; i<N; i++) { 10251 PackageParser.Permission p = pkg.permissions.get(i); 10252 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10253 if (bp == null) { 10254 bp = mSettings.mPermissionTrees.get(p.info.name); 10255 } 10256 if (bp != null && bp.perm == p) { 10257 bp.perm = null; 10258 if (DEBUG_REMOVE && chatty) { 10259 if (r == null) { 10260 r = new StringBuilder(256); 10261 } else { 10262 r.append(' '); 10263 } 10264 r.append(p.info.name); 10265 } 10266 } 10267 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10268 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10269 if (appOpPkgs != null) { 10270 appOpPkgs.remove(pkg.packageName); 10271 } 10272 } 10273 } 10274 if (r != null) { 10275 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10276 } 10277 10278 N = pkg.requestedPermissions.size(); 10279 r = null; 10280 for (i=0; i<N; i++) { 10281 String perm = pkg.requestedPermissions.get(i); 10282 BasePermission bp = mSettings.mPermissions.get(perm); 10283 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10284 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10285 if (appOpPkgs != null) { 10286 appOpPkgs.remove(pkg.packageName); 10287 if (appOpPkgs.isEmpty()) { 10288 mAppOpPermissionPackages.remove(perm); 10289 } 10290 } 10291 } 10292 } 10293 if (r != null) { 10294 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10295 } 10296 10297 N = pkg.instrumentation.size(); 10298 r = null; 10299 for (i=0; i<N; i++) { 10300 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10301 mInstrumentation.remove(a.getComponentName()); 10302 if (DEBUG_REMOVE && chatty) { 10303 if (r == null) { 10304 r = new StringBuilder(256); 10305 } else { 10306 r.append(' '); 10307 } 10308 r.append(a.info.name); 10309 } 10310 } 10311 if (r != null) { 10312 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10313 } 10314 10315 r = null; 10316 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10317 // Only system apps can hold shared libraries. 10318 if (pkg.libraryNames != null) { 10319 for (i=0; i<pkg.libraryNames.size(); i++) { 10320 String name = pkg.libraryNames.get(i); 10321 SharedLibraryEntry cur = mSharedLibraries.get(name); 10322 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10323 mSharedLibraries.remove(name); 10324 if (DEBUG_REMOVE && chatty) { 10325 if (r == null) { 10326 r = new StringBuilder(256); 10327 } else { 10328 r.append(' '); 10329 } 10330 r.append(name); 10331 } 10332 } 10333 } 10334 } 10335 } 10336 if (r != null) { 10337 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10338 } 10339 } 10340 10341 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10342 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10343 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10344 return true; 10345 } 10346 } 10347 return false; 10348 } 10349 10350 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10351 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10352 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10353 10354 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10355 // Update the parent permissions 10356 updatePermissionsLPw(pkg.packageName, pkg, flags); 10357 // Update the child permissions 10358 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10359 for (int i = 0; i < childCount; i++) { 10360 PackageParser.Package childPkg = pkg.childPackages.get(i); 10361 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10362 } 10363 } 10364 10365 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10366 int flags) { 10367 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10368 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10369 } 10370 10371 private void updatePermissionsLPw(String changingPkg, 10372 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10373 // Make sure there are no dangling permission trees. 10374 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10375 while (it.hasNext()) { 10376 final BasePermission bp = it.next(); 10377 if (bp.packageSetting == null) { 10378 // We may not yet have parsed the package, so just see if 10379 // we still know about its settings. 10380 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10381 } 10382 if (bp.packageSetting == null) { 10383 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10384 + " from package " + bp.sourcePackage); 10385 it.remove(); 10386 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10387 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10388 Slog.i(TAG, "Removing old permission tree: " + bp.name 10389 + " from package " + bp.sourcePackage); 10390 flags |= UPDATE_PERMISSIONS_ALL; 10391 it.remove(); 10392 } 10393 } 10394 } 10395 10396 // Make sure all dynamic permissions have been assigned to a package, 10397 // and make sure there are no dangling permissions. 10398 it = mSettings.mPermissions.values().iterator(); 10399 while (it.hasNext()) { 10400 final BasePermission bp = it.next(); 10401 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10402 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10403 + bp.name + " pkg=" + bp.sourcePackage 10404 + " info=" + bp.pendingInfo); 10405 if (bp.packageSetting == null && bp.pendingInfo != null) { 10406 final BasePermission tree = findPermissionTreeLP(bp.name); 10407 if (tree != null && tree.perm != null) { 10408 bp.packageSetting = tree.packageSetting; 10409 bp.perm = new PackageParser.Permission(tree.perm.owner, 10410 new PermissionInfo(bp.pendingInfo)); 10411 bp.perm.info.packageName = tree.perm.info.packageName; 10412 bp.perm.info.name = bp.name; 10413 bp.uid = tree.uid; 10414 } 10415 } 10416 } 10417 if (bp.packageSetting == null) { 10418 // We may not yet have parsed the package, so just see if 10419 // we still know about its settings. 10420 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10421 } 10422 if (bp.packageSetting == null) { 10423 Slog.w(TAG, "Removing dangling permission: " + bp.name 10424 + " from package " + bp.sourcePackage); 10425 it.remove(); 10426 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10427 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10428 Slog.i(TAG, "Removing old permission: " + bp.name 10429 + " from package " + bp.sourcePackage); 10430 flags |= UPDATE_PERMISSIONS_ALL; 10431 it.remove(); 10432 } 10433 } 10434 } 10435 10436 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10437 // Now update the permissions for all packages, in particular 10438 // replace the granted permissions of the system packages. 10439 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10440 for (PackageParser.Package pkg : mPackages.values()) { 10441 if (pkg != pkgInfo) { 10442 // Only replace for packages on requested volume 10443 final String volumeUuid = getVolumeUuidForPackage(pkg); 10444 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10445 && Objects.equals(replaceVolumeUuid, volumeUuid); 10446 grantPermissionsLPw(pkg, replace, changingPkg); 10447 } 10448 } 10449 } 10450 10451 if (pkgInfo != null) { 10452 // Only replace for packages on requested volume 10453 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10454 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10455 && Objects.equals(replaceVolumeUuid, volumeUuid); 10456 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10457 } 10458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10459 } 10460 10461 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10462 String packageOfInterest) { 10463 // IMPORTANT: There are two types of permissions: install and runtime. 10464 // Install time permissions are granted when the app is installed to 10465 // all device users and users added in the future. Runtime permissions 10466 // are granted at runtime explicitly to specific users. Normal and signature 10467 // protected permissions are install time permissions. Dangerous permissions 10468 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10469 // otherwise they are runtime permissions. This function does not manage 10470 // runtime permissions except for the case an app targeting Lollipop MR1 10471 // being upgraded to target a newer SDK, in which case dangerous permissions 10472 // are transformed from install time to runtime ones. 10473 10474 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10475 if (ps == null) { 10476 return; 10477 } 10478 10479 PermissionsState permissionsState = ps.getPermissionsState(); 10480 PermissionsState origPermissions = permissionsState; 10481 10482 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10483 10484 boolean runtimePermissionsRevoked = false; 10485 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10486 10487 boolean changedInstallPermission = false; 10488 10489 if (replace) { 10490 ps.installPermissionsFixed = false; 10491 if (!ps.isSharedUser()) { 10492 origPermissions = new PermissionsState(permissionsState); 10493 permissionsState.reset(); 10494 } else { 10495 // We need to know only about runtime permission changes since the 10496 // calling code always writes the install permissions state but 10497 // the runtime ones are written only if changed. The only cases of 10498 // changed runtime permissions here are promotion of an install to 10499 // runtime and revocation of a runtime from a shared user. 10500 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10501 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10502 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10503 runtimePermissionsRevoked = true; 10504 } 10505 } 10506 } 10507 10508 permissionsState.setGlobalGids(mGlobalGids); 10509 10510 final int N = pkg.requestedPermissions.size(); 10511 for (int i=0; i<N; i++) { 10512 final String name = pkg.requestedPermissions.get(i); 10513 final BasePermission bp = mSettings.mPermissions.get(name); 10514 10515 if (DEBUG_INSTALL) { 10516 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10517 } 10518 10519 if (bp == null || bp.packageSetting == null) { 10520 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10521 Slog.w(TAG, "Unknown permission " + name 10522 + " in package " + pkg.packageName); 10523 } 10524 continue; 10525 } 10526 10527 10528 // Limit ephemeral apps to ephemeral allowed permissions. 10529 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10530 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10531 + pkg.packageName); 10532 continue; 10533 } 10534 10535 final String perm = bp.name; 10536 boolean allowedSig = false; 10537 int grant = GRANT_DENIED; 10538 10539 // Keep track of app op permissions. 10540 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10541 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10542 if (pkgs == null) { 10543 pkgs = new ArraySet<>(); 10544 mAppOpPermissionPackages.put(bp.name, pkgs); 10545 } 10546 pkgs.add(pkg.packageName); 10547 } 10548 10549 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10550 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10551 >= Build.VERSION_CODES.M; 10552 switch (level) { 10553 case PermissionInfo.PROTECTION_NORMAL: { 10554 // For all apps normal permissions are install time ones. 10555 grant = GRANT_INSTALL; 10556 } break; 10557 10558 case PermissionInfo.PROTECTION_DANGEROUS: { 10559 // If a permission review is required for legacy apps we represent 10560 // their permissions as always granted runtime ones since we need 10561 // to keep the review required permission flag per user while an 10562 // install permission's state is shared across all users. 10563 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10564 // For legacy apps dangerous permissions are install time ones. 10565 grant = GRANT_INSTALL; 10566 } else if (origPermissions.hasInstallPermission(bp.name)) { 10567 // For legacy apps that became modern, install becomes runtime. 10568 grant = GRANT_UPGRADE; 10569 } else if (mPromoteSystemApps 10570 && isSystemApp(ps) 10571 && mExistingSystemPackages.contains(ps.name)) { 10572 // For legacy system apps, install becomes runtime. 10573 // We cannot check hasInstallPermission() for system apps since those 10574 // permissions were granted implicitly and not persisted pre-M. 10575 grant = GRANT_UPGRADE; 10576 } else { 10577 // For modern apps keep runtime permissions unchanged. 10578 grant = GRANT_RUNTIME; 10579 } 10580 } break; 10581 10582 case PermissionInfo.PROTECTION_SIGNATURE: { 10583 // For all apps signature permissions are install time ones. 10584 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10585 if (allowedSig) { 10586 grant = GRANT_INSTALL; 10587 } 10588 } break; 10589 } 10590 10591 if (DEBUG_INSTALL) { 10592 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10593 } 10594 10595 if (grant != GRANT_DENIED) { 10596 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10597 // If this is an existing, non-system package, then 10598 // we can't add any new permissions to it. 10599 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10600 // Except... if this is a permission that was added 10601 // to the platform (note: need to only do this when 10602 // updating the platform). 10603 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10604 grant = GRANT_DENIED; 10605 } 10606 } 10607 } 10608 10609 switch (grant) { 10610 case GRANT_INSTALL: { 10611 // Revoke this as runtime permission to handle the case of 10612 // a runtime permission being downgraded to an install one. 10613 // Also in permission review mode we keep dangerous permissions 10614 // for legacy apps 10615 for (int userId : UserManagerService.getInstance().getUserIds()) { 10616 if (origPermissions.getRuntimePermissionState( 10617 bp.name, userId) != null) { 10618 // Revoke the runtime permission and clear the flags. 10619 origPermissions.revokeRuntimePermission(bp, userId); 10620 origPermissions.updatePermissionFlags(bp, userId, 10621 PackageManager.MASK_PERMISSION_FLAGS, 0); 10622 // If we revoked a permission permission, we have to write. 10623 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10624 changedRuntimePermissionUserIds, userId); 10625 } 10626 } 10627 // Grant an install permission. 10628 if (permissionsState.grantInstallPermission(bp) != 10629 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10630 changedInstallPermission = true; 10631 } 10632 } break; 10633 10634 case GRANT_RUNTIME: { 10635 // Grant previously granted runtime permissions. 10636 for (int userId : UserManagerService.getInstance().getUserIds()) { 10637 PermissionState permissionState = origPermissions 10638 .getRuntimePermissionState(bp.name, userId); 10639 int flags = permissionState != null 10640 ? permissionState.getFlags() : 0; 10641 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10642 if (permissionsState.grantRuntimePermission(bp, userId) == 10643 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10644 // If we cannot put the permission as it was, we have to write. 10645 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10646 changedRuntimePermissionUserIds, userId); 10647 } 10648 // If the app supports runtime permissions no need for a review. 10649 if (mPermissionReviewRequired 10650 && appSupportsRuntimePermissions 10651 && (flags & PackageManager 10652 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10653 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10654 // Since we changed the flags, we have to write. 10655 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10656 changedRuntimePermissionUserIds, userId); 10657 } 10658 } else if (mPermissionReviewRequired 10659 && !appSupportsRuntimePermissions) { 10660 // For legacy apps that need a permission review, every new 10661 // runtime permission is granted but it is pending a review. 10662 // We also need to review only platform defined runtime 10663 // permissions as these are the only ones the platform knows 10664 // how to disable the API to simulate revocation as legacy 10665 // apps don't expect to run with revoked permissions. 10666 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10667 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10668 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10669 // We changed the flags, hence have to write. 10670 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10671 changedRuntimePermissionUserIds, userId); 10672 } 10673 } 10674 if (permissionsState.grantRuntimePermission(bp, userId) 10675 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10676 // We changed the permission, hence have to write. 10677 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10678 changedRuntimePermissionUserIds, userId); 10679 } 10680 } 10681 // Propagate the permission flags. 10682 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10683 } 10684 } break; 10685 10686 case GRANT_UPGRADE: { 10687 // Grant runtime permissions for a previously held install permission. 10688 PermissionState permissionState = origPermissions 10689 .getInstallPermissionState(bp.name); 10690 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10691 10692 if (origPermissions.revokeInstallPermission(bp) 10693 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10694 // We will be transferring the permission flags, so clear them. 10695 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10696 PackageManager.MASK_PERMISSION_FLAGS, 0); 10697 changedInstallPermission = true; 10698 } 10699 10700 // If the permission is not to be promoted to runtime we ignore it and 10701 // also its other flags as they are not applicable to install permissions. 10702 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10703 for (int userId : currentUserIds) { 10704 if (permissionsState.grantRuntimePermission(bp, userId) != 10705 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10706 // Transfer the permission flags. 10707 permissionsState.updatePermissionFlags(bp, userId, 10708 flags, flags); 10709 // If we granted the permission, we have to write. 10710 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10711 changedRuntimePermissionUserIds, userId); 10712 } 10713 } 10714 } 10715 } break; 10716 10717 default: { 10718 if (packageOfInterest == null 10719 || packageOfInterest.equals(pkg.packageName)) { 10720 Slog.w(TAG, "Not granting permission " + perm 10721 + " to package " + pkg.packageName 10722 + " because it was previously installed without"); 10723 } 10724 } break; 10725 } 10726 } else { 10727 if (permissionsState.revokeInstallPermission(bp) != 10728 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10729 // Also drop the permission flags. 10730 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10731 PackageManager.MASK_PERMISSION_FLAGS, 0); 10732 changedInstallPermission = true; 10733 Slog.i(TAG, "Un-granting permission " + perm 10734 + " from package " + pkg.packageName 10735 + " (protectionLevel=" + bp.protectionLevel 10736 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10737 + ")"); 10738 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10739 // Don't print warning for app op permissions, since it is fine for them 10740 // not to be granted, there is a UI for the user to decide. 10741 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10742 Slog.w(TAG, "Not granting permission " + perm 10743 + " to package " + pkg.packageName 10744 + " (protectionLevel=" + bp.protectionLevel 10745 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10746 + ")"); 10747 } 10748 } 10749 } 10750 } 10751 10752 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10753 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10754 // This is the first that we have heard about this package, so the 10755 // permissions we have now selected are fixed until explicitly 10756 // changed. 10757 ps.installPermissionsFixed = true; 10758 } 10759 10760 // Persist the runtime permissions state for users with changes. If permissions 10761 // were revoked because no app in the shared user declares them we have to 10762 // write synchronously to avoid losing runtime permissions state. 10763 for (int userId : changedRuntimePermissionUserIds) { 10764 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10765 } 10766 } 10767 10768 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10769 boolean allowed = false; 10770 final int NP = PackageParser.NEW_PERMISSIONS.length; 10771 for (int ip=0; ip<NP; ip++) { 10772 final PackageParser.NewPermissionInfo npi 10773 = PackageParser.NEW_PERMISSIONS[ip]; 10774 if (npi.name.equals(perm) 10775 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10776 allowed = true; 10777 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10778 + pkg.packageName); 10779 break; 10780 } 10781 } 10782 return allowed; 10783 } 10784 10785 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10786 BasePermission bp, PermissionsState origPermissions) { 10787 boolean privilegedPermission = (bp.protectionLevel 10788 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10789 boolean privappPermissionsDisable = 10790 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10791 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10792 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10793 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10794 && !platformPackage && platformPermission) { 10795 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10796 .getPrivAppPermissions(pkg.packageName); 10797 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10798 if (!whitelisted) { 10799 Slog.w(TAG, "Privileged permission " + perm + " for package " 10800 + pkg.packageName + " - not in privapp-permissions whitelist"); 10801 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10802 return false; 10803 } 10804 } 10805 } 10806 boolean allowed = (compareSignatures( 10807 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10808 == PackageManager.SIGNATURE_MATCH) 10809 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10810 == PackageManager.SIGNATURE_MATCH); 10811 if (!allowed && privilegedPermission) { 10812 if (isSystemApp(pkg)) { 10813 // For updated system applications, a system permission 10814 // is granted only if it had been defined by the original application. 10815 if (pkg.isUpdatedSystemApp()) { 10816 final PackageSetting sysPs = mSettings 10817 .getDisabledSystemPkgLPr(pkg.packageName); 10818 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10819 // If the original was granted this permission, we take 10820 // that grant decision as read and propagate it to the 10821 // update. 10822 if (sysPs.isPrivileged()) { 10823 allowed = true; 10824 } 10825 } else { 10826 // The system apk may have been updated with an older 10827 // version of the one on the data partition, but which 10828 // granted a new system permission that it didn't have 10829 // before. In this case we do want to allow the app to 10830 // now get the new permission if the ancestral apk is 10831 // privileged to get it. 10832 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10833 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10834 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10835 allowed = true; 10836 break; 10837 } 10838 } 10839 } 10840 // Also if a privileged parent package on the system image or any of 10841 // its children requested a privileged permission, the updated child 10842 // packages can also get the permission. 10843 if (pkg.parentPackage != null) { 10844 final PackageSetting disabledSysParentPs = mSettings 10845 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10846 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10847 && disabledSysParentPs.isPrivileged()) { 10848 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10849 allowed = true; 10850 } else if (disabledSysParentPs.pkg.childPackages != null) { 10851 final int count = disabledSysParentPs.pkg.childPackages.size(); 10852 for (int i = 0; i < count; i++) { 10853 PackageParser.Package disabledSysChildPkg = 10854 disabledSysParentPs.pkg.childPackages.get(i); 10855 if (isPackageRequestingPermission(disabledSysChildPkg, 10856 perm)) { 10857 allowed = true; 10858 break; 10859 } 10860 } 10861 } 10862 } 10863 } 10864 } 10865 } else { 10866 allowed = isPrivilegedApp(pkg); 10867 } 10868 } 10869 } 10870 if (!allowed) { 10871 if (!allowed && (bp.protectionLevel 10872 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10873 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10874 // If this was a previously normal/dangerous permission that got moved 10875 // to a system permission as part of the runtime permission redesign, then 10876 // we still want to blindly grant it to old apps. 10877 allowed = true; 10878 } 10879 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10880 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10881 // If this permission is to be granted to the system installer and 10882 // this app is an installer, then it gets the permission. 10883 allowed = true; 10884 } 10885 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10886 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10887 // If this permission is to be granted to the system verifier and 10888 // this app is a verifier, then it gets the permission. 10889 allowed = true; 10890 } 10891 if (!allowed && (bp.protectionLevel 10892 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10893 && isSystemApp(pkg)) { 10894 // Any pre-installed system app is allowed to get this permission. 10895 allowed = true; 10896 } 10897 if (!allowed && (bp.protectionLevel 10898 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10899 // For development permissions, a development permission 10900 // is granted only if it was already granted. 10901 allowed = origPermissions.hasInstallPermission(perm); 10902 } 10903 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10904 && pkg.packageName.equals(mSetupWizardPackage)) { 10905 // If this permission is to be granted to the system setup wizard and 10906 // this app is a setup wizard, then it gets the permission. 10907 allowed = true; 10908 } 10909 } 10910 return allowed; 10911 } 10912 10913 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10914 final int permCount = pkg.requestedPermissions.size(); 10915 for (int j = 0; j < permCount; j++) { 10916 String requestedPermission = pkg.requestedPermissions.get(j); 10917 if (permission.equals(requestedPermission)) { 10918 return true; 10919 } 10920 } 10921 return false; 10922 } 10923 10924 final class ActivityIntentResolver 10925 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10926 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10927 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 10928 if (!sUserManager.exists(userId)) return null; 10929 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0) 10930 | (visibleToEphemeral ? PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY : 0) 10931 | (isEphemeral ? PackageManager.MATCH_EPHEMERAL : 0); 10932 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 10933 isEphemeral, userId); 10934 } 10935 10936 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10937 int userId) { 10938 if (!sUserManager.exists(userId)) return null; 10939 mFlags = flags; 10940 return super.queryIntent(intent, resolvedType, 10941 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 10942 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 10943 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 10944 } 10945 10946 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10947 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10948 if (!sUserManager.exists(userId)) return null; 10949 if (packageActivities == null) { 10950 return null; 10951 } 10952 mFlags = flags; 10953 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10954 final boolean vislbleToEphemeral = 10955 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 10956 final boolean isEphemeral = (flags & PackageManager.MATCH_EPHEMERAL) != 0; 10957 final int N = packageActivities.size(); 10958 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10959 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10960 10961 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10962 for (int i = 0; i < N; ++i) { 10963 intentFilters = packageActivities.get(i).intents; 10964 if (intentFilters != null && intentFilters.size() > 0) { 10965 PackageParser.ActivityIntentInfo[] array = 10966 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10967 intentFilters.toArray(array); 10968 listCut.add(array); 10969 } 10970 } 10971 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 10972 vislbleToEphemeral, isEphemeral, listCut, userId); 10973 } 10974 10975 /** 10976 * Finds a privileged activity that matches the specified activity names. 10977 */ 10978 private PackageParser.Activity findMatchingActivity( 10979 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10980 for (PackageParser.Activity sysActivity : activityList) { 10981 if (sysActivity.info.name.equals(activityInfo.name)) { 10982 return sysActivity; 10983 } 10984 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10985 return sysActivity; 10986 } 10987 if (sysActivity.info.targetActivity != null) { 10988 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10989 return sysActivity; 10990 } 10991 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10992 return sysActivity; 10993 } 10994 } 10995 } 10996 return null; 10997 } 10998 10999 public class IterGenerator<E> { 11000 public Iterator<E> generate(ActivityIntentInfo info) { 11001 return null; 11002 } 11003 } 11004 11005 public class ActionIterGenerator extends IterGenerator<String> { 11006 @Override 11007 public Iterator<String> generate(ActivityIntentInfo info) { 11008 return info.actionsIterator(); 11009 } 11010 } 11011 11012 public class CategoriesIterGenerator extends IterGenerator<String> { 11013 @Override 11014 public Iterator<String> generate(ActivityIntentInfo info) { 11015 return info.categoriesIterator(); 11016 } 11017 } 11018 11019 public class SchemesIterGenerator extends IterGenerator<String> { 11020 @Override 11021 public Iterator<String> generate(ActivityIntentInfo info) { 11022 return info.schemesIterator(); 11023 } 11024 } 11025 11026 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11027 @Override 11028 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11029 return info.authoritiesIterator(); 11030 } 11031 } 11032 11033 /** 11034 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11035 * MODIFIED. Do not pass in a list that should not be changed. 11036 */ 11037 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11038 IterGenerator<T> generator, Iterator<T> searchIterator) { 11039 // loop through the set of actions; every one must be found in the intent filter 11040 while (searchIterator.hasNext()) { 11041 // we must have at least one filter in the list to consider a match 11042 if (intentList.size() == 0) { 11043 break; 11044 } 11045 11046 final T searchAction = searchIterator.next(); 11047 11048 // loop through the set of intent filters 11049 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11050 while (intentIter.hasNext()) { 11051 final ActivityIntentInfo intentInfo = intentIter.next(); 11052 boolean selectionFound = false; 11053 11054 // loop through the intent filter's selection criteria; at least one 11055 // of them must match the searched criteria 11056 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11057 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11058 final T intentSelection = intentSelectionIter.next(); 11059 if (intentSelection != null && intentSelection.equals(searchAction)) { 11060 selectionFound = true; 11061 break; 11062 } 11063 } 11064 11065 // the selection criteria wasn't found in this filter's set; this filter 11066 // is not a potential match 11067 if (!selectionFound) { 11068 intentIter.remove(); 11069 } 11070 } 11071 } 11072 } 11073 11074 private boolean isProtectedAction(ActivityIntentInfo filter) { 11075 final Iterator<String> actionsIter = filter.actionsIterator(); 11076 while (actionsIter != null && actionsIter.hasNext()) { 11077 final String filterAction = actionsIter.next(); 11078 if (PROTECTED_ACTIONS.contains(filterAction)) { 11079 return true; 11080 } 11081 } 11082 return false; 11083 } 11084 11085 /** 11086 * Adjusts the priority of the given intent filter according to policy. 11087 * <p> 11088 * <ul> 11089 * <li>The priority for non privileged applications is capped to '0'</li> 11090 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11091 * <li>The priority for unbundled updates to privileged applications is capped to the 11092 * priority defined on the system partition</li> 11093 * </ul> 11094 * <p> 11095 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11096 * allowed to obtain any priority on any action. 11097 */ 11098 private void adjustPriority( 11099 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11100 // nothing to do; priority is fine as-is 11101 if (intent.getPriority() <= 0) { 11102 return; 11103 } 11104 11105 final ActivityInfo activityInfo = intent.activity.info; 11106 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11107 11108 final boolean privilegedApp = 11109 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11110 if (!privilegedApp) { 11111 // non-privileged applications can never define a priority >0 11112 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11113 + " package: " + applicationInfo.packageName 11114 + " activity: " + intent.activity.className 11115 + " origPrio: " + intent.getPriority()); 11116 intent.setPriority(0); 11117 return; 11118 } 11119 11120 if (systemActivities == null) { 11121 // the system package is not disabled; we're parsing the system partition 11122 if (isProtectedAction(intent)) { 11123 if (mDeferProtectedFilters) { 11124 // We can't deal with these just yet. No component should ever obtain a 11125 // >0 priority for a protected actions, with ONE exception -- the setup 11126 // wizard. The setup wizard, however, cannot be known until we're able to 11127 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11128 // until all intent filters have been processed. Chicken, meet egg. 11129 // Let the filter temporarily have a high priority and rectify the 11130 // priorities after all system packages have been scanned. 11131 mProtectedFilters.add(intent); 11132 if (DEBUG_FILTERS) { 11133 Slog.i(TAG, "Protected action; save for later;" 11134 + " package: " + applicationInfo.packageName 11135 + " activity: " + intent.activity.className 11136 + " origPrio: " + intent.getPriority()); 11137 } 11138 return; 11139 } else { 11140 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11141 Slog.i(TAG, "No setup wizard;" 11142 + " All protected intents capped to priority 0"); 11143 } 11144 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11145 if (DEBUG_FILTERS) { 11146 Slog.i(TAG, "Found setup wizard;" 11147 + " allow priority " + intent.getPriority() + ";" 11148 + " package: " + intent.activity.info.packageName 11149 + " activity: " + intent.activity.className 11150 + " priority: " + intent.getPriority()); 11151 } 11152 // setup wizard gets whatever it wants 11153 return; 11154 } 11155 Slog.w(TAG, "Protected action; cap priority to 0;" 11156 + " package: " + intent.activity.info.packageName 11157 + " activity: " + intent.activity.className 11158 + " origPrio: " + intent.getPriority()); 11159 intent.setPriority(0); 11160 return; 11161 } 11162 } 11163 // privileged apps on the system image get whatever priority they request 11164 return; 11165 } 11166 11167 // privileged app unbundled update ... try to find the same activity 11168 final PackageParser.Activity foundActivity = 11169 findMatchingActivity(systemActivities, activityInfo); 11170 if (foundActivity == null) { 11171 // this is a new activity; it cannot obtain >0 priority 11172 if (DEBUG_FILTERS) { 11173 Slog.i(TAG, "New activity; cap priority to 0;" 11174 + " package: " + applicationInfo.packageName 11175 + " activity: " + intent.activity.className 11176 + " origPrio: " + intent.getPriority()); 11177 } 11178 intent.setPriority(0); 11179 return; 11180 } 11181 11182 // found activity, now check for filter equivalence 11183 11184 // a shallow copy is enough; we modify the list, not its contents 11185 final List<ActivityIntentInfo> intentListCopy = 11186 new ArrayList<>(foundActivity.intents); 11187 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11188 11189 // find matching action subsets 11190 final Iterator<String> actionsIterator = intent.actionsIterator(); 11191 if (actionsIterator != null) { 11192 getIntentListSubset( 11193 intentListCopy, new ActionIterGenerator(), actionsIterator); 11194 if (intentListCopy.size() == 0) { 11195 // no more intents to match; we're not equivalent 11196 if (DEBUG_FILTERS) { 11197 Slog.i(TAG, "Mismatched action; cap priority to 0;" 11198 + " package: " + applicationInfo.packageName 11199 + " activity: " + intent.activity.className 11200 + " origPrio: " + intent.getPriority()); 11201 } 11202 intent.setPriority(0); 11203 return; 11204 } 11205 } 11206 11207 // find matching category subsets 11208 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 11209 if (categoriesIterator != null) { 11210 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 11211 categoriesIterator); 11212 if (intentListCopy.size() == 0) { 11213 // no more intents to match; we're not equivalent 11214 if (DEBUG_FILTERS) { 11215 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11216 + " package: " + applicationInfo.packageName 11217 + " activity: " + intent.activity.className 11218 + " origPrio: " + intent.getPriority()); 11219 } 11220 intent.setPriority(0); 11221 return; 11222 } 11223 } 11224 11225 // find matching schemes subsets 11226 final Iterator<String> schemesIterator = intent.schemesIterator(); 11227 if (schemesIterator != null) { 11228 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11229 schemesIterator); 11230 if (intentListCopy.size() == 0) { 11231 // no more intents to match; we're not equivalent 11232 if (DEBUG_FILTERS) { 11233 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11234 + " package: " + applicationInfo.packageName 11235 + " activity: " + intent.activity.className 11236 + " origPrio: " + intent.getPriority()); 11237 } 11238 intent.setPriority(0); 11239 return; 11240 } 11241 } 11242 11243 // find matching authorities subsets 11244 final Iterator<IntentFilter.AuthorityEntry> 11245 authoritiesIterator = intent.authoritiesIterator(); 11246 if (authoritiesIterator != null) { 11247 getIntentListSubset(intentListCopy, 11248 new AuthoritiesIterGenerator(), 11249 authoritiesIterator); 11250 if (intentListCopy.size() == 0) { 11251 // no more intents to match; we're not equivalent 11252 if (DEBUG_FILTERS) { 11253 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11254 + " package: " + applicationInfo.packageName 11255 + " activity: " + intent.activity.className 11256 + " origPrio: " + intent.getPriority()); 11257 } 11258 intent.setPriority(0); 11259 return; 11260 } 11261 } 11262 11263 // we found matching filter(s); app gets the max priority of all intents 11264 int cappedPriority = 0; 11265 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11266 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11267 } 11268 if (intent.getPriority() > cappedPriority) { 11269 if (DEBUG_FILTERS) { 11270 Slog.i(TAG, "Found matching filter(s);" 11271 + " cap priority to " + cappedPriority + ";" 11272 + " package: " + applicationInfo.packageName 11273 + " activity: " + intent.activity.className 11274 + " origPrio: " + intent.getPriority()); 11275 } 11276 intent.setPriority(cappedPriority); 11277 return; 11278 } 11279 // all this for nothing; the requested priority was <= what was on the system 11280 } 11281 11282 public final void addActivity(PackageParser.Activity a, String type) { 11283 mActivities.put(a.getComponentName(), a); 11284 if (DEBUG_SHOW_INFO) 11285 Log.v( 11286 TAG, " " + type + " " + 11287 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11288 if (DEBUG_SHOW_INFO) 11289 Log.v(TAG, " Class=" + a.info.name); 11290 final int NI = a.intents.size(); 11291 for (int j=0; j<NI; j++) { 11292 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11293 if ("activity".equals(type)) { 11294 final PackageSetting ps = 11295 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11296 final List<PackageParser.Activity> systemActivities = 11297 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11298 adjustPriority(systemActivities, intent); 11299 } 11300 if (DEBUG_SHOW_INFO) { 11301 Log.v(TAG, " IntentFilter:"); 11302 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11303 } 11304 if (!intent.debugCheck()) { 11305 Log.w(TAG, "==> For Activity " + a.info.name); 11306 } 11307 addFilter(intent); 11308 } 11309 } 11310 11311 public final void removeActivity(PackageParser.Activity a, String type) { 11312 mActivities.remove(a.getComponentName()); 11313 if (DEBUG_SHOW_INFO) { 11314 Log.v(TAG, " " + type + " " 11315 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11316 : a.info.name) + ":"); 11317 Log.v(TAG, " Class=" + a.info.name); 11318 } 11319 final int NI = a.intents.size(); 11320 for (int j=0; j<NI; j++) { 11321 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11322 if (DEBUG_SHOW_INFO) { 11323 Log.v(TAG, " IntentFilter:"); 11324 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11325 } 11326 removeFilter(intent); 11327 } 11328 } 11329 11330 @Override 11331 protected boolean allowFilterResult( 11332 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11333 ActivityInfo filterAi = filter.activity.info; 11334 for (int i=dest.size()-1; i>=0; i--) { 11335 ActivityInfo destAi = dest.get(i).activityInfo; 11336 if (destAi.name == filterAi.name 11337 && destAi.packageName == filterAi.packageName) { 11338 return false; 11339 } 11340 } 11341 return true; 11342 } 11343 11344 @Override 11345 protected ActivityIntentInfo[] newArray(int size) { 11346 return new ActivityIntentInfo[size]; 11347 } 11348 11349 @Override 11350 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11351 if (!sUserManager.exists(userId)) return true; 11352 PackageParser.Package p = filter.activity.owner; 11353 if (p != null) { 11354 PackageSetting ps = (PackageSetting)p.mExtras; 11355 if (ps != null) { 11356 // System apps are never considered stopped for purposes of 11357 // filtering, because there may be no way for the user to 11358 // actually re-launch them. 11359 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11360 && ps.getStopped(userId); 11361 } 11362 } 11363 return false; 11364 } 11365 11366 @Override 11367 protected boolean isPackageForFilter(String packageName, 11368 PackageParser.ActivityIntentInfo info) { 11369 return packageName.equals(info.activity.owner.packageName); 11370 } 11371 11372 @Override 11373 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11374 int match, int userId) { 11375 if (!sUserManager.exists(userId)) return null; 11376 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11377 return null; 11378 } 11379 final PackageParser.Activity activity = info.activity; 11380 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11381 if (ps == null) { 11382 return null; 11383 } 11384 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11385 ps.readUserState(userId), userId); 11386 if (ai == null) { 11387 return null; 11388 } 11389 final ResolveInfo res = new ResolveInfo(); 11390 res.activityInfo = ai; 11391 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11392 res.filter = info; 11393 } 11394 if (info != null) { 11395 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11396 } 11397 res.priority = info.getPriority(); 11398 res.preferredOrder = activity.owner.mPreferredOrder; 11399 //System.out.println("Result: " + res.activityInfo.className + 11400 // " = " + res.priority); 11401 res.match = match; 11402 res.isDefault = info.hasDefault; 11403 res.labelRes = info.labelRes; 11404 res.nonLocalizedLabel = info.nonLocalizedLabel; 11405 if (userNeedsBadging(userId)) { 11406 res.noResourceId = true; 11407 } else { 11408 res.icon = info.icon; 11409 } 11410 res.iconResourceId = info.icon; 11411 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11412 return res; 11413 } 11414 11415 @Override 11416 protected void sortResults(List<ResolveInfo> results) { 11417 Collections.sort(results, mResolvePrioritySorter); 11418 } 11419 11420 @Override 11421 protected void dumpFilter(PrintWriter out, String prefix, 11422 PackageParser.ActivityIntentInfo filter) { 11423 out.print(prefix); out.print( 11424 Integer.toHexString(System.identityHashCode(filter.activity))); 11425 out.print(' '); 11426 filter.activity.printComponentShortName(out); 11427 out.print(" filter "); 11428 out.println(Integer.toHexString(System.identityHashCode(filter))); 11429 } 11430 11431 @Override 11432 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11433 return filter.activity; 11434 } 11435 11436 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11437 PackageParser.Activity activity = (PackageParser.Activity)label; 11438 out.print(prefix); out.print( 11439 Integer.toHexString(System.identityHashCode(activity))); 11440 out.print(' '); 11441 activity.printComponentShortName(out); 11442 if (count > 1) { 11443 out.print(" ("); out.print(count); out.print(" filters)"); 11444 } 11445 out.println(); 11446 } 11447 11448 // Keys are String (activity class name), values are Activity. 11449 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11450 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11451 private int mFlags; 11452 } 11453 11454 private final class ServiceIntentResolver 11455 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11456 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11457 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11458 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11459 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11460 isEphemeral, userId); 11461 } 11462 11463 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11464 int userId) { 11465 if (!sUserManager.exists(userId)) return null; 11466 mFlags = flags; 11467 return super.queryIntent(intent, resolvedType, 11468 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11469 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11470 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11471 } 11472 11473 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11474 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11475 if (!sUserManager.exists(userId)) return null; 11476 if (packageServices == null) { 11477 return null; 11478 } 11479 mFlags = flags; 11480 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11481 final boolean vislbleToEphemeral = 11482 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11483 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11484 final int N = packageServices.size(); 11485 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11486 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11487 11488 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11489 for (int i = 0; i < N; ++i) { 11490 intentFilters = packageServices.get(i).intents; 11491 if (intentFilters != null && intentFilters.size() > 0) { 11492 PackageParser.ServiceIntentInfo[] array = 11493 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11494 intentFilters.toArray(array); 11495 listCut.add(array); 11496 } 11497 } 11498 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11499 vislbleToEphemeral, isEphemeral, listCut, userId); 11500 } 11501 11502 public final void addService(PackageParser.Service s) { 11503 mServices.put(s.getComponentName(), s); 11504 if (DEBUG_SHOW_INFO) { 11505 Log.v(TAG, " " 11506 + (s.info.nonLocalizedLabel != null 11507 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11508 Log.v(TAG, " Class=" + s.info.name); 11509 } 11510 final int NI = s.intents.size(); 11511 int j; 11512 for (j=0; j<NI; j++) { 11513 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11514 if (DEBUG_SHOW_INFO) { 11515 Log.v(TAG, " IntentFilter:"); 11516 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11517 } 11518 if (!intent.debugCheck()) { 11519 Log.w(TAG, "==> For Service " + s.info.name); 11520 } 11521 addFilter(intent); 11522 } 11523 } 11524 11525 public final void removeService(PackageParser.Service s) { 11526 mServices.remove(s.getComponentName()); 11527 if (DEBUG_SHOW_INFO) { 11528 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11529 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11530 Log.v(TAG, " Class=" + s.info.name); 11531 } 11532 final int NI = s.intents.size(); 11533 int j; 11534 for (j=0; j<NI; j++) { 11535 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11536 if (DEBUG_SHOW_INFO) { 11537 Log.v(TAG, " IntentFilter:"); 11538 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11539 } 11540 removeFilter(intent); 11541 } 11542 } 11543 11544 @Override 11545 protected boolean allowFilterResult( 11546 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11547 ServiceInfo filterSi = filter.service.info; 11548 for (int i=dest.size()-1; i>=0; i--) { 11549 ServiceInfo destAi = dest.get(i).serviceInfo; 11550 if (destAi.name == filterSi.name 11551 && destAi.packageName == filterSi.packageName) { 11552 return false; 11553 } 11554 } 11555 return true; 11556 } 11557 11558 @Override 11559 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11560 return new PackageParser.ServiceIntentInfo[size]; 11561 } 11562 11563 @Override 11564 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11565 if (!sUserManager.exists(userId)) return true; 11566 PackageParser.Package p = filter.service.owner; 11567 if (p != null) { 11568 PackageSetting ps = (PackageSetting)p.mExtras; 11569 if (ps != null) { 11570 // System apps are never considered stopped for purposes of 11571 // filtering, because there may be no way for the user to 11572 // actually re-launch them. 11573 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11574 && ps.getStopped(userId); 11575 } 11576 } 11577 return false; 11578 } 11579 11580 @Override 11581 protected boolean isPackageForFilter(String packageName, 11582 PackageParser.ServiceIntentInfo info) { 11583 return packageName.equals(info.service.owner.packageName); 11584 } 11585 11586 @Override 11587 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11588 int match, int userId) { 11589 if (!sUserManager.exists(userId)) return null; 11590 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11591 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11592 return null; 11593 } 11594 final PackageParser.Service service = info.service; 11595 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11596 if (ps == null) { 11597 return null; 11598 } 11599 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11600 ps.readUserState(userId), userId); 11601 if (si == null) { 11602 return null; 11603 } 11604 final ResolveInfo res = new ResolveInfo(); 11605 res.serviceInfo = si; 11606 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11607 res.filter = filter; 11608 } 11609 res.priority = info.getPriority(); 11610 res.preferredOrder = service.owner.mPreferredOrder; 11611 res.match = match; 11612 res.isDefault = info.hasDefault; 11613 res.labelRes = info.labelRes; 11614 res.nonLocalizedLabel = info.nonLocalizedLabel; 11615 res.icon = info.icon; 11616 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11617 return res; 11618 } 11619 11620 @Override 11621 protected void sortResults(List<ResolveInfo> results) { 11622 Collections.sort(results, mResolvePrioritySorter); 11623 } 11624 11625 @Override 11626 protected void dumpFilter(PrintWriter out, String prefix, 11627 PackageParser.ServiceIntentInfo filter) { 11628 out.print(prefix); out.print( 11629 Integer.toHexString(System.identityHashCode(filter.service))); 11630 out.print(' '); 11631 filter.service.printComponentShortName(out); 11632 out.print(" filter "); 11633 out.println(Integer.toHexString(System.identityHashCode(filter))); 11634 } 11635 11636 @Override 11637 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11638 return filter.service; 11639 } 11640 11641 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11642 PackageParser.Service service = (PackageParser.Service)label; 11643 out.print(prefix); out.print( 11644 Integer.toHexString(System.identityHashCode(service))); 11645 out.print(' '); 11646 service.printComponentShortName(out); 11647 if (count > 1) { 11648 out.print(" ("); out.print(count); out.print(" filters)"); 11649 } 11650 out.println(); 11651 } 11652 11653// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11654// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11655// final List<ResolveInfo> retList = Lists.newArrayList(); 11656// while (i.hasNext()) { 11657// final ResolveInfo resolveInfo = (ResolveInfo) i; 11658// if (isEnabledLP(resolveInfo.serviceInfo)) { 11659// retList.add(resolveInfo); 11660// } 11661// } 11662// return retList; 11663// } 11664 11665 // Keys are String (activity class name), values are Activity. 11666 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11667 = new ArrayMap<ComponentName, PackageParser.Service>(); 11668 private int mFlags; 11669 } 11670 11671 private final class ProviderIntentResolver 11672 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11673 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11674 boolean defaultOnly, boolean visibleToEphemeral, boolean isEphemeral, int userId) { 11675 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11676 return super.queryIntent(intent, resolvedType, defaultOnly, visibleToEphemeral, 11677 isEphemeral, userId); 11678 } 11679 11680 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11681 int userId) { 11682 if (!sUserManager.exists(userId)) 11683 return null; 11684 mFlags = flags; 11685 return super.queryIntent(intent, resolvedType, 11686 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11687 (flags & PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0, 11688 (flags & PackageManager.MATCH_EPHEMERAL) != 0, userId); 11689 } 11690 11691 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11692 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11693 if (!sUserManager.exists(userId)) 11694 return null; 11695 if (packageProviders == null) { 11696 return null; 11697 } 11698 mFlags = flags; 11699 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11700 final boolean isEphemeral = (flags&PackageManager.MATCH_EPHEMERAL) != 0; 11701 final boolean vislbleToEphemeral = 11702 (flags&PackageManager.MATCH_VISIBLE_TO_EPHEMERAL_ONLY) != 0; 11703 final int N = packageProviders.size(); 11704 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11705 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11706 11707 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11708 for (int i = 0; i < N; ++i) { 11709 intentFilters = packageProviders.get(i).intents; 11710 if (intentFilters != null && intentFilters.size() > 0) { 11711 PackageParser.ProviderIntentInfo[] array = 11712 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11713 intentFilters.toArray(array); 11714 listCut.add(array); 11715 } 11716 } 11717 return super.queryIntentFromList(intent, resolvedType, defaultOnly, 11718 vislbleToEphemeral, isEphemeral, listCut, userId); 11719 } 11720 11721 public final void addProvider(PackageParser.Provider p) { 11722 if (mProviders.containsKey(p.getComponentName())) { 11723 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11724 return; 11725 } 11726 11727 mProviders.put(p.getComponentName(), p); 11728 if (DEBUG_SHOW_INFO) { 11729 Log.v(TAG, " " 11730 + (p.info.nonLocalizedLabel != null 11731 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11732 Log.v(TAG, " Class=" + p.info.name); 11733 } 11734 final int NI = p.intents.size(); 11735 int j; 11736 for (j = 0; j < NI; j++) { 11737 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11738 if (DEBUG_SHOW_INFO) { 11739 Log.v(TAG, " IntentFilter:"); 11740 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11741 } 11742 if (!intent.debugCheck()) { 11743 Log.w(TAG, "==> For Provider " + p.info.name); 11744 } 11745 addFilter(intent); 11746 } 11747 } 11748 11749 public final void removeProvider(PackageParser.Provider p) { 11750 mProviders.remove(p.getComponentName()); 11751 if (DEBUG_SHOW_INFO) { 11752 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11753 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11754 Log.v(TAG, " Class=" + p.info.name); 11755 } 11756 final int NI = p.intents.size(); 11757 int j; 11758 for (j = 0; j < NI; j++) { 11759 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11760 if (DEBUG_SHOW_INFO) { 11761 Log.v(TAG, " IntentFilter:"); 11762 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11763 } 11764 removeFilter(intent); 11765 } 11766 } 11767 11768 @Override 11769 protected boolean allowFilterResult( 11770 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11771 ProviderInfo filterPi = filter.provider.info; 11772 for (int i = dest.size() - 1; i >= 0; i--) { 11773 ProviderInfo destPi = dest.get(i).providerInfo; 11774 if (destPi.name == filterPi.name 11775 && destPi.packageName == filterPi.packageName) { 11776 return false; 11777 } 11778 } 11779 return true; 11780 } 11781 11782 @Override 11783 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11784 return new PackageParser.ProviderIntentInfo[size]; 11785 } 11786 11787 @Override 11788 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11789 if (!sUserManager.exists(userId)) 11790 return true; 11791 PackageParser.Package p = filter.provider.owner; 11792 if (p != null) { 11793 PackageSetting ps = (PackageSetting) p.mExtras; 11794 if (ps != null) { 11795 // System apps are never considered stopped for purposes of 11796 // filtering, because there may be no way for the user to 11797 // actually re-launch them. 11798 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11799 && ps.getStopped(userId); 11800 } 11801 } 11802 return false; 11803 } 11804 11805 @Override 11806 protected boolean isPackageForFilter(String packageName, 11807 PackageParser.ProviderIntentInfo info) { 11808 return packageName.equals(info.provider.owner.packageName); 11809 } 11810 11811 @Override 11812 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11813 int match, int userId) { 11814 if (!sUserManager.exists(userId)) 11815 return null; 11816 final PackageParser.ProviderIntentInfo info = filter; 11817 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11818 return null; 11819 } 11820 final PackageParser.Provider provider = info.provider; 11821 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11822 if (ps == null) { 11823 return null; 11824 } 11825 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11826 ps.readUserState(userId), userId); 11827 if (pi == null) { 11828 return null; 11829 } 11830 final ResolveInfo res = new ResolveInfo(); 11831 res.providerInfo = pi; 11832 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11833 res.filter = filter; 11834 } 11835 res.priority = info.getPriority(); 11836 res.preferredOrder = provider.owner.mPreferredOrder; 11837 res.match = match; 11838 res.isDefault = info.hasDefault; 11839 res.labelRes = info.labelRes; 11840 res.nonLocalizedLabel = info.nonLocalizedLabel; 11841 res.icon = info.icon; 11842 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11843 return res; 11844 } 11845 11846 @Override 11847 protected void sortResults(List<ResolveInfo> results) { 11848 Collections.sort(results, mResolvePrioritySorter); 11849 } 11850 11851 @Override 11852 protected void dumpFilter(PrintWriter out, String prefix, 11853 PackageParser.ProviderIntentInfo filter) { 11854 out.print(prefix); 11855 out.print( 11856 Integer.toHexString(System.identityHashCode(filter.provider))); 11857 out.print(' '); 11858 filter.provider.printComponentShortName(out); 11859 out.print(" filter "); 11860 out.println(Integer.toHexString(System.identityHashCode(filter))); 11861 } 11862 11863 @Override 11864 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11865 return filter.provider; 11866 } 11867 11868 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11869 PackageParser.Provider provider = (PackageParser.Provider)label; 11870 out.print(prefix); out.print( 11871 Integer.toHexString(System.identityHashCode(provider))); 11872 out.print(' '); 11873 provider.printComponentShortName(out); 11874 if (count > 1) { 11875 out.print(" ("); out.print(count); out.print(" filters)"); 11876 } 11877 out.println(); 11878 } 11879 11880 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11881 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11882 private int mFlags; 11883 } 11884 11885 static final class EphemeralIntentResolver 11886 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11887 /** 11888 * The result that has the highest defined order. Ordering applies on a 11889 * per-package basis. Mapping is from package name to Pair of order and 11890 * EphemeralResolveInfo. 11891 * <p> 11892 * NOTE: This is implemented as a field variable for convenience and efficiency. 11893 * By having a field variable, we're able to track filter ordering as soon as 11894 * a non-zero order is defined. Otherwise, multiple loops across the result set 11895 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11896 * this needs to be contained entirely within {@link #filterResults()}. 11897 */ 11898 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11899 11900 @Override 11901 protected EphemeralResponse[] newArray(int size) { 11902 return new EphemeralResponse[size]; 11903 } 11904 11905 @Override 11906 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11907 return true; 11908 } 11909 11910 @Override 11911 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11912 int userId) { 11913 if (!sUserManager.exists(userId)) { 11914 return null; 11915 } 11916 final String packageName = responseObj.resolveInfo.getPackageName(); 11917 final Integer order = responseObj.getOrder(); 11918 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11919 mOrderResult.get(packageName); 11920 // ordering is enabled and this item's order isn't high enough 11921 if (lastOrderResult != null && lastOrderResult.first >= order) { 11922 return null; 11923 } 11924 final EphemeralResolveInfo res = responseObj.resolveInfo; 11925 if (order > 0) { 11926 // non-zero order, enable ordering 11927 mOrderResult.put(packageName, new Pair<>(order, res)); 11928 } 11929 return responseObj; 11930 } 11931 11932 @Override 11933 protected void filterResults(List<EphemeralResponse> results) { 11934 // only do work if ordering is enabled [most of the time it won't be] 11935 if (mOrderResult.size() == 0) { 11936 return; 11937 } 11938 int resultSize = results.size(); 11939 for (int i = 0; i < resultSize; i++) { 11940 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11941 final String packageName = info.getPackageName(); 11942 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11943 if (savedInfo == null) { 11944 // package doesn't having ordering 11945 continue; 11946 } 11947 if (savedInfo.second == info) { 11948 // circled back to the highest ordered item; remove from order list 11949 mOrderResult.remove(savedInfo); 11950 if (mOrderResult.size() == 0) { 11951 // no more ordered items 11952 break; 11953 } 11954 continue; 11955 } 11956 // item has a worse order, remove it from the result list 11957 results.remove(i); 11958 resultSize--; 11959 i--; 11960 } 11961 } 11962 } 11963 11964 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11965 new Comparator<ResolveInfo>() { 11966 public int compare(ResolveInfo r1, ResolveInfo r2) { 11967 int v1 = r1.priority; 11968 int v2 = r2.priority; 11969 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11970 if (v1 != v2) { 11971 return (v1 > v2) ? -1 : 1; 11972 } 11973 v1 = r1.preferredOrder; 11974 v2 = r2.preferredOrder; 11975 if (v1 != v2) { 11976 return (v1 > v2) ? -1 : 1; 11977 } 11978 if (r1.isDefault != r2.isDefault) { 11979 return r1.isDefault ? -1 : 1; 11980 } 11981 v1 = r1.match; 11982 v2 = r2.match; 11983 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11984 if (v1 != v2) { 11985 return (v1 > v2) ? -1 : 1; 11986 } 11987 if (r1.system != r2.system) { 11988 return r1.system ? -1 : 1; 11989 } 11990 if (r1.activityInfo != null) { 11991 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11992 } 11993 if (r1.serviceInfo != null) { 11994 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11995 } 11996 if (r1.providerInfo != null) { 11997 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11998 } 11999 return 0; 12000 } 12001 }; 12002 12003 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12004 new Comparator<ProviderInfo>() { 12005 public int compare(ProviderInfo p1, ProviderInfo p2) { 12006 final int v1 = p1.initOrder; 12007 final int v2 = p2.initOrder; 12008 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12009 } 12010 }; 12011 12012 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12013 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12014 final int[] userIds) { 12015 mHandler.post(new Runnable() { 12016 @Override 12017 public void run() { 12018 try { 12019 final IActivityManager am = ActivityManager.getService(); 12020 if (am == null) return; 12021 final int[] resolvedUserIds; 12022 if (userIds == null) { 12023 resolvedUserIds = am.getRunningUserIds(); 12024 } else { 12025 resolvedUserIds = userIds; 12026 } 12027 for (int id : resolvedUserIds) { 12028 final Intent intent = new Intent(action, 12029 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12030 if (extras != null) { 12031 intent.putExtras(extras); 12032 } 12033 if (targetPkg != null) { 12034 intent.setPackage(targetPkg); 12035 } 12036 // Modify the UID when posting to other users 12037 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12038 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12039 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12040 intent.putExtra(Intent.EXTRA_UID, uid); 12041 } 12042 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12043 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12044 if (DEBUG_BROADCASTS) { 12045 RuntimeException here = new RuntimeException("here"); 12046 here.fillInStackTrace(); 12047 Slog.d(TAG, "Sending to user " + id + ": " 12048 + intent.toShortString(false, true, false, false) 12049 + " " + intent.getExtras(), here); 12050 } 12051 am.broadcastIntent(null, intent, null, finishedReceiver, 12052 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12053 null, finishedReceiver != null, false, id); 12054 } 12055 } catch (RemoteException ex) { 12056 } 12057 } 12058 }); 12059 } 12060 12061 /** 12062 * Check if the external storage media is available. This is true if there 12063 * is a mounted external storage medium or if the external storage is 12064 * emulated. 12065 */ 12066 private boolean isExternalMediaAvailable() { 12067 return mMediaMounted || Environment.isExternalStorageEmulated(); 12068 } 12069 12070 @Override 12071 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12072 // writer 12073 synchronized (mPackages) { 12074 if (!isExternalMediaAvailable()) { 12075 // If the external storage is no longer mounted at this point, 12076 // the caller may not have been able to delete all of this 12077 // packages files and can not delete any more. Bail. 12078 return null; 12079 } 12080 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12081 if (lastPackage != null) { 12082 pkgs.remove(lastPackage); 12083 } 12084 if (pkgs.size() > 0) { 12085 return pkgs.get(0); 12086 } 12087 } 12088 return null; 12089 } 12090 12091 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12092 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12093 userId, andCode ? 1 : 0, packageName); 12094 if (mSystemReady) { 12095 msg.sendToTarget(); 12096 } else { 12097 if (mPostSystemReadyMessages == null) { 12098 mPostSystemReadyMessages = new ArrayList<>(); 12099 } 12100 mPostSystemReadyMessages.add(msg); 12101 } 12102 } 12103 12104 void startCleaningPackages() { 12105 // reader 12106 if (!isExternalMediaAvailable()) { 12107 return; 12108 } 12109 synchronized (mPackages) { 12110 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12111 return; 12112 } 12113 } 12114 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12115 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12116 IActivityManager am = ActivityManager.getService(); 12117 if (am != null) { 12118 try { 12119 am.startService(null, intent, null, mContext.getOpPackageName(), 12120 UserHandle.USER_SYSTEM); 12121 } catch (RemoteException e) { 12122 } 12123 } 12124 } 12125 12126 @Override 12127 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12128 int installFlags, String installerPackageName, int userId) { 12129 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12130 12131 final int callingUid = Binder.getCallingUid(); 12132 enforceCrossUserPermission(callingUid, userId, 12133 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12134 12135 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12136 try { 12137 if (observer != null) { 12138 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12139 } 12140 } catch (RemoteException re) { 12141 } 12142 return; 12143 } 12144 12145 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12146 installFlags |= PackageManager.INSTALL_FROM_ADB; 12147 12148 } else { 12149 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12150 // about installerPackageName. 12151 12152 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12153 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12154 } 12155 12156 UserHandle user; 12157 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12158 user = UserHandle.ALL; 12159 } else { 12160 user = new UserHandle(userId); 12161 } 12162 12163 // Only system components can circumvent runtime permissions when installing. 12164 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12165 && mContext.checkCallingOrSelfPermission(Manifest.permission 12166 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12167 throw new SecurityException("You need the " 12168 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12169 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12170 } 12171 12172 final File originFile = new File(originPath); 12173 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12174 12175 final Message msg = mHandler.obtainMessage(INIT_COPY); 12176 final VerificationInfo verificationInfo = new VerificationInfo( 12177 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12178 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12179 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12180 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12181 null /*certificates*/); 12182 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12183 msg.obj = params; 12184 12185 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 12186 System.identityHashCode(msg.obj)); 12187 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12188 System.identityHashCode(msg.obj)); 12189 12190 mHandler.sendMessage(msg); 12191 } 12192 12193 void installStage(String packageName, File stagedDir, String stagedCid, 12194 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 12195 String installerPackageName, int installerUid, UserHandle user, 12196 Certificate[][] certificates) { 12197 if (DEBUG_EPHEMERAL) { 12198 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12199 Slog.d(TAG, "Ephemeral install of " + packageName); 12200 } 12201 } 12202 final VerificationInfo verificationInfo = new VerificationInfo( 12203 sessionParams.originatingUri, sessionParams.referrerUri, 12204 sessionParams.originatingUid, installerUid); 12205 12206 final OriginInfo origin; 12207 if (stagedDir != null) { 12208 origin = OriginInfo.fromStagedFile(stagedDir); 12209 } else { 12210 origin = OriginInfo.fromStagedContainer(stagedCid); 12211 } 12212 12213 final Message msg = mHandler.obtainMessage(INIT_COPY); 12214 final InstallParams params = new InstallParams(origin, null, observer, 12215 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 12216 verificationInfo, user, sessionParams.abiOverride, 12217 sessionParams.grantedRuntimePermissions, certificates); 12218 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12219 msg.obj = params; 12220 12221 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12222 System.identityHashCode(msg.obj)); 12223 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12224 System.identityHashCode(msg.obj)); 12225 12226 mHandler.sendMessage(msg); 12227 } 12228 12229 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12230 int userId) { 12231 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12232 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12233 } 12234 12235 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12236 int appId, int... userIds) { 12237 if (ArrayUtils.isEmpty(userIds)) { 12238 return; 12239 } 12240 Bundle extras = new Bundle(1); 12241 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12242 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12243 12244 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12245 packageName, extras, 0, null, null, userIds); 12246 if (isSystem) { 12247 mHandler.post(() -> { 12248 for (int userId : userIds) { 12249 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12250 } 12251 } 12252 ); 12253 } 12254 } 12255 12256 /** 12257 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12258 * automatically without needing an explicit launch. 12259 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12260 */ 12261 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12262 // If user is not running, the app didn't miss any broadcast 12263 if (!mUserManagerInternal.isUserRunning(userId)) { 12264 return; 12265 } 12266 final IActivityManager am = ActivityManager.getService(); 12267 try { 12268 // Deliver LOCKED_BOOT_COMPLETED first 12269 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12270 .setPackage(packageName); 12271 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12272 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12273 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12274 12275 // Deliver BOOT_COMPLETED only if user is unlocked 12276 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12277 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12278 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12279 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12280 } 12281 } catch (RemoteException e) { 12282 throw e.rethrowFromSystemServer(); 12283 } 12284 } 12285 12286 @Override 12287 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12288 int userId) { 12289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12290 PackageSetting pkgSetting; 12291 final int uid = Binder.getCallingUid(); 12292 enforceCrossUserPermission(uid, userId, 12293 true /* requireFullPermission */, true /* checkShell */, 12294 "setApplicationHiddenSetting for user " + userId); 12295 12296 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12297 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12298 return false; 12299 } 12300 12301 long callingId = Binder.clearCallingIdentity(); 12302 try { 12303 boolean sendAdded = false; 12304 boolean sendRemoved = false; 12305 // writer 12306 synchronized (mPackages) { 12307 pkgSetting = mSettings.mPackages.get(packageName); 12308 if (pkgSetting == null) { 12309 return false; 12310 } 12311 // Do not allow "android" is being disabled 12312 if ("android".equals(packageName)) { 12313 Slog.w(TAG, "Cannot hide package: android"); 12314 return false; 12315 } 12316 // Only allow protected packages to hide themselves. 12317 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12318 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12319 Slog.w(TAG, "Not hiding protected package: " + packageName); 12320 return false; 12321 } 12322 12323 if (pkgSetting.getHidden(userId) != hidden) { 12324 pkgSetting.setHidden(hidden, userId); 12325 mSettings.writePackageRestrictionsLPr(userId); 12326 if (hidden) { 12327 sendRemoved = true; 12328 } else { 12329 sendAdded = true; 12330 } 12331 } 12332 } 12333 if (sendAdded) { 12334 sendPackageAddedForUser(packageName, pkgSetting, userId); 12335 return true; 12336 } 12337 if (sendRemoved) { 12338 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12339 "hiding pkg"); 12340 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12341 return true; 12342 } 12343 } finally { 12344 Binder.restoreCallingIdentity(callingId); 12345 } 12346 return false; 12347 } 12348 12349 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12350 int userId) { 12351 final PackageRemovedInfo info = new PackageRemovedInfo(); 12352 info.removedPackage = packageName; 12353 info.removedUsers = new int[] {userId}; 12354 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12355 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12356 } 12357 12358 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12359 if (pkgList.length > 0) { 12360 Bundle extras = new Bundle(1); 12361 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12362 12363 sendPackageBroadcast( 12364 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12365 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12366 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12367 new int[] {userId}); 12368 } 12369 } 12370 12371 /** 12372 * Returns true if application is not found or there was an error. Otherwise it returns 12373 * the hidden state of the package for the given user. 12374 */ 12375 @Override 12376 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12377 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12378 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12379 true /* requireFullPermission */, false /* checkShell */, 12380 "getApplicationHidden for user " + userId); 12381 PackageSetting pkgSetting; 12382 long callingId = Binder.clearCallingIdentity(); 12383 try { 12384 // writer 12385 synchronized (mPackages) { 12386 pkgSetting = mSettings.mPackages.get(packageName); 12387 if (pkgSetting == null) { 12388 return true; 12389 } 12390 return pkgSetting.getHidden(userId); 12391 } 12392 } finally { 12393 Binder.restoreCallingIdentity(callingId); 12394 } 12395 } 12396 12397 /** 12398 * @hide 12399 */ 12400 @Override 12401 public int installExistingPackageAsUser(String packageName, int userId) { 12402 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12403 null); 12404 PackageSetting pkgSetting; 12405 final int uid = Binder.getCallingUid(); 12406 enforceCrossUserPermission(uid, userId, 12407 true /* requireFullPermission */, true /* checkShell */, 12408 "installExistingPackage for user " + userId); 12409 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12410 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12411 } 12412 12413 long callingId = Binder.clearCallingIdentity(); 12414 try { 12415 boolean installed = false; 12416 12417 // writer 12418 synchronized (mPackages) { 12419 pkgSetting = mSettings.mPackages.get(packageName); 12420 if (pkgSetting == null) { 12421 return PackageManager.INSTALL_FAILED_INVALID_URI; 12422 } 12423 if (!pkgSetting.getInstalled(userId)) { 12424 pkgSetting.setInstalled(true, userId); 12425 pkgSetting.setHidden(false, userId); 12426 mSettings.writePackageRestrictionsLPr(userId); 12427 installed = true; 12428 } 12429 } 12430 12431 if (installed) { 12432 if (pkgSetting.pkg != null) { 12433 synchronized (mInstallLock) { 12434 // We don't need to freeze for a brand new install 12435 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12436 } 12437 } 12438 sendPackageAddedForUser(packageName, pkgSetting, userId); 12439 } 12440 } finally { 12441 Binder.restoreCallingIdentity(callingId); 12442 } 12443 12444 return PackageManager.INSTALL_SUCCEEDED; 12445 } 12446 12447 boolean isUserRestricted(int userId, String restrictionKey) { 12448 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12449 if (restrictions.getBoolean(restrictionKey, false)) { 12450 Log.w(TAG, "User is restricted: " + restrictionKey); 12451 return true; 12452 } 12453 return false; 12454 } 12455 12456 @Override 12457 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12458 int userId) { 12459 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12460 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12461 true /* requireFullPermission */, true /* checkShell */, 12462 "setPackagesSuspended for user " + userId); 12463 12464 if (ArrayUtils.isEmpty(packageNames)) { 12465 return packageNames; 12466 } 12467 12468 // List of package names for whom the suspended state has changed. 12469 List<String> changedPackages = new ArrayList<>(packageNames.length); 12470 // List of package names for whom the suspended state is not set as requested in this 12471 // method. 12472 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12473 long callingId = Binder.clearCallingIdentity(); 12474 try { 12475 for (int i = 0; i < packageNames.length; i++) { 12476 String packageName = packageNames[i]; 12477 boolean changed = false; 12478 final int appId; 12479 synchronized (mPackages) { 12480 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12481 if (pkgSetting == null) { 12482 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12483 + "\". Skipping suspending/un-suspending."); 12484 unactionedPackages.add(packageName); 12485 continue; 12486 } 12487 appId = pkgSetting.appId; 12488 if (pkgSetting.getSuspended(userId) != suspended) { 12489 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12490 unactionedPackages.add(packageName); 12491 continue; 12492 } 12493 pkgSetting.setSuspended(suspended, userId); 12494 mSettings.writePackageRestrictionsLPr(userId); 12495 changed = true; 12496 changedPackages.add(packageName); 12497 } 12498 } 12499 12500 if (changed && suspended) { 12501 killApplication(packageName, UserHandle.getUid(userId, appId), 12502 "suspending package"); 12503 } 12504 } 12505 } finally { 12506 Binder.restoreCallingIdentity(callingId); 12507 } 12508 12509 if (!changedPackages.isEmpty()) { 12510 sendPackagesSuspendedForUser(changedPackages.toArray( 12511 new String[changedPackages.size()]), userId, suspended); 12512 } 12513 12514 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12515 } 12516 12517 @Override 12518 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12519 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12520 true /* requireFullPermission */, false /* checkShell */, 12521 "isPackageSuspendedForUser for user " + userId); 12522 synchronized (mPackages) { 12523 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12524 if (pkgSetting == null) { 12525 throw new IllegalArgumentException("Unknown target package: " + packageName); 12526 } 12527 return pkgSetting.getSuspended(userId); 12528 } 12529 } 12530 12531 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12532 if (isPackageDeviceAdmin(packageName, userId)) { 12533 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12534 + "\": has an active device admin"); 12535 return false; 12536 } 12537 12538 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12539 if (packageName.equals(activeLauncherPackageName)) { 12540 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12541 + "\": contains the active launcher"); 12542 return false; 12543 } 12544 12545 if (packageName.equals(mRequiredInstallerPackage)) { 12546 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12547 + "\": required for package installation"); 12548 return false; 12549 } 12550 12551 if (packageName.equals(mRequiredUninstallerPackage)) { 12552 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12553 + "\": required for package uninstallation"); 12554 return false; 12555 } 12556 12557 if (packageName.equals(mRequiredVerifierPackage)) { 12558 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12559 + "\": required for package verification"); 12560 return false; 12561 } 12562 12563 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12564 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12565 + "\": is the default dialer"); 12566 return false; 12567 } 12568 12569 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12570 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12571 + "\": protected package"); 12572 return false; 12573 } 12574 12575 return true; 12576 } 12577 12578 private String getActiveLauncherPackageName(int userId) { 12579 Intent intent = new Intent(Intent.ACTION_MAIN); 12580 intent.addCategory(Intent.CATEGORY_HOME); 12581 ResolveInfo resolveInfo = resolveIntent( 12582 intent, 12583 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12584 PackageManager.MATCH_DEFAULT_ONLY, 12585 userId); 12586 12587 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12588 } 12589 12590 private String getDefaultDialerPackageName(int userId) { 12591 synchronized (mPackages) { 12592 return mSettings.getDefaultDialerPackageNameLPw(userId); 12593 } 12594 } 12595 12596 @Override 12597 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12598 mContext.enforceCallingOrSelfPermission( 12599 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12600 "Only package verification agents can verify applications"); 12601 12602 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12603 final PackageVerificationResponse response = new PackageVerificationResponse( 12604 verificationCode, Binder.getCallingUid()); 12605 msg.arg1 = id; 12606 msg.obj = response; 12607 mHandler.sendMessage(msg); 12608 } 12609 12610 @Override 12611 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12612 long millisecondsToDelay) { 12613 mContext.enforceCallingOrSelfPermission( 12614 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12615 "Only package verification agents can extend verification timeouts"); 12616 12617 final PackageVerificationState state = mPendingVerification.get(id); 12618 final PackageVerificationResponse response = new PackageVerificationResponse( 12619 verificationCodeAtTimeout, Binder.getCallingUid()); 12620 12621 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12622 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12623 } 12624 if (millisecondsToDelay < 0) { 12625 millisecondsToDelay = 0; 12626 } 12627 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12628 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12629 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12630 } 12631 12632 if ((state != null) && !state.timeoutExtended()) { 12633 state.extendTimeout(); 12634 12635 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12636 msg.arg1 = id; 12637 msg.obj = response; 12638 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12639 } 12640 } 12641 12642 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12643 int verificationCode, UserHandle user) { 12644 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12645 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12646 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12647 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12648 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12649 12650 mContext.sendBroadcastAsUser(intent, user, 12651 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12652 } 12653 12654 private ComponentName matchComponentForVerifier(String packageName, 12655 List<ResolveInfo> receivers) { 12656 ActivityInfo targetReceiver = null; 12657 12658 final int NR = receivers.size(); 12659 for (int i = 0; i < NR; i++) { 12660 final ResolveInfo info = receivers.get(i); 12661 if (info.activityInfo == null) { 12662 continue; 12663 } 12664 12665 if (packageName.equals(info.activityInfo.packageName)) { 12666 targetReceiver = info.activityInfo; 12667 break; 12668 } 12669 } 12670 12671 if (targetReceiver == null) { 12672 return null; 12673 } 12674 12675 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12676 } 12677 12678 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12679 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12680 if (pkgInfo.verifiers.length == 0) { 12681 return null; 12682 } 12683 12684 final int N = pkgInfo.verifiers.length; 12685 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12686 for (int i = 0; i < N; i++) { 12687 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12688 12689 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12690 receivers); 12691 if (comp == null) { 12692 continue; 12693 } 12694 12695 final int verifierUid = getUidForVerifier(verifierInfo); 12696 if (verifierUid == -1) { 12697 continue; 12698 } 12699 12700 if (DEBUG_VERIFY) { 12701 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12702 + " with the correct signature"); 12703 } 12704 sufficientVerifiers.add(comp); 12705 verificationState.addSufficientVerifier(verifierUid); 12706 } 12707 12708 return sufficientVerifiers; 12709 } 12710 12711 private int getUidForVerifier(VerifierInfo verifierInfo) { 12712 synchronized (mPackages) { 12713 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12714 if (pkg == null) { 12715 return -1; 12716 } else if (pkg.mSignatures.length != 1) { 12717 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12718 + " has more than one signature; ignoring"); 12719 return -1; 12720 } 12721 12722 /* 12723 * If the public key of the package's signature does not match 12724 * our expected public key, then this is a different package and 12725 * we should skip. 12726 */ 12727 12728 final byte[] expectedPublicKey; 12729 try { 12730 final Signature verifierSig = pkg.mSignatures[0]; 12731 final PublicKey publicKey = verifierSig.getPublicKey(); 12732 expectedPublicKey = publicKey.getEncoded(); 12733 } catch (CertificateException e) { 12734 return -1; 12735 } 12736 12737 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12738 12739 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12740 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12741 + " does not have the expected public key; ignoring"); 12742 return -1; 12743 } 12744 12745 return pkg.applicationInfo.uid; 12746 } 12747 } 12748 12749 @Override 12750 public void finishPackageInstall(int token, boolean didLaunch) { 12751 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12752 12753 if (DEBUG_INSTALL) { 12754 Slog.v(TAG, "BM finishing package install for " + token); 12755 } 12756 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12757 12758 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12759 mHandler.sendMessage(msg); 12760 } 12761 12762 /** 12763 * Get the verification agent timeout. 12764 * 12765 * @return verification timeout in milliseconds 12766 */ 12767 private long getVerificationTimeout() { 12768 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12769 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12770 DEFAULT_VERIFICATION_TIMEOUT); 12771 } 12772 12773 /** 12774 * Get the default verification agent response code. 12775 * 12776 * @return default verification response code 12777 */ 12778 private int getDefaultVerificationResponse() { 12779 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12780 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12781 DEFAULT_VERIFICATION_RESPONSE); 12782 } 12783 12784 /** 12785 * Check whether or not package verification has been enabled. 12786 * 12787 * @return true if verification should be performed 12788 */ 12789 private boolean isVerificationEnabled(int userId, int installFlags) { 12790 if (!DEFAULT_VERIFY_ENABLE) { 12791 return false; 12792 } 12793 // Ephemeral apps don't get the full verification treatment 12794 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12795 if (DEBUG_EPHEMERAL) { 12796 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12797 } 12798 return false; 12799 } 12800 12801 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12802 12803 // Check if installing from ADB 12804 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12805 // Do not run verification in a test harness environment 12806 if (ActivityManager.isRunningInTestHarness()) { 12807 return false; 12808 } 12809 if (ensureVerifyAppsEnabled) { 12810 return true; 12811 } 12812 // Check if the developer does not want package verification for ADB installs 12813 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12814 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12815 return false; 12816 } 12817 } 12818 12819 if (ensureVerifyAppsEnabled) { 12820 return true; 12821 } 12822 12823 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12824 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12825 } 12826 12827 @Override 12828 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12829 throws RemoteException { 12830 mContext.enforceCallingOrSelfPermission( 12831 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12832 "Only intentfilter verification agents can verify applications"); 12833 12834 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12835 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12836 Binder.getCallingUid(), verificationCode, failedDomains); 12837 msg.arg1 = id; 12838 msg.obj = response; 12839 mHandler.sendMessage(msg); 12840 } 12841 12842 @Override 12843 public int getIntentVerificationStatus(String packageName, int userId) { 12844 synchronized (mPackages) { 12845 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12846 } 12847 } 12848 12849 @Override 12850 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12851 mContext.enforceCallingOrSelfPermission( 12852 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12853 12854 boolean result = false; 12855 synchronized (mPackages) { 12856 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12857 } 12858 if (result) { 12859 scheduleWritePackageRestrictionsLocked(userId); 12860 } 12861 return result; 12862 } 12863 12864 @Override 12865 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12866 String packageName) { 12867 synchronized (mPackages) { 12868 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12869 } 12870 } 12871 12872 @Override 12873 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12874 if (TextUtils.isEmpty(packageName)) { 12875 return ParceledListSlice.emptyList(); 12876 } 12877 synchronized (mPackages) { 12878 PackageParser.Package pkg = mPackages.get(packageName); 12879 if (pkg == null || pkg.activities == null) { 12880 return ParceledListSlice.emptyList(); 12881 } 12882 final int count = pkg.activities.size(); 12883 ArrayList<IntentFilter> result = new ArrayList<>(); 12884 for (int n=0; n<count; n++) { 12885 PackageParser.Activity activity = pkg.activities.get(n); 12886 if (activity.intents != null && activity.intents.size() > 0) { 12887 result.addAll(activity.intents); 12888 } 12889 } 12890 return new ParceledListSlice<>(result); 12891 } 12892 } 12893 12894 @Override 12895 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12896 mContext.enforceCallingOrSelfPermission( 12897 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12898 12899 synchronized (mPackages) { 12900 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12901 if (packageName != null) { 12902 result |= updateIntentVerificationStatus(packageName, 12903 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12904 userId); 12905 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12906 packageName, userId); 12907 } 12908 return result; 12909 } 12910 } 12911 12912 @Override 12913 public String getDefaultBrowserPackageName(int userId) { 12914 synchronized (mPackages) { 12915 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12916 } 12917 } 12918 12919 /** 12920 * Get the "allow unknown sources" setting. 12921 * 12922 * @return the current "allow unknown sources" setting 12923 */ 12924 private int getUnknownSourcesSettings() { 12925 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12926 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12927 -1); 12928 } 12929 12930 @Override 12931 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12932 final int uid = Binder.getCallingUid(); 12933 // writer 12934 synchronized (mPackages) { 12935 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12936 if (targetPackageSetting == null) { 12937 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12938 } 12939 12940 PackageSetting installerPackageSetting; 12941 if (installerPackageName != null) { 12942 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12943 if (installerPackageSetting == null) { 12944 throw new IllegalArgumentException("Unknown installer package: " 12945 + installerPackageName); 12946 } 12947 } else { 12948 installerPackageSetting = null; 12949 } 12950 12951 Signature[] callerSignature; 12952 Object obj = mSettings.getUserIdLPr(uid); 12953 if (obj != null) { 12954 if (obj instanceof SharedUserSetting) { 12955 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12956 } else if (obj instanceof PackageSetting) { 12957 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12958 } else { 12959 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12960 } 12961 } else { 12962 throw new SecurityException("Unknown calling UID: " + uid); 12963 } 12964 12965 // Verify: can't set installerPackageName to a package that is 12966 // not signed with the same cert as the caller. 12967 if (installerPackageSetting != null) { 12968 if (compareSignatures(callerSignature, 12969 installerPackageSetting.signatures.mSignatures) 12970 != PackageManager.SIGNATURE_MATCH) { 12971 throw new SecurityException( 12972 "Caller does not have same cert as new installer package " 12973 + installerPackageName); 12974 } 12975 } 12976 12977 // Verify: if target already has an installer package, it must 12978 // be signed with the same cert as the caller. 12979 if (targetPackageSetting.installerPackageName != null) { 12980 PackageSetting setting = mSettings.mPackages.get( 12981 targetPackageSetting.installerPackageName); 12982 // If the currently set package isn't valid, then it's always 12983 // okay to change it. 12984 if (setting != null) { 12985 if (compareSignatures(callerSignature, 12986 setting.signatures.mSignatures) 12987 != PackageManager.SIGNATURE_MATCH) { 12988 throw new SecurityException( 12989 "Caller does not have same cert as old installer package " 12990 + targetPackageSetting.installerPackageName); 12991 } 12992 } 12993 } 12994 12995 // Okay! 12996 targetPackageSetting.installerPackageName = installerPackageName; 12997 if (installerPackageName != null) { 12998 mSettings.mInstallerPackages.add(installerPackageName); 12999 } 13000 scheduleWriteSettingsLocked(); 13001 } 13002 } 13003 13004 @Override 13005 public void setApplicationCategoryHint(String packageName, int categoryHint, 13006 String callerPackageName) { 13007 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13008 callerPackageName); 13009 synchronized (mPackages) { 13010 PackageSetting ps = mSettings.mPackages.get(packageName); 13011 if (ps == null) { 13012 throw new IllegalArgumentException("Unknown target package " + packageName); 13013 } 13014 13015 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13016 throw new IllegalArgumentException("Calling package " + callerPackageName 13017 + " is not installer for " + packageName); 13018 } 13019 13020 ps.categoryHint = categoryHint; 13021 scheduleWriteSettingsLocked(); 13022 } 13023 } 13024 13025 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13026 // Queue up an async operation since the package installation may take a little while. 13027 mHandler.post(new Runnable() { 13028 public void run() { 13029 mHandler.removeCallbacks(this); 13030 // Result object to be returned 13031 PackageInstalledInfo res = new PackageInstalledInfo(); 13032 res.setReturnCode(currentStatus); 13033 res.uid = -1; 13034 res.pkg = null; 13035 res.removedInfo = null; 13036 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13037 args.doPreInstall(res.returnCode); 13038 synchronized (mInstallLock) { 13039 installPackageTracedLI(args, res); 13040 } 13041 args.doPostInstall(res.returnCode, res.uid); 13042 } 13043 13044 // A restore should be performed at this point if (a) the install 13045 // succeeded, (b) the operation is not an update, and (c) the new 13046 // package has not opted out of backup participation. 13047 final boolean update = res.removedInfo != null 13048 && res.removedInfo.removedPackage != null; 13049 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13050 boolean doRestore = !update 13051 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13052 13053 // Set up the post-install work request bookkeeping. This will be used 13054 // and cleaned up by the post-install event handling regardless of whether 13055 // there's a restore pass performed. Token values are >= 1. 13056 int token; 13057 if (mNextInstallToken < 0) mNextInstallToken = 1; 13058 token = mNextInstallToken++; 13059 13060 PostInstallData data = new PostInstallData(args, res); 13061 mRunningInstalls.put(token, data); 13062 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13063 13064 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13065 // Pass responsibility to the Backup Manager. It will perform a 13066 // restore if appropriate, then pass responsibility back to the 13067 // Package Manager to run the post-install observer callbacks 13068 // and broadcasts. 13069 IBackupManager bm = IBackupManager.Stub.asInterface( 13070 ServiceManager.getService(Context.BACKUP_SERVICE)); 13071 if (bm != null) { 13072 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 13073 + " to BM for possible restore"); 13074 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13075 try { 13076 // TODO: http://b/22388012 13077 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 13078 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 13079 } else { 13080 doRestore = false; 13081 } 13082 } catch (RemoteException e) { 13083 // can't happen; the backup manager is local 13084 } catch (Exception e) { 13085 Slog.e(TAG, "Exception trying to enqueue restore", e); 13086 doRestore = false; 13087 } 13088 } else { 13089 Slog.e(TAG, "Backup Manager not found!"); 13090 doRestore = false; 13091 } 13092 } 13093 13094 if (!doRestore) { 13095 // No restore possible, or the Backup Manager was mysteriously not 13096 // available -- just fire the post-install work request directly. 13097 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 13098 13099 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 13100 13101 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 13102 mHandler.sendMessage(msg); 13103 } 13104 } 13105 }); 13106 } 13107 13108 /** 13109 * Callback from PackageSettings whenever an app is first transitioned out of the 13110 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 13111 * the app was "launched" for a restoreAtInstall operation. Therefore we check 13112 * here whether the app is the target of an ongoing install, and only send the 13113 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 13114 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 13115 * handling. 13116 */ 13117 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 13118 // Serialize this with the rest of the install-process message chain. In the 13119 // restore-at-install case, this Runnable will necessarily run before the 13120 // POST_INSTALL message is processed, so the contents of mRunningInstalls 13121 // are coherent. In the non-restore case, the app has already completed install 13122 // and been launched through some other means, so it is not in a problematic 13123 // state for observers to see the FIRST_LAUNCH signal. 13124 mHandler.post(new Runnable() { 13125 @Override 13126 public void run() { 13127 for (int i = 0; i < mRunningInstalls.size(); i++) { 13128 final PostInstallData data = mRunningInstalls.valueAt(i); 13129 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13130 continue; 13131 } 13132 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 13133 // right package; but is it for the right user? 13134 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 13135 if (userId == data.res.newUsers[uIndex]) { 13136 if (DEBUG_BACKUP) { 13137 Slog.i(TAG, "Package " + pkgName 13138 + " being restored so deferring FIRST_LAUNCH"); 13139 } 13140 return; 13141 } 13142 } 13143 } 13144 } 13145 // didn't find it, so not being restored 13146 if (DEBUG_BACKUP) { 13147 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 13148 } 13149 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 13150 } 13151 }); 13152 } 13153 13154 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 13155 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 13156 installerPkg, null, userIds); 13157 } 13158 13159 private abstract class HandlerParams { 13160 private static final int MAX_RETRIES = 4; 13161 13162 /** 13163 * Number of times startCopy() has been attempted and had a non-fatal 13164 * error. 13165 */ 13166 private int mRetries = 0; 13167 13168 /** User handle for the user requesting the information or installation. */ 13169 private final UserHandle mUser; 13170 String traceMethod; 13171 int traceCookie; 13172 13173 HandlerParams(UserHandle user) { 13174 mUser = user; 13175 } 13176 13177 UserHandle getUser() { 13178 return mUser; 13179 } 13180 13181 HandlerParams setTraceMethod(String traceMethod) { 13182 this.traceMethod = traceMethod; 13183 return this; 13184 } 13185 13186 HandlerParams setTraceCookie(int traceCookie) { 13187 this.traceCookie = traceCookie; 13188 return this; 13189 } 13190 13191 final boolean startCopy() { 13192 boolean res; 13193 try { 13194 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 13195 13196 if (++mRetries > MAX_RETRIES) { 13197 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 13198 mHandler.sendEmptyMessage(MCS_GIVE_UP); 13199 handleServiceError(); 13200 return false; 13201 } else { 13202 handleStartCopy(); 13203 res = true; 13204 } 13205 } catch (RemoteException e) { 13206 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 13207 mHandler.sendEmptyMessage(MCS_RECONNECT); 13208 res = false; 13209 } 13210 handleReturnCode(); 13211 return res; 13212 } 13213 13214 final void serviceError() { 13215 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 13216 handleServiceError(); 13217 handleReturnCode(); 13218 } 13219 13220 abstract void handleStartCopy() throws RemoteException; 13221 abstract void handleServiceError(); 13222 abstract void handleReturnCode(); 13223 } 13224 13225 class MeasureParams extends HandlerParams { 13226 private final PackageStats mStats; 13227 private boolean mSuccess; 13228 13229 private final IPackageStatsObserver mObserver; 13230 13231 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 13232 super(new UserHandle(stats.userHandle)); 13233 mObserver = observer; 13234 mStats = stats; 13235 } 13236 13237 @Override 13238 public String toString() { 13239 return "MeasureParams{" 13240 + Integer.toHexString(System.identityHashCode(this)) 13241 + " " + mStats.packageName + "}"; 13242 } 13243 13244 @Override 13245 void handleStartCopy() throws RemoteException { 13246 synchronized (mInstallLock) { 13247 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 13248 } 13249 13250 if (mSuccess) { 13251 boolean mounted = false; 13252 try { 13253 final String status = Environment.getExternalStorageState(); 13254 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13255 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13256 } catch (Exception e) { 13257 } 13258 13259 if (mounted) { 13260 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13261 13262 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13263 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13264 13265 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13266 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13267 13268 // Always subtract cache size, since it's a subdirectory 13269 mStats.externalDataSize -= mStats.externalCacheSize; 13270 13271 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13272 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13273 13274 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13275 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13276 } 13277 } 13278 } 13279 13280 @Override 13281 void handleReturnCode() { 13282 if (mObserver != null) { 13283 try { 13284 mObserver.onGetStatsCompleted(mStats, mSuccess); 13285 } catch (RemoteException e) { 13286 Slog.i(TAG, "Observer no longer exists."); 13287 } 13288 } 13289 } 13290 13291 @Override 13292 void handleServiceError() { 13293 Slog.e(TAG, "Could not measure application " + mStats.packageName 13294 + " external storage"); 13295 } 13296 } 13297 13298 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13299 throws RemoteException { 13300 long result = 0; 13301 for (File path : paths) { 13302 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13303 } 13304 return result; 13305 } 13306 13307 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13308 for (File path : paths) { 13309 try { 13310 mcs.clearDirectory(path.getAbsolutePath()); 13311 } catch (RemoteException e) { 13312 } 13313 } 13314 } 13315 13316 static class OriginInfo { 13317 /** 13318 * Location where install is coming from, before it has been 13319 * copied/renamed into place. This could be a single monolithic APK 13320 * file, or a cluster directory. This location may be untrusted. 13321 */ 13322 final File file; 13323 final String cid; 13324 13325 /** 13326 * Flag indicating that {@link #file} or {@link #cid} has already been 13327 * staged, meaning downstream users don't need to defensively copy the 13328 * contents. 13329 */ 13330 final boolean staged; 13331 13332 /** 13333 * Flag indicating that {@link #file} or {@link #cid} is an already 13334 * installed app that is being moved. 13335 */ 13336 final boolean existing; 13337 13338 final String resolvedPath; 13339 final File resolvedFile; 13340 13341 static OriginInfo fromNothing() { 13342 return new OriginInfo(null, null, false, false); 13343 } 13344 13345 static OriginInfo fromUntrustedFile(File file) { 13346 return new OriginInfo(file, null, false, false); 13347 } 13348 13349 static OriginInfo fromExistingFile(File file) { 13350 return new OriginInfo(file, null, false, true); 13351 } 13352 13353 static OriginInfo fromStagedFile(File file) { 13354 return new OriginInfo(file, null, true, false); 13355 } 13356 13357 static OriginInfo fromStagedContainer(String cid) { 13358 return new OriginInfo(null, cid, true, false); 13359 } 13360 13361 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13362 this.file = file; 13363 this.cid = cid; 13364 this.staged = staged; 13365 this.existing = existing; 13366 13367 if (cid != null) { 13368 resolvedPath = PackageHelper.getSdDir(cid); 13369 resolvedFile = new File(resolvedPath); 13370 } else if (file != null) { 13371 resolvedPath = file.getAbsolutePath(); 13372 resolvedFile = file; 13373 } else { 13374 resolvedPath = null; 13375 resolvedFile = null; 13376 } 13377 } 13378 } 13379 13380 static class MoveInfo { 13381 final int moveId; 13382 final String fromUuid; 13383 final String toUuid; 13384 final String packageName; 13385 final String dataAppName; 13386 final int appId; 13387 final String seinfo; 13388 final int targetSdkVersion; 13389 13390 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13391 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13392 this.moveId = moveId; 13393 this.fromUuid = fromUuid; 13394 this.toUuid = toUuid; 13395 this.packageName = packageName; 13396 this.dataAppName = dataAppName; 13397 this.appId = appId; 13398 this.seinfo = seinfo; 13399 this.targetSdkVersion = targetSdkVersion; 13400 } 13401 } 13402 13403 static class VerificationInfo { 13404 /** A constant used to indicate that a uid value is not present. */ 13405 public static final int NO_UID = -1; 13406 13407 /** URI referencing where the package was downloaded from. */ 13408 final Uri originatingUri; 13409 13410 /** HTTP referrer URI associated with the originatingURI. */ 13411 final Uri referrer; 13412 13413 /** UID of the application that the install request originated from. */ 13414 final int originatingUid; 13415 13416 /** UID of application requesting the install */ 13417 final int installerUid; 13418 13419 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13420 this.originatingUri = originatingUri; 13421 this.referrer = referrer; 13422 this.originatingUid = originatingUid; 13423 this.installerUid = installerUid; 13424 } 13425 } 13426 13427 class InstallParams extends HandlerParams { 13428 final OriginInfo origin; 13429 final MoveInfo move; 13430 final IPackageInstallObserver2 observer; 13431 int installFlags; 13432 final String installerPackageName; 13433 final String volumeUuid; 13434 private InstallArgs mArgs; 13435 private int mRet; 13436 final String packageAbiOverride; 13437 final String[] grantedRuntimePermissions; 13438 final VerificationInfo verificationInfo; 13439 final Certificate[][] certificates; 13440 13441 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13442 int installFlags, String installerPackageName, String volumeUuid, 13443 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13444 String[] grantedPermissions, Certificate[][] certificates) { 13445 super(user); 13446 this.origin = origin; 13447 this.move = move; 13448 this.observer = observer; 13449 this.installFlags = installFlags; 13450 this.installerPackageName = installerPackageName; 13451 this.volumeUuid = volumeUuid; 13452 this.verificationInfo = verificationInfo; 13453 this.packageAbiOverride = packageAbiOverride; 13454 this.grantedRuntimePermissions = grantedPermissions; 13455 this.certificates = certificates; 13456 } 13457 13458 @Override 13459 public String toString() { 13460 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13461 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13462 } 13463 13464 private int installLocationPolicy(PackageInfoLite pkgLite) { 13465 String packageName = pkgLite.packageName; 13466 int installLocation = pkgLite.installLocation; 13467 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13468 // reader 13469 synchronized (mPackages) { 13470 // Currently installed package which the new package is attempting to replace or 13471 // null if no such package is installed. 13472 PackageParser.Package installedPkg = mPackages.get(packageName); 13473 // Package which currently owns the data which the new package will own if installed. 13474 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13475 // will be null whereas dataOwnerPkg will contain information about the package 13476 // which was uninstalled while keeping its data. 13477 PackageParser.Package dataOwnerPkg = installedPkg; 13478 if (dataOwnerPkg == null) { 13479 PackageSetting ps = mSettings.mPackages.get(packageName); 13480 if (ps != null) { 13481 dataOwnerPkg = ps.pkg; 13482 } 13483 } 13484 13485 if (dataOwnerPkg != null) { 13486 // If installed, the package will get access to data left on the device by its 13487 // predecessor. As a security measure, this is permited only if this is not a 13488 // version downgrade or if the predecessor package is marked as debuggable and 13489 // a downgrade is explicitly requested. 13490 // 13491 // On debuggable platform builds, downgrades are permitted even for 13492 // non-debuggable packages to make testing easier. Debuggable platform builds do 13493 // not offer security guarantees and thus it's OK to disable some security 13494 // mechanisms to make debugging/testing easier on those builds. However, even on 13495 // debuggable builds downgrades of packages are permitted only if requested via 13496 // installFlags. This is because we aim to keep the behavior of debuggable 13497 // platform builds as close as possible to the behavior of non-debuggable 13498 // platform builds. 13499 final boolean downgradeRequested = 13500 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13501 final boolean packageDebuggable = 13502 (dataOwnerPkg.applicationInfo.flags 13503 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13504 final boolean downgradePermitted = 13505 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13506 if (!downgradePermitted) { 13507 try { 13508 checkDowngrade(dataOwnerPkg, pkgLite); 13509 } catch (PackageManagerException e) { 13510 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13511 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13512 } 13513 } 13514 } 13515 13516 if (installedPkg != null) { 13517 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13518 // Check for updated system application. 13519 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13520 if (onSd) { 13521 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13522 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13523 } 13524 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13525 } else { 13526 if (onSd) { 13527 // Install flag overrides everything. 13528 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13529 } 13530 // If current upgrade specifies particular preference 13531 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13532 // Application explicitly specified internal. 13533 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13534 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13535 // App explictly prefers external. Let policy decide 13536 } else { 13537 // Prefer previous location 13538 if (isExternal(installedPkg)) { 13539 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13540 } 13541 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13542 } 13543 } 13544 } else { 13545 // Invalid install. Return error code 13546 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13547 } 13548 } 13549 } 13550 // All the special cases have been taken care of. 13551 // Return result based on recommended install location. 13552 if (onSd) { 13553 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13554 } 13555 return pkgLite.recommendedInstallLocation; 13556 } 13557 13558 /* 13559 * Invoke remote method to get package information and install 13560 * location values. Override install location based on default 13561 * policy if needed and then create install arguments based 13562 * on the install location. 13563 */ 13564 public void handleStartCopy() throws RemoteException { 13565 int ret = PackageManager.INSTALL_SUCCEEDED; 13566 13567 // If we're already staged, we've firmly committed to an install location 13568 if (origin.staged) { 13569 if (origin.file != null) { 13570 installFlags |= PackageManager.INSTALL_INTERNAL; 13571 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13572 } else if (origin.cid != null) { 13573 installFlags |= PackageManager.INSTALL_EXTERNAL; 13574 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13575 } else { 13576 throw new IllegalStateException("Invalid stage location"); 13577 } 13578 } 13579 13580 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13581 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13582 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13583 PackageInfoLite pkgLite = null; 13584 13585 if (onInt && onSd) { 13586 // Check if both bits are set. 13587 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13588 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13589 } else if (onSd && ephemeral) { 13590 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13591 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13592 } else { 13593 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13594 packageAbiOverride); 13595 13596 if (DEBUG_EPHEMERAL && ephemeral) { 13597 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13598 } 13599 13600 /* 13601 * If we have too little free space, try to free cache 13602 * before giving up. 13603 */ 13604 if (!origin.staged && pkgLite.recommendedInstallLocation 13605 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13606 // TODO: focus freeing disk space on the target device 13607 final StorageManager storage = StorageManager.from(mContext); 13608 final long lowThreshold = storage.getStorageLowBytes( 13609 Environment.getDataDirectory()); 13610 13611 final long sizeBytes = mContainerService.calculateInstalledSize( 13612 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13613 13614 try { 13615 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13616 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13617 installFlags, packageAbiOverride); 13618 } catch (InstallerException e) { 13619 Slog.w(TAG, "Failed to free cache", e); 13620 } 13621 13622 /* 13623 * The cache free must have deleted the file we 13624 * downloaded to install. 13625 * 13626 * TODO: fix the "freeCache" call to not delete 13627 * the file we care about. 13628 */ 13629 if (pkgLite.recommendedInstallLocation 13630 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13631 pkgLite.recommendedInstallLocation 13632 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13633 } 13634 } 13635 } 13636 13637 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13638 int loc = pkgLite.recommendedInstallLocation; 13639 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13640 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13641 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13642 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13643 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13644 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13645 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13646 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13647 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13648 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13649 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13650 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13651 } else { 13652 // Override with defaults if needed. 13653 loc = installLocationPolicy(pkgLite); 13654 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13655 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13656 } else if (!onSd && !onInt) { 13657 // Override install location with flags 13658 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13659 // Set the flag to install on external media. 13660 installFlags |= PackageManager.INSTALL_EXTERNAL; 13661 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13662 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13663 if (DEBUG_EPHEMERAL) { 13664 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13665 } 13666 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13667 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13668 |PackageManager.INSTALL_INTERNAL); 13669 } else { 13670 // Make sure the flag for installing on external 13671 // media is unset 13672 installFlags |= PackageManager.INSTALL_INTERNAL; 13673 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13674 } 13675 } 13676 } 13677 } 13678 13679 final InstallArgs args = createInstallArgs(this); 13680 mArgs = args; 13681 13682 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13683 // TODO: http://b/22976637 13684 // Apps installed for "all" users use the device owner to verify the app 13685 UserHandle verifierUser = getUser(); 13686 if (verifierUser == UserHandle.ALL) { 13687 verifierUser = UserHandle.SYSTEM; 13688 } 13689 13690 /* 13691 * Determine if we have any installed package verifiers. If we 13692 * do, then we'll defer to them to verify the packages. 13693 */ 13694 final int requiredUid = mRequiredVerifierPackage == null ? -1 13695 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13696 verifierUser.getIdentifier()); 13697 if (!origin.existing && requiredUid != -1 13698 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13699 final Intent verification = new Intent( 13700 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13701 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13702 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13703 PACKAGE_MIME_TYPE); 13704 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13705 13706 // Query all live verifiers based on current user state 13707 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13708 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13709 13710 if (DEBUG_VERIFY) { 13711 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13712 + verification.toString() + " with " + pkgLite.verifiers.length 13713 + " optional verifiers"); 13714 } 13715 13716 final int verificationId = mPendingVerificationToken++; 13717 13718 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13719 13720 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13721 installerPackageName); 13722 13723 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13724 installFlags); 13725 13726 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13727 pkgLite.packageName); 13728 13729 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13730 pkgLite.versionCode); 13731 13732 if (verificationInfo != null) { 13733 if (verificationInfo.originatingUri != null) { 13734 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13735 verificationInfo.originatingUri); 13736 } 13737 if (verificationInfo.referrer != null) { 13738 verification.putExtra(Intent.EXTRA_REFERRER, 13739 verificationInfo.referrer); 13740 } 13741 if (verificationInfo.originatingUid >= 0) { 13742 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13743 verificationInfo.originatingUid); 13744 } 13745 if (verificationInfo.installerUid >= 0) { 13746 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13747 verificationInfo.installerUid); 13748 } 13749 } 13750 13751 final PackageVerificationState verificationState = new PackageVerificationState( 13752 requiredUid, args); 13753 13754 mPendingVerification.append(verificationId, verificationState); 13755 13756 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13757 receivers, verificationState); 13758 13759 /* 13760 * If any sufficient verifiers were listed in the package 13761 * manifest, attempt to ask them. 13762 */ 13763 if (sufficientVerifiers != null) { 13764 final int N = sufficientVerifiers.size(); 13765 if (N == 0) { 13766 Slog.i(TAG, "Additional verifiers required, but none installed."); 13767 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13768 } else { 13769 for (int i = 0; i < N; i++) { 13770 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13771 13772 final Intent sufficientIntent = new Intent(verification); 13773 sufficientIntent.setComponent(verifierComponent); 13774 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13775 } 13776 } 13777 } 13778 13779 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13780 mRequiredVerifierPackage, receivers); 13781 if (ret == PackageManager.INSTALL_SUCCEEDED 13782 && mRequiredVerifierPackage != null) { 13783 Trace.asyncTraceBegin( 13784 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13785 /* 13786 * Send the intent to the required verification agent, 13787 * but only start the verification timeout after the 13788 * target BroadcastReceivers have run. 13789 */ 13790 verification.setComponent(requiredVerifierComponent); 13791 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13792 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13793 new BroadcastReceiver() { 13794 @Override 13795 public void onReceive(Context context, Intent intent) { 13796 final Message msg = mHandler 13797 .obtainMessage(CHECK_PENDING_VERIFICATION); 13798 msg.arg1 = verificationId; 13799 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13800 } 13801 }, null, 0, null, null); 13802 13803 /* 13804 * We don't want the copy to proceed until verification 13805 * succeeds, so null out this field. 13806 */ 13807 mArgs = null; 13808 } 13809 } else { 13810 /* 13811 * No package verification is enabled, so immediately start 13812 * the remote call to initiate copy using temporary file. 13813 */ 13814 ret = args.copyApk(mContainerService, true); 13815 } 13816 } 13817 13818 mRet = ret; 13819 } 13820 13821 @Override 13822 void handleReturnCode() { 13823 // If mArgs is null, then MCS couldn't be reached. When it 13824 // reconnects, it will try again to install. At that point, this 13825 // will succeed. 13826 if (mArgs != null) { 13827 processPendingInstall(mArgs, mRet); 13828 } 13829 } 13830 13831 @Override 13832 void handleServiceError() { 13833 mArgs = createInstallArgs(this); 13834 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13835 } 13836 13837 public boolean isForwardLocked() { 13838 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13839 } 13840 } 13841 13842 /** 13843 * Used during creation of InstallArgs 13844 * 13845 * @param installFlags package installation flags 13846 * @return true if should be installed on external storage 13847 */ 13848 private static boolean installOnExternalAsec(int installFlags) { 13849 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13850 return false; 13851 } 13852 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13853 return true; 13854 } 13855 return false; 13856 } 13857 13858 /** 13859 * Used during creation of InstallArgs 13860 * 13861 * @param installFlags package installation flags 13862 * @return true if should be installed as forward locked 13863 */ 13864 private static boolean installForwardLocked(int installFlags) { 13865 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13866 } 13867 13868 private InstallArgs createInstallArgs(InstallParams params) { 13869 if (params.move != null) { 13870 return new MoveInstallArgs(params); 13871 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13872 return new AsecInstallArgs(params); 13873 } else { 13874 return new FileInstallArgs(params); 13875 } 13876 } 13877 13878 /** 13879 * Create args that describe an existing installed package. Typically used 13880 * when cleaning up old installs, or used as a move source. 13881 */ 13882 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13883 String resourcePath, String[] instructionSets) { 13884 final boolean isInAsec; 13885 if (installOnExternalAsec(installFlags)) { 13886 /* Apps on SD card are always in ASEC containers. */ 13887 isInAsec = true; 13888 } else if (installForwardLocked(installFlags) 13889 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13890 /* 13891 * Forward-locked apps are only in ASEC containers if they're the 13892 * new style 13893 */ 13894 isInAsec = true; 13895 } else { 13896 isInAsec = false; 13897 } 13898 13899 if (isInAsec) { 13900 return new AsecInstallArgs(codePath, instructionSets, 13901 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13902 } else { 13903 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13904 } 13905 } 13906 13907 static abstract class InstallArgs { 13908 /** @see InstallParams#origin */ 13909 final OriginInfo origin; 13910 /** @see InstallParams#move */ 13911 final MoveInfo move; 13912 13913 final IPackageInstallObserver2 observer; 13914 // Always refers to PackageManager flags only 13915 final int installFlags; 13916 final String installerPackageName; 13917 final String volumeUuid; 13918 final UserHandle user; 13919 final String abiOverride; 13920 final String[] installGrantPermissions; 13921 /** If non-null, drop an async trace when the install completes */ 13922 final String traceMethod; 13923 final int traceCookie; 13924 final Certificate[][] certificates; 13925 13926 // The list of instruction sets supported by this app. This is currently 13927 // only used during the rmdex() phase to clean up resources. We can get rid of this 13928 // if we move dex files under the common app path. 13929 /* nullable */ String[] instructionSets; 13930 13931 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13932 int installFlags, String installerPackageName, String volumeUuid, 13933 UserHandle user, String[] instructionSets, 13934 String abiOverride, String[] installGrantPermissions, 13935 String traceMethod, int traceCookie, Certificate[][] certificates) { 13936 this.origin = origin; 13937 this.move = move; 13938 this.installFlags = installFlags; 13939 this.observer = observer; 13940 this.installerPackageName = installerPackageName; 13941 this.volumeUuid = volumeUuid; 13942 this.user = user; 13943 this.instructionSets = instructionSets; 13944 this.abiOverride = abiOverride; 13945 this.installGrantPermissions = installGrantPermissions; 13946 this.traceMethod = traceMethod; 13947 this.traceCookie = traceCookie; 13948 this.certificates = certificates; 13949 } 13950 13951 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13952 abstract int doPreInstall(int status); 13953 13954 /** 13955 * Rename package into final resting place. All paths on the given 13956 * scanned package should be updated to reflect the rename. 13957 */ 13958 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13959 abstract int doPostInstall(int status, int uid); 13960 13961 /** @see PackageSettingBase#codePathString */ 13962 abstract String getCodePath(); 13963 /** @see PackageSettingBase#resourcePathString */ 13964 abstract String getResourcePath(); 13965 13966 // Need installer lock especially for dex file removal. 13967 abstract void cleanUpResourcesLI(); 13968 abstract boolean doPostDeleteLI(boolean delete); 13969 13970 /** 13971 * Called before the source arguments are copied. This is used mostly 13972 * for MoveParams when it needs to read the source file to put it in the 13973 * destination. 13974 */ 13975 int doPreCopy() { 13976 return PackageManager.INSTALL_SUCCEEDED; 13977 } 13978 13979 /** 13980 * Called after the source arguments are copied. This is used mostly for 13981 * MoveParams when it needs to read the source file to put it in the 13982 * destination. 13983 */ 13984 int doPostCopy(int uid) { 13985 return PackageManager.INSTALL_SUCCEEDED; 13986 } 13987 13988 protected boolean isFwdLocked() { 13989 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13990 } 13991 13992 protected boolean isExternalAsec() { 13993 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13994 } 13995 13996 protected boolean isEphemeral() { 13997 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13998 } 13999 14000 UserHandle getUser() { 14001 return user; 14002 } 14003 } 14004 14005 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14006 if (!allCodePaths.isEmpty()) { 14007 if (instructionSets == null) { 14008 throw new IllegalStateException("instructionSet == null"); 14009 } 14010 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14011 for (String codePath : allCodePaths) { 14012 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14013 try { 14014 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14015 } catch (InstallerException ignored) { 14016 } 14017 } 14018 } 14019 } 14020 } 14021 14022 /** 14023 * Logic to handle installation of non-ASEC applications, including copying 14024 * and renaming logic. 14025 */ 14026 class FileInstallArgs extends InstallArgs { 14027 private File codeFile; 14028 private File resourceFile; 14029 14030 // Example topology: 14031 // /data/app/com.example/base.apk 14032 // /data/app/com.example/split_foo.apk 14033 // /data/app/com.example/lib/arm/libfoo.so 14034 // /data/app/com.example/lib/arm64/libfoo.so 14035 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14036 14037 /** New install */ 14038 FileInstallArgs(InstallParams params) { 14039 super(params.origin, params.move, params.observer, params.installFlags, 14040 params.installerPackageName, params.volumeUuid, 14041 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14042 params.grantedRuntimePermissions, 14043 params.traceMethod, params.traceCookie, params.certificates); 14044 if (isFwdLocked()) { 14045 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14046 } 14047 } 14048 14049 /** Existing install */ 14050 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14051 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14052 null, null, null, 0, null /*certificates*/); 14053 this.codeFile = (codePath != null) ? new File(codePath) : null; 14054 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14055 } 14056 14057 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14058 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14059 try { 14060 return doCopyApk(imcs, temp); 14061 } finally { 14062 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14063 } 14064 } 14065 14066 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14067 if (origin.staged) { 14068 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14069 codeFile = origin.file; 14070 resourceFile = origin.file; 14071 return PackageManager.INSTALL_SUCCEEDED; 14072 } 14073 14074 try { 14075 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 14076 final File tempDir = 14077 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14078 codeFile = tempDir; 14079 resourceFile = tempDir; 14080 } catch (IOException e) { 14081 Slog.w(TAG, "Failed to create copy file: " + e); 14082 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14083 } 14084 14085 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14086 @Override 14087 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14088 if (!FileUtils.isValidExtFilename(name)) { 14089 throw new IllegalArgumentException("Invalid filename: " + name); 14090 } 14091 try { 14092 final File file = new File(codeFile, name); 14093 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14094 O_RDWR | O_CREAT, 0644); 14095 Os.chmod(file.getAbsolutePath(), 0644); 14096 return new ParcelFileDescriptor(fd); 14097 } catch (ErrnoException e) { 14098 throw new RemoteException("Failed to open: " + e.getMessage()); 14099 } 14100 } 14101 }; 14102 14103 int ret = PackageManager.INSTALL_SUCCEEDED; 14104 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14105 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14106 Slog.e(TAG, "Failed to copy package"); 14107 return ret; 14108 } 14109 14110 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14111 NativeLibraryHelper.Handle handle = null; 14112 try { 14113 handle = NativeLibraryHelper.Handle.create(codeFile); 14114 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14115 abiOverride); 14116 } catch (IOException e) { 14117 Slog.e(TAG, "Copying native libraries failed", e); 14118 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14119 } finally { 14120 IoUtils.closeQuietly(handle); 14121 } 14122 14123 return ret; 14124 } 14125 14126 int doPreInstall(int status) { 14127 if (status != PackageManager.INSTALL_SUCCEEDED) { 14128 cleanUp(); 14129 } 14130 return status; 14131 } 14132 14133 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14134 if (status != PackageManager.INSTALL_SUCCEEDED) { 14135 cleanUp(); 14136 return false; 14137 } 14138 14139 final File targetDir = codeFile.getParentFile(); 14140 final File beforeCodeFile = codeFile; 14141 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 14142 14143 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 14144 try { 14145 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 14146 } catch (ErrnoException e) { 14147 Slog.w(TAG, "Failed to rename", e); 14148 return false; 14149 } 14150 14151 if (!SELinux.restoreconRecursive(afterCodeFile)) { 14152 Slog.w(TAG, "Failed to restorecon"); 14153 return false; 14154 } 14155 14156 // Reflect the rename internally 14157 codeFile = afterCodeFile; 14158 resourceFile = afterCodeFile; 14159 14160 // Reflect the rename in scanned details 14161 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14162 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14163 afterCodeFile, pkg.baseCodePath)); 14164 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14165 afterCodeFile, pkg.splitCodePaths)); 14166 14167 // Reflect the rename in app info 14168 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14169 pkg.setApplicationInfoCodePath(pkg.codePath); 14170 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14171 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14172 pkg.setApplicationInfoResourcePath(pkg.codePath); 14173 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14174 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14175 14176 return true; 14177 } 14178 14179 int doPostInstall(int status, int uid) { 14180 if (status != PackageManager.INSTALL_SUCCEEDED) { 14181 cleanUp(); 14182 } 14183 return status; 14184 } 14185 14186 @Override 14187 String getCodePath() { 14188 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14189 } 14190 14191 @Override 14192 String getResourcePath() { 14193 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14194 } 14195 14196 private boolean cleanUp() { 14197 if (codeFile == null || !codeFile.exists()) { 14198 return false; 14199 } 14200 14201 removeCodePathLI(codeFile); 14202 14203 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 14204 resourceFile.delete(); 14205 } 14206 14207 return true; 14208 } 14209 14210 void cleanUpResourcesLI() { 14211 // Try enumerating all code paths before deleting 14212 List<String> allCodePaths = Collections.EMPTY_LIST; 14213 if (codeFile != null && codeFile.exists()) { 14214 try { 14215 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14216 allCodePaths = pkg.getAllCodePaths(); 14217 } catch (PackageParserException e) { 14218 // Ignored; we tried our best 14219 } 14220 } 14221 14222 cleanUp(); 14223 removeDexFiles(allCodePaths, instructionSets); 14224 } 14225 14226 boolean doPostDeleteLI(boolean delete) { 14227 // XXX err, shouldn't we respect the delete flag? 14228 cleanUpResourcesLI(); 14229 return true; 14230 } 14231 } 14232 14233 private boolean isAsecExternal(String cid) { 14234 final String asecPath = PackageHelper.getSdFilesystem(cid); 14235 return !asecPath.startsWith(mAsecInternalPath); 14236 } 14237 14238 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 14239 PackageManagerException { 14240 if (copyRet < 0) { 14241 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 14242 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 14243 throw new PackageManagerException(copyRet, message); 14244 } 14245 } 14246 } 14247 14248 /** 14249 * Extract the StorageManagerService "container ID" from the full code path of an 14250 * .apk. 14251 */ 14252 static String cidFromCodePath(String fullCodePath) { 14253 int eidx = fullCodePath.lastIndexOf("/"); 14254 String subStr1 = fullCodePath.substring(0, eidx); 14255 int sidx = subStr1.lastIndexOf("/"); 14256 return subStr1.substring(sidx+1, eidx); 14257 } 14258 14259 /** 14260 * Logic to handle installation of ASEC applications, including copying and 14261 * renaming logic. 14262 */ 14263 class AsecInstallArgs extends InstallArgs { 14264 static final String RES_FILE_NAME = "pkg.apk"; 14265 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14266 14267 String cid; 14268 String packagePath; 14269 String resourcePath; 14270 14271 /** New install */ 14272 AsecInstallArgs(InstallParams params) { 14273 super(params.origin, params.move, params.observer, params.installFlags, 14274 params.installerPackageName, params.volumeUuid, 14275 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14276 params.grantedRuntimePermissions, 14277 params.traceMethod, params.traceCookie, params.certificates); 14278 } 14279 14280 /** Existing install */ 14281 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14282 boolean isExternal, boolean isForwardLocked) { 14283 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14284 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14285 instructionSets, null, null, null, 0, null /*certificates*/); 14286 // Hackily pretend we're still looking at a full code path 14287 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14288 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14289 } 14290 14291 // Extract cid from fullCodePath 14292 int eidx = fullCodePath.lastIndexOf("/"); 14293 String subStr1 = fullCodePath.substring(0, eidx); 14294 int sidx = subStr1.lastIndexOf("/"); 14295 cid = subStr1.substring(sidx+1, eidx); 14296 setMountPath(subStr1); 14297 } 14298 14299 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14300 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14301 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14302 instructionSets, null, null, null, 0, null /*certificates*/); 14303 this.cid = cid; 14304 setMountPath(PackageHelper.getSdDir(cid)); 14305 } 14306 14307 void createCopyFile() { 14308 cid = mInstallerService.allocateExternalStageCidLegacy(); 14309 } 14310 14311 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14312 if (origin.staged && origin.cid != null) { 14313 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14314 cid = origin.cid; 14315 setMountPath(PackageHelper.getSdDir(cid)); 14316 return PackageManager.INSTALL_SUCCEEDED; 14317 } 14318 14319 if (temp) { 14320 createCopyFile(); 14321 } else { 14322 /* 14323 * Pre-emptively destroy the container since it's destroyed if 14324 * copying fails due to it existing anyway. 14325 */ 14326 PackageHelper.destroySdDir(cid); 14327 } 14328 14329 final String newMountPath = imcs.copyPackageToContainer( 14330 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14331 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14332 14333 if (newMountPath != null) { 14334 setMountPath(newMountPath); 14335 return PackageManager.INSTALL_SUCCEEDED; 14336 } else { 14337 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14338 } 14339 } 14340 14341 @Override 14342 String getCodePath() { 14343 return packagePath; 14344 } 14345 14346 @Override 14347 String getResourcePath() { 14348 return resourcePath; 14349 } 14350 14351 int doPreInstall(int status) { 14352 if (status != PackageManager.INSTALL_SUCCEEDED) { 14353 // Destroy container 14354 PackageHelper.destroySdDir(cid); 14355 } else { 14356 boolean mounted = PackageHelper.isContainerMounted(cid); 14357 if (!mounted) { 14358 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14359 Process.SYSTEM_UID); 14360 if (newMountPath != null) { 14361 setMountPath(newMountPath); 14362 } else { 14363 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14364 } 14365 } 14366 } 14367 return status; 14368 } 14369 14370 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14371 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14372 String newMountPath = null; 14373 if (PackageHelper.isContainerMounted(cid)) { 14374 // Unmount the container 14375 if (!PackageHelper.unMountSdDir(cid)) { 14376 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14377 return false; 14378 } 14379 } 14380 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14381 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14382 " which might be stale. Will try to clean up."); 14383 // Clean up the stale container and proceed to recreate. 14384 if (!PackageHelper.destroySdDir(newCacheId)) { 14385 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14386 return false; 14387 } 14388 // Successfully cleaned up stale container. Try to rename again. 14389 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14390 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14391 + " inspite of cleaning it up."); 14392 return false; 14393 } 14394 } 14395 if (!PackageHelper.isContainerMounted(newCacheId)) { 14396 Slog.w(TAG, "Mounting container " + newCacheId); 14397 newMountPath = PackageHelper.mountSdDir(newCacheId, 14398 getEncryptKey(), Process.SYSTEM_UID); 14399 } else { 14400 newMountPath = PackageHelper.getSdDir(newCacheId); 14401 } 14402 if (newMountPath == null) { 14403 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14404 return false; 14405 } 14406 Log.i(TAG, "Succesfully renamed " + cid + 14407 " to " + newCacheId + 14408 " at new path: " + newMountPath); 14409 cid = newCacheId; 14410 14411 final File beforeCodeFile = new File(packagePath); 14412 setMountPath(newMountPath); 14413 final File afterCodeFile = new File(packagePath); 14414 14415 // Reflect the rename in scanned details 14416 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14417 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14418 afterCodeFile, pkg.baseCodePath)); 14419 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14420 afterCodeFile, pkg.splitCodePaths)); 14421 14422 // Reflect the rename in app info 14423 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14424 pkg.setApplicationInfoCodePath(pkg.codePath); 14425 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14426 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14427 pkg.setApplicationInfoResourcePath(pkg.codePath); 14428 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14429 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14430 14431 return true; 14432 } 14433 14434 private void setMountPath(String mountPath) { 14435 final File mountFile = new File(mountPath); 14436 14437 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14438 if (monolithicFile.exists()) { 14439 packagePath = monolithicFile.getAbsolutePath(); 14440 if (isFwdLocked()) { 14441 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14442 } else { 14443 resourcePath = packagePath; 14444 } 14445 } else { 14446 packagePath = mountFile.getAbsolutePath(); 14447 resourcePath = packagePath; 14448 } 14449 } 14450 14451 int doPostInstall(int status, int uid) { 14452 if (status != PackageManager.INSTALL_SUCCEEDED) { 14453 cleanUp(); 14454 } else { 14455 final int groupOwner; 14456 final String protectedFile; 14457 if (isFwdLocked()) { 14458 groupOwner = UserHandle.getSharedAppGid(uid); 14459 protectedFile = RES_FILE_NAME; 14460 } else { 14461 groupOwner = -1; 14462 protectedFile = null; 14463 } 14464 14465 if (uid < Process.FIRST_APPLICATION_UID 14466 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14467 Slog.e(TAG, "Failed to finalize " + cid); 14468 PackageHelper.destroySdDir(cid); 14469 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14470 } 14471 14472 boolean mounted = PackageHelper.isContainerMounted(cid); 14473 if (!mounted) { 14474 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14475 } 14476 } 14477 return status; 14478 } 14479 14480 private void cleanUp() { 14481 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14482 14483 // Destroy secure container 14484 PackageHelper.destroySdDir(cid); 14485 } 14486 14487 private List<String> getAllCodePaths() { 14488 final File codeFile = new File(getCodePath()); 14489 if (codeFile != null && codeFile.exists()) { 14490 try { 14491 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14492 return pkg.getAllCodePaths(); 14493 } catch (PackageParserException e) { 14494 // Ignored; we tried our best 14495 } 14496 } 14497 return Collections.EMPTY_LIST; 14498 } 14499 14500 void cleanUpResourcesLI() { 14501 // Enumerate all code paths before deleting 14502 cleanUpResourcesLI(getAllCodePaths()); 14503 } 14504 14505 private void cleanUpResourcesLI(List<String> allCodePaths) { 14506 cleanUp(); 14507 removeDexFiles(allCodePaths, instructionSets); 14508 } 14509 14510 String getPackageName() { 14511 return getAsecPackageName(cid); 14512 } 14513 14514 boolean doPostDeleteLI(boolean delete) { 14515 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14516 final List<String> allCodePaths = getAllCodePaths(); 14517 boolean mounted = PackageHelper.isContainerMounted(cid); 14518 if (mounted) { 14519 // Unmount first 14520 if (PackageHelper.unMountSdDir(cid)) { 14521 mounted = false; 14522 } 14523 } 14524 if (!mounted && delete) { 14525 cleanUpResourcesLI(allCodePaths); 14526 } 14527 return !mounted; 14528 } 14529 14530 @Override 14531 int doPreCopy() { 14532 if (isFwdLocked()) { 14533 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14534 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14535 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14536 } 14537 } 14538 14539 return PackageManager.INSTALL_SUCCEEDED; 14540 } 14541 14542 @Override 14543 int doPostCopy(int uid) { 14544 if (isFwdLocked()) { 14545 if (uid < Process.FIRST_APPLICATION_UID 14546 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14547 RES_FILE_NAME)) { 14548 Slog.e(TAG, "Failed to finalize " + cid); 14549 PackageHelper.destroySdDir(cid); 14550 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14551 } 14552 } 14553 14554 return PackageManager.INSTALL_SUCCEEDED; 14555 } 14556 } 14557 14558 /** 14559 * Logic to handle movement of existing installed applications. 14560 */ 14561 class MoveInstallArgs extends InstallArgs { 14562 private File codeFile; 14563 private File resourceFile; 14564 14565 /** New install */ 14566 MoveInstallArgs(InstallParams params) { 14567 super(params.origin, params.move, params.observer, params.installFlags, 14568 params.installerPackageName, params.volumeUuid, 14569 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14570 params.grantedRuntimePermissions, 14571 params.traceMethod, params.traceCookie, params.certificates); 14572 } 14573 14574 int copyApk(IMediaContainerService imcs, boolean temp) { 14575 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14576 + move.fromUuid + " to " + move.toUuid); 14577 synchronized (mInstaller) { 14578 try { 14579 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14580 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14581 } catch (InstallerException e) { 14582 Slog.w(TAG, "Failed to move app", e); 14583 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14584 } 14585 } 14586 14587 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14588 resourceFile = codeFile; 14589 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14590 14591 return PackageManager.INSTALL_SUCCEEDED; 14592 } 14593 14594 int doPreInstall(int status) { 14595 if (status != PackageManager.INSTALL_SUCCEEDED) { 14596 cleanUp(move.toUuid); 14597 } 14598 return status; 14599 } 14600 14601 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14602 if (status != PackageManager.INSTALL_SUCCEEDED) { 14603 cleanUp(move.toUuid); 14604 return false; 14605 } 14606 14607 // Reflect the move in app info 14608 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14609 pkg.setApplicationInfoCodePath(pkg.codePath); 14610 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14611 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14612 pkg.setApplicationInfoResourcePath(pkg.codePath); 14613 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14614 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14615 14616 return true; 14617 } 14618 14619 int doPostInstall(int status, int uid) { 14620 if (status == PackageManager.INSTALL_SUCCEEDED) { 14621 cleanUp(move.fromUuid); 14622 } else { 14623 cleanUp(move.toUuid); 14624 } 14625 return status; 14626 } 14627 14628 @Override 14629 String getCodePath() { 14630 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14631 } 14632 14633 @Override 14634 String getResourcePath() { 14635 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14636 } 14637 14638 private boolean cleanUp(String volumeUuid) { 14639 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14640 move.dataAppName); 14641 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14642 final int[] userIds = sUserManager.getUserIds(); 14643 synchronized (mInstallLock) { 14644 // Clean up both app data and code 14645 // All package moves are frozen until finished 14646 for (int userId : userIds) { 14647 try { 14648 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14649 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14650 } catch (InstallerException e) { 14651 Slog.w(TAG, String.valueOf(e)); 14652 } 14653 } 14654 removeCodePathLI(codeFile); 14655 } 14656 return true; 14657 } 14658 14659 void cleanUpResourcesLI() { 14660 throw new UnsupportedOperationException(); 14661 } 14662 14663 boolean doPostDeleteLI(boolean delete) { 14664 throw new UnsupportedOperationException(); 14665 } 14666 } 14667 14668 static String getAsecPackageName(String packageCid) { 14669 int idx = packageCid.lastIndexOf("-"); 14670 if (idx == -1) { 14671 return packageCid; 14672 } 14673 return packageCid.substring(0, idx); 14674 } 14675 14676 // Utility method used to create code paths based on package name and available index. 14677 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14678 String idxStr = ""; 14679 int idx = 1; 14680 // Fall back to default value of idx=1 if prefix is not 14681 // part of oldCodePath 14682 if (oldCodePath != null) { 14683 String subStr = oldCodePath; 14684 // Drop the suffix right away 14685 if (suffix != null && subStr.endsWith(suffix)) { 14686 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14687 } 14688 // If oldCodePath already contains prefix find out the 14689 // ending index to either increment or decrement. 14690 int sidx = subStr.lastIndexOf(prefix); 14691 if (sidx != -1) { 14692 subStr = subStr.substring(sidx + prefix.length()); 14693 if (subStr != null) { 14694 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14695 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14696 } 14697 try { 14698 idx = Integer.parseInt(subStr); 14699 if (idx <= 1) { 14700 idx++; 14701 } else { 14702 idx--; 14703 } 14704 } catch(NumberFormatException e) { 14705 } 14706 } 14707 } 14708 } 14709 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14710 return prefix + idxStr; 14711 } 14712 14713 private File getNextCodePath(File targetDir, String packageName) { 14714 File result; 14715 SecureRandom random = new SecureRandom(); 14716 byte[] bytes = new byte[16]; 14717 do { 14718 random.nextBytes(bytes); 14719 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14720 result = new File(targetDir, packageName + "-" + suffix); 14721 } while (result.exists()); 14722 return result; 14723 } 14724 14725 // Utility method that returns the relative package path with respect 14726 // to the installation directory. Like say for /data/data/com.test-1.apk 14727 // string com.test-1 is returned. 14728 static String deriveCodePathName(String codePath) { 14729 if (codePath == null) { 14730 return null; 14731 } 14732 final File codeFile = new File(codePath); 14733 final String name = codeFile.getName(); 14734 if (codeFile.isDirectory()) { 14735 return name; 14736 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14737 final int lastDot = name.lastIndexOf('.'); 14738 return name.substring(0, lastDot); 14739 } else { 14740 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14741 return null; 14742 } 14743 } 14744 14745 static class PackageInstalledInfo { 14746 String name; 14747 int uid; 14748 // The set of users that originally had this package installed. 14749 int[] origUsers; 14750 // The set of users that now have this package installed. 14751 int[] newUsers; 14752 PackageParser.Package pkg; 14753 int returnCode; 14754 String returnMsg; 14755 PackageRemovedInfo removedInfo; 14756 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14757 14758 public void setError(int code, String msg) { 14759 setReturnCode(code); 14760 setReturnMessage(msg); 14761 Slog.w(TAG, msg); 14762 } 14763 14764 public void setError(String msg, PackageParserException e) { 14765 setReturnCode(e.error); 14766 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14767 Slog.w(TAG, msg, e); 14768 } 14769 14770 public void setError(String msg, PackageManagerException e) { 14771 returnCode = e.error; 14772 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14773 Slog.w(TAG, msg, e); 14774 } 14775 14776 public void setReturnCode(int returnCode) { 14777 this.returnCode = returnCode; 14778 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14779 for (int i = 0; i < childCount; i++) { 14780 addedChildPackages.valueAt(i).returnCode = returnCode; 14781 } 14782 } 14783 14784 private void setReturnMessage(String returnMsg) { 14785 this.returnMsg = returnMsg; 14786 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14787 for (int i = 0; i < childCount; i++) { 14788 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14789 } 14790 } 14791 14792 // In some error cases we want to convey more info back to the observer 14793 String origPackage; 14794 String origPermission; 14795 } 14796 14797 /* 14798 * Install a non-existing package. 14799 */ 14800 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14801 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14802 PackageInstalledInfo res) { 14803 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14804 14805 // Remember this for later, in case we need to rollback this install 14806 String pkgName = pkg.packageName; 14807 14808 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14809 14810 synchronized(mPackages) { 14811 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14812 if (renamedPackage != null) { 14813 // A package with the same name is already installed, though 14814 // it has been renamed to an older name. The package we 14815 // are trying to install should be installed as an update to 14816 // the existing one, but that has not been requested, so bail. 14817 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14818 + " without first uninstalling package running as " 14819 + renamedPackage); 14820 return; 14821 } 14822 if (mPackages.containsKey(pkgName)) { 14823 // Don't allow installation over an existing package with the same name. 14824 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14825 + " without first uninstalling."); 14826 return; 14827 } 14828 } 14829 14830 try { 14831 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14832 System.currentTimeMillis(), user); 14833 14834 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14835 14836 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14837 prepareAppDataAfterInstallLIF(newPackage); 14838 14839 } else { 14840 // Remove package from internal structures, but keep around any 14841 // data that might have already existed 14842 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14843 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14844 } 14845 } catch (PackageManagerException e) { 14846 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14847 } 14848 14849 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14850 } 14851 14852 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14853 // Can't rotate keys during boot or if sharedUser. 14854 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14855 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14856 return false; 14857 } 14858 // app is using upgradeKeySets; make sure all are valid 14859 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14860 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14861 for (int i = 0; i < upgradeKeySets.length; i++) { 14862 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14863 Slog.wtf(TAG, "Package " 14864 + (oldPs.name != null ? oldPs.name : "<null>") 14865 + " contains upgrade-key-set reference to unknown key-set: " 14866 + upgradeKeySets[i] 14867 + " reverting to signatures check."); 14868 return false; 14869 } 14870 } 14871 return true; 14872 } 14873 14874 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14875 // Upgrade keysets are being used. Determine if new package has a superset of the 14876 // required keys. 14877 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14878 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14879 for (int i = 0; i < upgradeKeySets.length; i++) { 14880 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14881 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14882 return true; 14883 } 14884 } 14885 return false; 14886 } 14887 14888 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14889 try (DigestInputStream digestStream = 14890 new DigestInputStream(new FileInputStream(file), digest)) { 14891 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14892 } 14893 } 14894 14895 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14896 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14897 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14898 14899 final PackageParser.Package oldPackage; 14900 final String pkgName = pkg.packageName; 14901 final int[] allUsers; 14902 final int[] installedUsers; 14903 14904 synchronized(mPackages) { 14905 oldPackage = mPackages.get(pkgName); 14906 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14907 14908 // don't allow upgrade to target a release SDK from a pre-release SDK 14909 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14910 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14911 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14912 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14913 if (oldTargetsPreRelease 14914 && !newTargetsPreRelease 14915 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14916 Slog.w(TAG, "Can't install package targeting released sdk"); 14917 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14918 return; 14919 } 14920 14921 // don't allow an upgrade from full to ephemeral 14922 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14923 if (isEphemeral && !oldIsEphemeral) { 14924 // can't downgrade from full to ephemeral 14925 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14926 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14927 return; 14928 } 14929 14930 // verify signatures are valid 14931 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14932 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14933 if (!checkUpgradeKeySetLP(ps, pkg)) { 14934 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14935 "New package not signed by keys specified by upgrade-keysets: " 14936 + pkgName); 14937 return; 14938 } 14939 } else { 14940 // default to original signature matching 14941 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14942 != PackageManager.SIGNATURE_MATCH) { 14943 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14944 "New package has a different signature: " + pkgName); 14945 return; 14946 } 14947 } 14948 14949 // don't allow a system upgrade unless the upgrade hash matches 14950 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14951 byte[] digestBytes = null; 14952 try { 14953 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14954 updateDigest(digest, new File(pkg.baseCodePath)); 14955 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14956 for (String path : pkg.splitCodePaths) { 14957 updateDigest(digest, new File(path)); 14958 } 14959 } 14960 digestBytes = digest.digest(); 14961 } catch (NoSuchAlgorithmException | IOException e) { 14962 res.setError(INSTALL_FAILED_INVALID_APK, 14963 "Could not compute hash: " + pkgName); 14964 return; 14965 } 14966 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14967 res.setError(INSTALL_FAILED_INVALID_APK, 14968 "New package fails restrict-update check: " + pkgName); 14969 return; 14970 } 14971 // retain upgrade restriction 14972 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14973 } 14974 14975 // Check for shared user id changes 14976 String invalidPackageName = 14977 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14978 if (invalidPackageName != null) { 14979 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14980 "Package " + invalidPackageName + " tried to change user " 14981 + oldPackage.mSharedUserId); 14982 return; 14983 } 14984 14985 // In case of rollback, remember per-user/profile install state 14986 allUsers = sUserManager.getUserIds(); 14987 installedUsers = ps.queryInstalledUsers(allUsers, true); 14988 } 14989 14990 // Update what is removed 14991 res.removedInfo = new PackageRemovedInfo(); 14992 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14993 res.removedInfo.removedPackage = oldPackage.packageName; 14994 res.removedInfo.isUpdate = true; 14995 res.removedInfo.origUsers = installedUsers; 14996 final int childCount = (oldPackage.childPackages != null) 14997 ? oldPackage.childPackages.size() : 0; 14998 for (int i = 0; i < childCount; i++) { 14999 boolean childPackageUpdated = false; 15000 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15001 if (res.addedChildPackages != null) { 15002 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15003 if (childRes != null) { 15004 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15005 childRes.removedInfo.removedPackage = childPkg.packageName; 15006 childRes.removedInfo.isUpdate = true; 15007 childPackageUpdated = true; 15008 } 15009 } 15010 if (!childPackageUpdated) { 15011 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15012 childRemovedRes.removedPackage = childPkg.packageName; 15013 childRemovedRes.isUpdate = false; 15014 childRemovedRes.dataRemoved = true; 15015 synchronized (mPackages) { 15016 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15017 if (childPs != null) { 15018 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15019 } 15020 } 15021 if (res.removedInfo.removedChildPackages == null) { 15022 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15023 } 15024 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15025 } 15026 } 15027 15028 boolean sysPkg = (isSystemApp(oldPackage)); 15029 if (sysPkg) { 15030 // Set the system/privileged flags as needed 15031 final boolean privileged = 15032 (oldPackage.applicationInfo.privateFlags 15033 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15034 final int systemPolicyFlags = policyFlags 15035 | PackageParser.PARSE_IS_SYSTEM 15036 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15037 15038 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15039 user, allUsers, installerPackageName, res); 15040 } else { 15041 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15042 user, allUsers, installerPackageName, res); 15043 } 15044 } 15045 15046 public List<String> getPreviousCodePaths(String packageName) { 15047 final PackageSetting ps = mSettings.mPackages.get(packageName); 15048 final List<String> result = new ArrayList<String>(); 15049 if (ps != null && ps.oldCodePaths != null) { 15050 result.addAll(ps.oldCodePaths); 15051 } 15052 return result; 15053 } 15054 15055 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15056 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15057 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 15058 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15059 + deletedPackage); 15060 15061 String pkgName = deletedPackage.packageName; 15062 boolean deletedPkg = true; 15063 boolean addedPkg = false; 15064 boolean updatedSettings = false; 15065 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15066 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15067 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15068 15069 final long origUpdateTime = (pkg.mExtras != null) 15070 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15071 15072 // First delete the existing package while retaining the data directory 15073 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15074 res.removedInfo, true, pkg)) { 15075 // If the existing package wasn't successfully deleted 15076 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15077 deletedPkg = false; 15078 } else { 15079 // Successfully deleted the old package; proceed with replace. 15080 15081 // If deleted package lived in a container, give users a chance to 15082 // relinquish resources before killing. 15083 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15084 if (DEBUG_INSTALL) { 15085 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15086 } 15087 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15088 final ArrayList<String> pkgList = new ArrayList<String>(1); 15089 pkgList.add(deletedPackage.applicationInfo.packageName); 15090 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15091 } 15092 15093 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15094 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15095 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15096 15097 try { 15098 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15099 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15100 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15101 15102 // Update the in-memory copy of the previous code paths. 15103 PackageSetting ps = mSettings.mPackages.get(pkgName); 15104 if (!killApp) { 15105 if (ps.oldCodePaths == null) { 15106 ps.oldCodePaths = new ArraySet<>(); 15107 } 15108 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15109 if (deletedPackage.splitCodePaths != null) { 15110 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15111 } 15112 } else { 15113 ps.oldCodePaths = null; 15114 } 15115 if (ps.childPackageNames != null) { 15116 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15117 final String childPkgName = ps.childPackageNames.get(i); 15118 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15119 childPs.oldCodePaths = ps.oldCodePaths; 15120 } 15121 } 15122 prepareAppDataAfterInstallLIF(newPackage); 15123 addedPkg = true; 15124 } catch (PackageManagerException e) { 15125 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15126 } 15127 } 15128 15129 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15130 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 15131 15132 // Revert all internal state mutations and added folders for the failed install 15133 if (addedPkg) { 15134 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15135 res.removedInfo, true, null); 15136 } 15137 15138 // Restore the old package 15139 if (deletedPkg) { 15140 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 15141 File restoreFile = new File(deletedPackage.codePath); 15142 // Parse old package 15143 boolean oldExternal = isExternal(deletedPackage); 15144 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 15145 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 15146 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 15147 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 15148 try { 15149 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 15150 null); 15151 } catch (PackageManagerException e) { 15152 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 15153 + e.getMessage()); 15154 return; 15155 } 15156 15157 synchronized (mPackages) { 15158 // Ensure the installer package name up to date 15159 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15160 15161 // Update permissions for restored package 15162 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15163 15164 mSettings.writeLPr(); 15165 } 15166 15167 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 15168 } 15169 } else { 15170 synchronized (mPackages) { 15171 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 15172 if (ps != null) { 15173 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15174 if (res.removedInfo.removedChildPackages != null) { 15175 final int childCount = res.removedInfo.removedChildPackages.size(); 15176 // Iterate in reverse as we may modify the collection 15177 for (int i = childCount - 1; i >= 0; i--) { 15178 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 15179 if (res.addedChildPackages.containsKey(childPackageName)) { 15180 res.removedInfo.removedChildPackages.removeAt(i); 15181 } else { 15182 PackageRemovedInfo childInfo = res.removedInfo 15183 .removedChildPackages.valueAt(i); 15184 childInfo.removedForAllUsers = mPackages.get( 15185 childInfo.removedPackage) == null; 15186 } 15187 } 15188 } 15189 } 15190 } 15191 } 15192 } 15193 15194 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 15195 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15196 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 15197 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 15198 + ", old=" + deletedPackage); 15199 15200 final boolean disabledSystem; 15201 15202 // Remove existing system package 15203 removePackageLI(deletedPackage, true); 15204 15205 synchronized (mPackages) { 15206 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 15207 } 15208 if (!disabledSystem) { 15209 // We didn't need to disable the .apk as a current system package, 15210 // which means we are replacing another update that is already 15211 // installed. We need to make sure to delete the older one's .apk. 15212 res.removedInfo.args = createInstallArgsForExisting(0, 15213 deletedPackage.applicationInfo.getCodePath(), 15214 deletedPackage.applicationInfo.getResourcePath(), 15215 getAppDexInstructionSets(deletedPackage.applicationInfo)); 15216 } else { 15217 res.removedInfo.args = null; 15218 } 15219 15220 // Successfully disabled the old package. Now proceed with re-installation 15221 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15222 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15223 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15224 15225 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15226 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 15227 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 15228 15229 PackageParser.Package newPackage = null; 15230 try { 15231 // Add the package to the internal data structures 15232 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 15233 15234 // Set the update and install times 15235 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 15236 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 15237 System.currentTimeMillis()); 15238 15239 // Update the package dynamic state if succeeded 15240 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15241 // Now that the install succeeded make sure we remove data 15242 // directories for any child package the update removed. 15243 final int deletedChildCount = (deletedPackage.childPackages != null) 15244 ? deletedPackage.childPackages.size() : 0; 15245 final int newChildCount = (newPackage.childPackages != null) 15246 ? newPackage.childPackages.size() : 0; 15247 for (int i = 0; i < deletedChildCount; i++) { 15248 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 15249 boolean childPackageDeleted = true; 15250 for (int j = 0; j < newChildCount; j++) { 15251 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15252 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15253 childPackageDeleted = false; 15254 break; 15255 } 15256 } 15257 if (childPackageDeleted) { 15258 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15259 deletedChildPkg.packageName); 15260 if (ps != null && res.removedInfo.removedChildPackages != null) { 15261 PackageRemovedInfo removedChildRes = res.removedInfo 15262 .removedChildPackages.get(deletedChildPkg.packageName); 15263 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15264 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15265 } 15266 } 15267 } 15268 15269 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15270 prepareAppDataAfterInstallLIF(newPackage); 15271 } 15272 } catch (PackageManagerException e) { 15273 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15274 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15275 } 15276 15277 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15278 // Re installation failed. Restore old information 15279 // Remove new pkg information 15280 if (newPackage != null) { 15281 removeInstalledPackageLI(newPackage, true); 15282 } 15283 // Add back the old system package 15284 try { 15285 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15286 } catch (PackageManagerException e) { 15287 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15288 } 15289 15290 synchronized (mPackages) { 15291 if (disabledSystem) { 15292 enableSystemPackageLPw(deletedPackage); 15293 } 15294 15295 // Ensure the installer package name up to date 15296 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15297 15298 // Update permissions for restored package 15299 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15300 15301 mSettings.writeLPr(); 15302 } 15303 15304 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15305 + " after failed upgrade"); 15306 } 15307 } 15308 15309 /** 15310 * Checks whether the parent or any of the child packages have a change shared 15311 * user. For a package to be a valid update the shred users of the parent and 15312 * the children should match. We may later support changing child shared users. 15313 * @param oldPkg The updated package. 15314 * @param newPkg The update package. 15315 * @return The shared user that change between the versions. 15316 */ 15317 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15318 PackageParser.Package newPkg) { 15319 // Check parent shared user 15320 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15321 return newPkg.packageName; 15322 } 15323 // Check child shared users 15324 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15325 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15326 for (int i = 0; i < newChildCount; i++) { 15327 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15328 // If this child was present, did it have the same shared user? 15329 for (int j = 0; j < oldChildCount; j++) { 15330 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15331 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15332 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15333 return newChildPkg.packageName; 15334 } 15335 } 15336 } 15337 return null; 15338 } 15339 15340 private void removeNativeBinariesLI(PackageSetting ps) { 15341 // Remove the lib path for the parent package 15342 if (ps != null) { 15343 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15344 // Remove the lib path for the child packages 15345 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15346 for (int i = 0; i < childCount; i++) { 15347 PackageSetting childPs = null; 15348 synchronized (mPackages) { 15349 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15350 } 15351 if (childPs != null) { 15352 NativeLibraryHelper.removeNativeBinariesLI(childPs 15353 .legacyNativeLibraryPathString); 15354 } 15355 } 15356 } 15357 } 15358 15359 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15360 // Enable the parent package 15361 mSettings.enableSystemPackageLPw(pkg.packageName); 15362 // Enable the child packages 15363 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15364 for (int i = 0; i < childCount; i++) { 15365 PackageParser.Package childPkg = pkg.childPackages.get(i); 15366 mSettings.enableSystemPackageLPw(childPkg.packageName); 15367 } 15368 } 15369 15370 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15371 PackageParser.Package newPkg) { 15372 // Disable the parent package (parent always replaced) 15373 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15374 // Disable the child packages 15375 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15376 for (int i = 0; i < childCount; i++) { 15377 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15378 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15379 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15380 } 15381 return disabled; 15382 } 15383 15384 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15385 String installerPackageName) { 15386 // Enable the parent package 15387 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15388 // Enable the child packages 15389 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15390 for (int i = 0; i < childCount; i++) { 15391 PackageParser.Package childPkg = pkg.childPackages.get(i); 15392 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15393 } 15394 } 15395 15396 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15397 // Collect all used permissions in the UID 15398 ArraySet<String> usedPermissions = new ArraySet<>(); 15399 final int packageCount = su.packages.size(); 15400 for (int i = 0; i < packageCount; i++) { 15401 PackageSetting ps = su.packages.valueAt(i); 15402 if (ps.pkg == null) { 15403 continue; 15404 } 15405 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15406 for (int j = 0; j < requestedPermCount; j++) { 15407 String permission = ps.pkg.requestedPermissions.get(j); 15408 BasePermission bp = mSettings.mPermissions.get(permission); 15409 if (bp != null) { 15410 usedPermissions.add(permission); 15411 } 15412 } 15413 } 15414 15415 PermissionsState permissionsState = su.getPermissionsState(); 15416 // Prune install permissions 15417 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15418 final int installPermCount = installPermStates.size(); 15419 for (int i = installPermCount - 1; i >= 0; i--) { 15420 PermissionState permissionState = installPermStates.get(i); 15421 if (!usedPermissions.contains(permissionState.getName())) { 15422 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15423 if (bp != null) { 15424 permissionsState.revokeInstallPermission(bp); 15425 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15426 PackageManager.MASK_PERMISSION_FLAGS, 0); 15427 } 15428 } 15429 } 15430 15431 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15432 15433 // Prune runtime permissions 15434 for (int userId : allUserIds) { 15435 List<PermissionState> runtimePermStates = permissionsState 15436 .getRuntimePermissionStates(userId); 15437 final int runtimePermCount = runtimePermStates.size(); 15438 for (int i = runtimePermCount - 1; i >= 0; i--) { 15439 PermissionState permissionState = runtimePermStates.get(i); 15440 if (!usedPermissions.contains(permissionState.getName())) { 15441 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15442 if (bp != null) { 15443 permissionsState.revokeRuntimePermission(bp, userId); 15444 permissionsState.updatePermissionFlags(bp, userId, 15445 PackageManager.MASK_PERMISSION_FLAGS, 0); 15446 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15447 runtimePermissionChangedUserIds, userId); 15448 } 15449 } 15450 } 15451 } 15452 15453 return runtimePermissionChangedUserIds; 15454 } 15455 15456 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15457 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15458 // Update the parent package setting 15459 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15460 res, user); 15461 // Update the child packages setting 15462 final int childCount = (newPackage.childPackages != null) 15463 ? newPackage.childPackages.size() : 0; 15464 for (int i = 0; i < childCount; i++) { 15465 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15466 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15467 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15468 childRes.origUsers, childRes, user); 15469 } 15470 } 15471 15472 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15473 String installerPackageName, int[] allUsers, int[] installedForUsers, 15474 PackageInstalledInfo res, UserHandle user) { 15475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15476 15477 String pkgName = newPackage.packageName; 15478 synchronized (mPackages) { 15479 //write settings. the installStatus will be incomplete at this stage. 15480 //note that the new package setting would have already been 15481 //added to mPackages. It hasn't been persisted yet. 15482 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15484 mSettings.writeLPr(); 15485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15486 } 15487 15488 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15489 synchronized (mPackages) { 15490 updatePermissionsLPw(newPackage.packageName, newPackage, 15491 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15492 ? UPDATE_PERMISSIONS_ALL : 0)); 15493 // For system-bundled packages, we assume that installing an upgraded version 15494 // of the package implies that the user actually wants to run that new code, 15495 // so we enable the package. 15496 PackageSetting ps = mSettings.mPackages.get(pkgName); 15497 final int userId = user.getIdentifier(); 15498 if (ps != null) { 15499 if (isSystemApp(newPackage)) { 15500 if (DEBUG_INSTALL) { 15501 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15502 } 15503 // Enable system package for requested users 15504 if (res.origUsers != null) { 15505 for (int origUserId : res.origUsers) { 15506 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15507 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15508 origUserId, installerPackageName); 15509 } 15510 } 15511 } 15512 // Also convey the prior install/uninstall state 15513 if (allUsers != null && installedForUsers != null) { 15514 for (int currentUserId : allUsers) { 15515 final boolean installed = ArrayUtils.contains( 15516 installedForUsers, currentUserId); 15517 if (DEBUG_INSTALL) { 15518 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15519 } 15520 ps.setInstalled(installed, currentUserId); 15521 } 15522 // these install state changes will be persisted in the 15523 // upcoming call to mSettings.writeLPr(). 15524 } 15525 } 15526 // It's implied that when a user requests installation, they want the app to be 15527 // installed and enabled. 15528 if (userId != UserHandle.USER_ALL) { 15529 ps.setInstalled(true, userId); 15530 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15531 } 15532 } 15533 res.name = pkgName; 15534 res.uid = newPackage.applicationInfo.uid; 15535 res.pkg = newPackage; 15536 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15537 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15538 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15539 //to update install status 15540 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15541 mSettings.writeLPr(); 15542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15543 } 15544 15545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15546 } 15547 15548 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15549 try { 15550 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15551 installPackageLI(args, res); 15552 } finally { 15553 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15554 } 15555 } 15556 15557 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15558 final int installFlags = args.installFlags; 15559 final String installerPackageName = args.installerPackageName; 15560 final String volumeUuid = args.volumeUuid; 15561 final File tmpPackageFile = new File(args.getCodePath()); 15562 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15563 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15564 || (args.volumeUuid != null)); 15565 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15566 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15567 boolean replace = false; 15568 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15569 if (args.move != null) { 15570 // moving a complete application; perform an initial scan on the new install location 15571 scanFlags |= SCAN_INITIAL; 15572 } 15573 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15574 scanFlags |= SCAN_DONT_KILL_APP; 15575 } 15576 15577 // Result object to be returned 15578 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15579 15580 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15581 15582 // Sanity check 15583 if (ephemeral && (forwardLocked || onExternal)) { 15584 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15585 + " external=" + onExternal); 15586 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15587 return; 15588 } 15589 15590 // Retrieve PackageSettings and parse package 15591 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15592 | PackageParser.PARSE_ENFORCE_CODE 15593 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15594 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15595 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15596 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15597 PackageParser pp = new PackageParser(); 15598 pp.setSeparateProcesses(mSeparateProcesses); 15599 pp.setDisplayMetrics(mMetrics); 15600 15601 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15602 final PackageParser.Package pkg; 15603 try { 15604 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15605 } catch (PackageParserException e) { 15606 res.setError("Failed parse during installPackageLI", e); 15607 return; 15608 } finally { 15609 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15610 } 15611 15612 // Ephemeral apps must have target SDK >= O. 15613 // TODO: Update conditional and error message when O gets locked down 15614 if (ephemeral && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 15615 res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 15616 "Ephemeral apps must have target SDK version of at least O"); 15617 return; 15618 } 15619 15620 // If we are installing a clustered package add results for the children 15621 if (pkg.childPackages != null) { 15622 synchronized (mPackages) { 15623 final int childCount = pkg.childPackages.size(); 15624 for (int i = 0; i < childCount; i++) { 15625 PackageParser.Package childPkg = pkg.childPackages.get(i); 15626 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15627 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15628 childRes.pkg = childPkg; 15629 childRes.name = childPkg.packageName; 15630 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15631 if (childPs != null) { 15632 childRes.origUsers = childPs.queryInstalledUsers( 15633 sUserManager.getUserIds(), true); 15634 } 15635 if ((mPackages.containsKey(childPkg.packageName))) { 15636 childRes.removedInfo = new PackageRemovedInfo(); 15637 childRes.removedInfo.removedPackage = childPkg.packageName; 15638 } 15639 if (res.addedChildPackages == null) { 15640 res.addedChildPackages = new ArrayMap<>(); 15641 } 15642 res.addedChildPackages.put(childPkg.packageName, childRes); 15643 } 15644 } 15645 } 15646 15647 // If package doesn't declare API override, mark that we have an install 15648 // time CPU ABI override. 15649 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15650 pkg.cpuAbiOverride = args.abiOverride; 15651 } 15652 15653 String pkgName = res.name = pkg.packageName; 15654 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15655 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15656 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15657 return; 15658 } 15659 } 15660 15661 try { 15662 // either use what we've been given or parse directly from the APK 15663 if (args.certificates != null) { 15664 try { 15665 PackageParser.populateCertificates(pkg, args.certificates); 15666 } catch (PackageParserException e) { 15667 // there was something wrong with the certificates we were given; 15668 // try to pull them from the APK 15669 PackageParser.collectCertificates(pkg, parseFlags); 15670 } 15671 } else { 15672 PackageParser.collectCertificates(pkg, parseFlags); 15673 } 15674 } catch (PackageParserException e) { 15675 res.setError("Failed collect during installPackageLI", e); 15676 return; 15677 } 15678 15679 // Get rid of all references to package scan path via parser. 15680 pp = null; 15681 String oldCodePath = null; 15682 boolean systemApp = false; 15683 synchronized (mPackages) { 15684 // Check if installing already existing package 15685 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15686 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15687 if (pkg.mOriginalPackages != null 15688 && pkg.mOriginalPackages.contains(oldName) 15689 && mPackages.containsKey(oldName)) { 15690 // This package is derived from an original package, 15691 // and this device has been updating from that original 15692 // name. We must continue using the original name, so 15693 // rename the new package here. 15694 pkg.setPackageName(oldName); 15695 pkgName = pkg.packageName; 15696 replace = true; 15697 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15698 + oldName + " pkgName=" + pkgName); 15699 } else if (mPackages.containsKey(pkgName)) { 15700 // This package, under its official name, already exists 15701 // on the device; we should replace it. 15702 replace = true; 15703 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15704 } 15705 15706 // Child packages are installed through the parent package 15707 if (pkg.parentPackage != null) { 15708 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15709 "Package " + pkg.packageName + " is child of package " 15710 + pkg.parentPackage.parentPackage + ". Child packages " 15711 + "can be updated only through the parent package."); 15712 return; 15713 } 15714 15715 if (replace) { 15716 // Prevent apps opting out from runtime permissions 15717 PackageParser.Package oldPackage = mPackages.get(pkgName); 15718 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15719 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15720 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15721 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15722 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15723 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15724 + " doesn't support runtime permissions but the old" 15725 + " target SDK " + oldTargetSdk + " does."); 15726 return; 15727 } 15728 15729 // Prevent installing of child packages 15730 if (oldPackage.parentPackage != null) { 15731 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15732 "Package " + pkg.packageName + " is child of package " 15733 + oldPackage.parentPackage + ". Child packages " 15734 + "can be updated only through the parent package."); 15735 return; 15736 } 15737 } 15738 } 15739 15740 PackageSetting ps = mSettings.mPackages.get(pkgName); 15741 if (ps != null) { 15742 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15743 15744 // Quick sanity check that we're signed correctly if updating; 15745 // we'll check this again later when scanning, but we want to 15746 // bail early here before tripping over redefined permissions. 15747 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15748 if (!checkUpgradeKeySetLP(ps, pkg)) { 15749 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15750 + pkg.packageName + " upgrade keys do not match the " 15751 + "previously installed version"); 15752 return; 15753 } 15754 } else { 15755 try { 15756 verifySignaturesLP(ps, pkg); 15757 } catch (PackageManagerException e) { 15758 res.setError(e.error, e.getMessage()); 15759 return; 15760 } 15761 } 15762 15763 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15764 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15765 systemApp = (ps.pkg.applicationInfo.flags & 15766 ApplicationInfo.FLAG_SYSTEM) != 0; 15767 } 15768 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15769 } 15770 15771 // Check whether the newly-scanned package wants to define an already-defined perm 15772 int N = pkg.permissions.size(); 15773 for (int i = N-1; i >= 0; i--) { 15774 PackageParser.Permission perm = pkg.permissions.get(i); 15775 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15776 if (bp != null) { 15777 // If the defining package is signed with our cert, it's okay. This 15778 // also includes the "updating the same package" case, of course. 15779 // "updating same package" could also involve key-rotation. 15780 final boolean sigsOk; 15781 if (bp.sourcePackage.equals(pkg.packageName) 15782 && (bp.packageSetting instanceof PackageSetting) 15783 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15784 scanFlags))) { 15785 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15786 } else { 15787 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15788 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15789 } 15790 if (!sigsOk) { 15791 // If the owning package is the system itself, we log but allow 15792 // install to proceed; we fail the install on all other permission 15793 // redefinitions. 15794 if (!bp.sourcePackage.equals("android")) { 15795 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15796 + pkg.packageName + " attempting to redeclare permission " 15797 + perm.info.name + " already owned by " + bp.sourcePackage); 15798 res.origPermission = perm.info.name; 15799 res.origPackage = bp.sourcePackage; 15800 return; 15801 } else { 15802 Slog.w(TAG, "Package " + pkg.packageName 15803 + " attempting to redeclare system permission " 15804 + perm.info.name + "; ignoring new declaration"); 15805 pkg.permissions.remove(i); 15806 } 15807 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 15808 // Prevent apps to change protection level to dangerous from any other 15809 // type as this would allow a privilege escalation where an app adds a 15810 // normal/signature permission in other app's group and later redefines 15811 // it as dangerous leading to the group auto-grant. 15812 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 15813 == PermissionInfo.PROTECTION_DANGEROUS) { 15814 if (bp != null && !bp.isRuntime()) { 15815 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 15816 + "non-runtime permission " + perm.info.name 15817 + " to runtime; keeping old protection level"); 15818 perm.info.protectionLevel = bp.protectionLevel; 15819 } 15820 } 15821 } 15822 } 15823 } 15824 } 15825 15826 if (systemApp) { 15827 if (onExternal) { 15828 // Abort update; system app can't be replaced with app on sdcard 15829 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15830 "Cannot install updates to system apps on sdcard"); 15831 return; 15832 } else if (ephemeral) { 15833 // Abort update; system app can't be replaced with an ephemeral app 15834 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15835 "Cannot update a system app with an ephemeral app"); 15836 return; 15837 } 15838 } 15839 15840 if (args.move != null) { 15841 // We did an in-place move, so dex is ready to roll 15842 scanFlags |= SCAN_NO_DEX; 15843 scanFlags |= SCAN_MOVE; 15844 15845 synchronized (mPackages) { 15846 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15847 if (ps == null) { 15848 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15849 "Missing settings for moved package " + pkgName); 15850 } 15851 15852 // We moved the entire application as-is, so bring over the 15853 // previously derived ABI information. 15854 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15855 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15856 } 15857 15858 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15859 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15860 scanFlags |= SCAN_NO_DEX; 15861 15862 try { 15863 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15864 args.abiOverride : pkg.cpuAbiOverride); 15865 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15866 true /*extractLibs*/, mAppLib32InstallDir); 15867 } catch (PackageManagerException pme) { 15868 Slog.e(TAG, "Error deriving application ABI", pme); 15869 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15870 return; 15871 } 15872 15873 // Shared libraries for the package need to be updated. 15874 synchronized (mPackages) { 15875 try { 15876 updateSharedLibrariesLPr(pkg, null); 15877 } catch (PackageManagerException e) { 15878 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15879 } 15880 } 15881 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15882 // Do not run PackageDexOptimizer through the local performDexOpt 15883 // method because `pkg` may not be in `mPackages` yet. 15884 // 15885 // Also, don't fail application installs if the dexopt step fails. 15886 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15887 null /* instructionSets */, false /* checkProfiles */, 15888 getCompilerFilterForReason(REASON_INSTALL), 15889 getOrCreateCompilerPackageStats(pkg)); 15890 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15891 15892 // Notify BackgroundDexOptService that the package has been changed. 15893 // If this is an update of a package which used to fail to compile, 15894 // BDOS will remove it from its blacklist. 15895 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15896 } 15897 15898 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15899 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15900 return; 15901 } 15902 15903 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15904 15905 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15906 "installPackageLI")) { 15907 if (replace) { 15908 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15909 installerPackageName, res); 15910 } else { 15911 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15912 args.user, installerPackageName, volumeUuid, res); 15913 } 15914 } 15915 synchronized (mPackages) { 15916 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15917 if (ps != null) { 15918 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15919 } 15920 15921 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15922 for (int i = 0; i < childCount; i++) { 15923 PackageParser.Package childPkg = pkg.childPackages.get(i); 15924 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15925 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15926 if (childPs != null) { 15927 childRes.newUsers = childPs.queryInstalledUsers( 15928 sUserManager.getUserIds(), true); 15929 } 15930 } 15931 } 15932 } 15933 15934 private void startIntentFilterVerifications(int userId, boolean replacing, 15935 PackageParser.Package pkg) { 15936 if (mIntentFilterVerifierComponent == null) { 15937 Slog.w(TAG, "No IntentFilter verification will not be done as " 15938 + "there is no IntentFilterVerifier available!"); 15939 return; 15940 } 15941 15942 final int verifierUid = getPackageUid( 15943 mIntentFilterVerifierComponent.getPackageName(), 15944 MATCH_DEBUG_TRIAGED_MISSING, 15945 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15946 15947 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15948 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15949 mHandler.sendMessage(msg); 15950 15951 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15952 for (int i = 0; i < childCount; i++) { 15953 PackageParser.Package childPkg = pkg.childPackages.get(i); 15954 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15955 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15956 mHandler.sendMessage(msg); 15957 } 15958 } 15959 15960 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15961 PackageParser.Package pkg) { 15962 int size = pkg.activities.size(); 15963 if (size == 0) { 15964 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15965 "No activity, so no need to verify any IntentFilter!"); 15966 return; 15967 } 15968 15969 final boolean hasDomainURLs = hasDomainURLs(pkg); 15970 if (!hasDomainURLs) { 15971 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15972 "No domain URLs, so no need to verify any IntentFilter!"); 15973 return; 15974 } 15975 15976 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15977 + " if any IntentFilter from the " + size 15978 + " Activities needs verification ..."); 15979 15980 int count = 0; 15981 final String packageName = pkg.packageName; 15982 15983 synchronized (mPackages) { 15984 // If this is a new install and we see that we've already run verification for this 15985 // package, we have nothing to do: it means the state was restored from backup. 15986 if (!replacing) { 15987 IntentFilterVerificationInfo ivi = 15988 mSettings.getIntentFilterVerificationLPr(packageName); 15989 if (ivi != null) { 15990 if (DEBUG_DOMAIN_VERIFICATION) { 15991 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15992 + ivi.getStatusString()); 15993 } 15994 return; 15995 } 15996 } 15997 15998 // If any filters need to be verified, then all need to be. 15999 boolean needToVerify = false; 16000 for (PackageParser.Activity a : pkg.activities) { 16001 for (ActivityIntentInfo filter : a.intents) { 16002 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16003 if (DEBUG_DOMAIN_VERIFICATION) { 16004 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16005 } 16006 needToVerify = true; 16007 break; 16008 } 16009 } 16010 } 16011 16012 if (needToVerify) { 16013 final int verificationId = mIntentFilterVerificationToken++; 16014 for (PackageParser.Activity a : pkg.activities) { 16015 for (ActivityIntentInfo filter : a.intents) { 16016 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 16017 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16018 "Verification needed for IntentFilter:" + filter.toString()); 16019 mIntentFilterVerifier.addOneIntentFilterVerification( 16020 verifierUid, userId, verificationId, filter, packageName); 16021 count++; 16022 } 16023 } 16024 } 16025 } 16026 } 16027 16028 if (count > 0) { 16029 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 16030 + " IntentFilter verification" + (count > 1 ? "s" : "") 16031 + " for userId:" + userId); 16032 mIntentFilterVerifier.startVerifications(userId); 16033 } else { 16034 if (DEBUG_DOMAIN_VERIFICATION) { 16035 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 16036 } 16037 } 16038 } 16039 16040 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 16041 final ComponentName cn = filter.activity.getComponentName(); 16042 final String packageName = cn.getPackageName(); 16043 16044 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 16045 packageName); 16046 if (ivi == null) { 16047 return true; 16048 } 16049 int status = ivi.getStatus(); 16050 switch (status) { 16051 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 16052 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 16053 return true; 16054 16055 default: 16056 // Nothing to do 16057 return false; 16058 } 16059 } 16060 16061 private static boolean isMultiArch(ApplicationInfo info) { 16062 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 16063 } 16064 16065 private static boolean isExternal(PackageParser.Package pkg) { 16066 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16067 } 16068 16069 private static boolean isExternal(PackageSetting ps) { 16070 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 16071 } 16072 16073 private static boolean isEphemeral(PackageParser.Package pkg) { 16074 return pkg.applicationInfo.isEphemeralApp(); 16075 } 16076 16077 private static boolean isEphemeral(PackageSetting ps) { 16078 return ps.pkg != null && isEphemeral(ps.pkg); 16079 } 16080 16081 private static boolean isSystemApp(PackageParser.Package pkg) { 16082 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 16083 } 16084 16085 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 16086 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16087 } 16088 16089 private static boolean hasDomainURLs(PackageParser.Package pkg) { 16090 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 16091 } 16092 16093 private static boolean isSystemApp(PackageSetting ps) { 16094 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 16095 } 16096 16097 private static boolean isUpdatedSystemApp(PackageSetting ps) { 16098 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 16099 } 16100 16101 private int packageFlagsToInstallFlags(PackageSetting ps) { 16102 int installFlags = 0; 16103 if (isEphemeral(ps)) { 16104 installFlags |= PackageManager.INSTALL_EPHEMERAL; 16105 } 16106 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 16107 // This existing package was an external ASEC install when we have 16108 // the external flag without a UUID 16109 installFlags |= PackageManager.INSTALL_EXTERNAL; 16110 } 16111 if (ps.isForwardLocked()) { 16112 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 16113 } 16114 return installFlags; 16115 } 16116 16117 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 16118 if (isExternal(pkg)) { 16119 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16120 return StorageManager.UUID_PRIMARY_PHYSICAL; 16121 } else { 16122 return pkg.volumeUuid; 16123 } 16124 } else { 16125 return StorageManager.UUID_PRIVATE_INTERNAL; 16126 } 16127 } 16128 16129 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 16130 if (isExternal(pkg)) { 16131 if (TextUtils.isEmpty(pkg.volumeUuid)) { 16132 return mSettings.getExternalVersion(); 16133 } else { 16134 return mSettings.findOrCreateVersion(pkg.volumeUuid); 16135 } 16136 } else { 16137 return mSettings.getInternalVersion(); 16138 } 16139 } 16140 16141 private void deleteTempPackageFiles() { 16142 final FilenameFilter filter = new FilenameFilter() { 16143 public boolean accept(File dir, String name) { 16144 return name.startsWith("vmdl") && name.endsWith(".tmp"); 16145 } 16146 }; 16147 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 16148 file.delete(); 16149 } 16150 } 16151 16152 @Override 16153 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 16154 int flags) { 16155 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 16156 flags); 16157 } 16158 16159 @Override 16160 public void deletePackage(final String packageName, 16161 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 16162 mContext.enforceCallingOrSelfPermission( 16163 android.Manifest.permission.DELETE_PACKAGES, null); 16164 Preconditions.checkNotNull(packageName); 16165 Preconditions.checkNotNull(observer); 16166 final int uid = Binder.getCallingUid(); 16167 if (!isOrphaned(packageName) 16168 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 16169 try { 16170 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 16171 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 16172 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 16173 observer.onUserActionRequired(intent); 16174 } catch (RemoteException re) { 16175 } 16176 return; 16177 } 16178 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 16179 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 16180 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 16181 mContext.enforceCallingOrSelfPermission( 16182 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 16183 "deletePackage for user " + userId); 16184 } 16185 16186 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 16187 try { 16188 observer.onPackageDeleted(packageName, 16189 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 16190 } catch (RemoteException re) { 16191 } 16192 return; 16193 } 16194 16195 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 16196 try { 16197 observer.onPackageDeleted(packageName, 16198 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 16199 } catch (RemoteException re) { 16200 } 16201 return; 16202 } 16203 16204 if (DEBUG_REMOVE) { 16205 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 16206 + " deleteAllUsers: " + deleteAllUsers ); 16207 } 16208 // Queue up an async operation since the package deletion may take a little while. 16209 mHandler.post(new Runnable() { 16210 public void run() { 16211 mHandler.removeCallbacks(this); 16212 int returnCode; 16213 if (!deleteAllUsers) { 16214 returnCode = deletePackageX(packageName, userId, deleteFlags); 16215 } else { 16216 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 16217 // If nobody is blocking uninstall, proceed with delete for all users 16218 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 16219 returnCode = deletePackageX(packageName, userId, deleteFlags); 16220 } else { 16221 // Otherwise uninstall individually for users with blockUninstalls=false 16222 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 16223 for (int userId : users) { 16224 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 16225 returnCode = deletePackageX(packageName, userId, userFlags); 16226 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 16227 Slog.w(TAG, "Package delete failed for user " + userId 16228 + ", returnCode " + returnCode); 16229 } 16230 } 16231 } 16232 // The app has only been marked uninstalled for certain users. 16233 // We still need to report that delete was blocked 16234 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 16235 } 16236 } 16237 try { 16238 observer.onPackageDeleted(packageName, returnCode, null); 16239 } catch (RemoteException e) { 16240 Log.i(TAG, "Observer no longer exists."); 16241 } //end catch 16242 } //end run 16243 }); 16244 } 16245 16246 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 16247 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 16248 || callingUid == Process.SYSTEM_UID) { 16249 return true; 16250 } 16251 final int callingUserId = UserHandle.getUserId(callingUid); 16252 // If the caller installed the pkgName, then allow it to silently uninstall. 16253 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 16254 return true; 16255 } 16256 16257 // Allow package verifier to silently uninstall. 16258 if (mRequiredVerifierPackage != null && 16259 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 16260 return true; 16261 } 16262 16263 // Allow package uninstaller to silently uninstall. 16264 if (mRequiredUninstallerPackage != null && 16265 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 16266 return true; 16267 } 16268 16269 // Allow storage manager to silently uninstall. 16270 if (mStorageManagerPackage != null && 16271 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 16272 return true; 16273 } 16274 return false; 16275 } 16276 16277 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16278 int[] result = EMPTY_INT_ARRAY; 16279 for (int userId : userIds) { 16280 if (getBlockUninstallForUser(packageName, userId)) { 16281 result = ArrayUtils.appendInt(result, userId); 16282 } 16283 } 16284 return result; 16285 } 16286 16287 @Override 16288 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16289 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16290 } 16291 16292 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16293 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16294 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16295 try { 16296 if (dpm != null) { 16297 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16298 /* callingUserOnly =*/ false); 16299 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16300 : deviceOwnerComponentName.getPackageName(); 16301 // Does the package contains the device owner? 16302 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16303 // this check is probably not needed, since DO should be registered as a device 16304 // admin on some user too. (Original bug for this: b/17657954) 16305 if (packageName.equals(deviceOwnerPackageName)) { 16306 return true; 16307 } 16308 // Does it contain a device admin for any user? 16309 int[] users; 16310 if (userId == UserHandle.USER_ALL) { 16311 users = sUserManager.getUserIds(); 16312 } else { 16313 users = new int[]{userId}; 16314 } 16315 for (int i = 0; i < users.length; ++i) { 16316 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16317 return true; 16318 } 16319 } 16320 } 16321 } catch (RemoteException e) { 16322 } 16323 return false; 16324 } 16325 16326 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16327 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16328 } 16329 16330 /** 16331 * This method is an internal method that could be get invoked either 16332 * to delete an installed package or to clean up a failed installation. 16333 * After deleting an installed package, a broadcast is sent to notify any 16334 * listeners that the package has been removed. For cleaning up a failed 16335 * installation, the broadcast is not necessary since the package's 16336 * installation wouldn't have sent the initial broadcast either 16337 * The key steps in deleting a package are 16338 * deleting the package information in internal structures like mPackages, 16339 * deleting the packages base directories through installd 16340 * updating mSettings to reflect current status 16341 * persisting settings for later use 16342 * sending a broadcast if necessary 16343 */ 16344 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16345 final PackageRemovedInfo info = new PackageRemovedInfo(); 16346 final boolean res; 16347 16348 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16349 ? UserHandle.USER_ALL : userId; 16350 16351 if (isPackageDeviceAdmin(packageName, removeUser)) { 16352 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16353 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16354 } 16355 16356 PackageSetting uninstalledPs = null; 16357 16358 // for the uninstall-updates case and restricted profiles, remember the per- 16359 // user handle installed state 16360 int[] allUsers; 16361 synchronized (mPackages) { 16362 uninstalledPs = mSettings.mPackages.get(packageName); 16363 if (uninstalledPs == null) { 16364 Slog.w(TAG, "Not removing non-existent package " + packageName); 16365 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16366 } 16367 allUsers = sUserManager.getUserIds(); 16368 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16369 } 16370 16371 final int freezeUser; 16372 if (isUpdatedSystemApp(uninstalledPs) 16373 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16374 // We're downgrading a system app, which will apply to all users, so 16375 // freeze them all during the downgrade 16376 freezeUser = UserHandle.USER_ALL; 16377 } else { 16378 freezeUser = removeUser; 16379 } 16380 16381 synchronized (mInstallLock) { 16382 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16383 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16384 deleteFlags, "deletePackageX")) { 16385 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16386 deleteFlags | REMOVE_CHATTY, info, true, null); 16387 } 16388 synchronized (mPackages) { 16389 if (res) { 16390 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16391 } 16392 } 16393 } 16394 16395 if (res) { 16396 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16397 info.sendPackageRemovedBroadcasts(killApp); 16398 info.sendSystemPackageUpdatedBroadcasts(); 16399 info.sendSystemPackageAppearedBroadcasts(); 16400 } 16401 // Force a gc here. 16402 Runtime.getRuntime().gc(); 16403 // Delete the resources here after sending the broadcast to let 16404 // other processes clean up before deleting resources. 16405 if (info.args != null) { 16406 synchronized (mInstallLock) { 16407 info.args.doPostDeleteLI(true); 16408 } 16409 } 16410 16411 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16412 } 16413 16414 class PackageRemovedInfo { 16415 String removedPackage; 16416 int uid = -1; 16417 int removedAppId = -1; 16418 int[] origUsers; 16419 int[] removedUsers = null; 16420 boolean isRemovedPackageSystemUpdate = false; 16421 boolean isUpdate; 16422 boolean dataRemoved; 16423 boolean removedForAllUsers; 16424 // Clean up resources deleted packages. 16425 InstallArgs args = null; 16426 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16427 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16428 16429 void sendPackageRemovedBroadcasts(boolean killApp) { 16430 sendPackageRemovedBroadcastInternal(killApp); 16431 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16432 for (int i = 0; i < childCount; i++) { 16433 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16434 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16435 } 16436 } 16437 16438 void sendSystemPackageUpdatedBroadcasts() { 16439 if (isRemovedPackageSystemUpdate) { 16440 sendSystemPackageUpdatedBroadcastsInternal(); 16441 final int childCount = (removedChildPackages != null) 16442 ? removedChildPackages.size() : 0; 16443 for (int i = 0; i < childCount; i++) { 16444 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16445 if (childInfo.isRemovedPackageSystemUpdate) { 16446 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16447 } 16448 } 16449 } 16450 } 16451 16452 void sendSystemPackageAppearedBroadcasts() { 16453 final int packageCount = (appearedChildPackages != null) 16454 ? appearedChildPackages.size() : 0; 16455 for (int i = 0; i < packageCount; i++) { 16456 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16457 sendPackageAddedForNewUsers(installedInfo.name, true, 16458 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16459 } 16460 } 16461 16462 private void sendSystemPackageUpdatedBroadcastsInternal() { 16463 Bundle extras = new Bundle(2); 16464 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16465 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16466 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16467 extras, 0, null, null, null); 16468 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16469 extras, 0, null, null, null); 16470 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16471 null, 0, removedPackage, null, null); 16472 } 16473 16474 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16475 Bundle extras = new Bundle(2); 16476 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16477 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16478 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16479 if (isUpdate || isRemovedPackageSystemUpdate) { 16480 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16481 } 16482 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16483 if (removedPackage != null) { 16484 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16485 extras, 0, null, null, removedUsers); 16486 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16487 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16488 removedPackage, extras, 0, null, null, removedUsers); 16489 } 16490 } 16491 if (removedAppId >= 0) { 16492 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16493 removedUsers); 16494 } 16495 } 16496 } 16497 16498 /* 16499 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16500 * flag is not set, the data directory is removed as well. 16501 * make sure this flag is set for partially installed apps. If not its meaningless to 16502 * delete a partially installed application. 16503 */ 16504 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16505 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16506 String packageName = ps.name; 16507 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16508 // Retrieve object to delete permissions for shared user later on 16509 final PackageParser.Package deletedPkg; 16510 final PackageSetting deletedPs; 16511 // reader 16512 synchronized (mPackages) { 16513 deletedPkg = mPackages.get(packageName); 16514 deletedPs = mSettings.mPackages.get(packageName); 16515 if (outInfo != null) { 16516 outInfo.removedPackage = packageName; 16517 outInfo.removedUsers = deletedPs != null 16518 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16519 : null; 16520 } 16521 } 16522 16523 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16524 16525 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16526 final PackageParser.Package resolvedPkg; 16527 if (deletedPkg != null) { 16528 resolvedPkg = deletedPkg; 16529 } else { 16530 // We don't have a parsed package when it lives on an ejected 16531 // adopted storage device, so fake something together 16532 resolvedPkg = new PackageParser.Package(ps.name); 16533 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16534 } 16535 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16536 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16537 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16538 if (outInfo != null) { 16539 outInfo.dataRemoved = true; 16540 } 16541 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16542 } 16543 16544 // writer 16545 synchronized (mPackages) { 16546 if (deletedPs != null) { 16547 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16548 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16549 clearDefaultBrowserIfNeeded(packageName); 16550 if (outInfo != null) { 16551 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16552 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16553 } 16554 updatePermissionsLPw(deletedPs.name, null, 0); 16555 if (deletedPs.sharedUser != null) { 16556 // Remove permissions associated with package. Since runtime 16557 // permissions are per user we have to kill the removed package 16558 // or packages running under the shared user of the removed 16559 // package if revoking the permissions requested only by the removed 16560 // package is successful and this causes a change in gids. 16561 for (int userId : UserManagerService.getInstance().getUserIds()) { 16562 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16563 userId); 16564 if (userIdToKill == UserHandle.USER_ALL 16565 || userIdToKill >= UserHandle.USER_SYSTEM) { 16566 // If gids changed for this user, kill all affected packages. 16567 mHandler.post(new Runnable() { 16568 @Override 16569 public void run() { 16570 // This has to happen with no lock held. 16571 killApplication(deletedPs.name, deletedPs.appId, 16572 KILL_APP_REASON_GIDS_CHANGED); 16573 } 16574 }); 16575 break; 16576 } 16577 } 16578 } 16579 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16580 } 16581 // make sure to preserve per-user disabled state if this removal was just 16582 // a downgrade of a system app to the factory package 16583 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16584 if (DEBUG_REMOVE) { 16585 Slog.d(TAG, "Propagating install state across downgrade"); 16586 } 16587 for (int userId : allUserHandles) { 16588 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16589 if (DEBUG_REMOVE) { 16590 Slog.d(TAG, " user " + userId + " => " + installed); 16591 } 16592 ps.setInstalled(installed, userId); 16593 } 16594 } 16595 } 16596 // can downgrade to reader 16597 if (writeSettings) { 16598 // Save settings now 16599 mSettings.writeLPr(); 16600 } 16601 } 16602 if (outInfo != null) { 16603 // A user ID was deleted here. Go through all users and remove it 16604 // from KeyStore. 16605 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16606 } 16607 } 16608 16609 static boolean locationIsPrivileged(File path) { 16610 try { 16611 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16612 .getCanonicalPath(); 16613 return path.getCanonicalPath().startsWith(privilegedAppDir); 16614 } catch (IOException e) { 16615 Slog.e(TAG, "Unable to access code path " + path); 16616 } 16617 return false; 16618 } 16619 16620 /* 16621 * Tries to delete system package. 16622 */ 16623 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16624 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16625 boolean writeSettings) { 16626 if (deletedPs.parentPackageName != null) { 16627 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16628 return false; 16629 } 16630 16631 final boolean applyUserRestrictions 16632 = (allUserHandles != null) && (outInfo.origUsers != null); 16633 final PackageSetting disabledPs; 16634 // Confirm if the system package has been updated 16635 // An updated system app can be deleted. This will also have to restore 16636 // the system pkg from system partition 16637 // reader 16638 synchronized (mPackages) { 16639 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16640 } 16641 16642 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16643 + " disabledPs=" + disabledPs); 16644 16645 if (disabledPs == null) { 16646 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16647 return false; 16648 } else if (DEBUG_REMOVE) { 16649 Slog.d(TAG, "Deleting system pkg from data partition"); 16650 } 16651 16652 if (DEBUG_REMOVE) { 16653 if (applyUserRestrictions) { 16654 Slog.d(TAG, "Remembering install states:"); 16655 for (int userId : allUserHandles) { 16656 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16657 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16658 } 16659 } 16660 } 16661 16662 // Delete the updated package 16663 outInfo.isRemovedPackageSystemUpdate = true; 16664 if (outInfo.removedChildPackages != null) { 16665 final int childCount = (deletedPs.childPackageNames != null) 16666 ? deletedPs.childPackageNames.size() : 0; 16667 for (int i = 0; i < childCount; i++) { 16668 String childPackageName = deletedPs.childPackageNames.get(i); 16669 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16670 .contains(childPackageName)) { 16671 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16672 childPackageName); 16673 if (childInfo != null) { 16674 childInfo.isRemovedPackageSystemUpdate = true; 16675 } 16676 } 16677 } 16678 } 16679 16680 if (disabledPs.versionCode < deletedPs.versionCode) { 16681 // Delete data for downgrades 16682 flags &= ~PackageManager.DELETE_KEEP_DATA; 16683 } else { 16684 // Preserve data by setting flag 16685 flags |= PackageManager.DELETE_KEEP_DATA; 16686 } 16687 16688 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16689 outInfo, writeSettings, disabledPs.pkg); 16690 if (!ret) { 16691 return false; 16692 } 16693 16694 // writer 16695 synchronized (mPackages) { 16696 // Reinstate the old system package 16697 enableSystemPackageLPw(disabledPs.pkg); 16698 // Remove any native libraries from the upgraded package. 16699 removeNativeBinariesLI(deletedPs); 16700 } 16701 16702 // Install the system package 16703 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16704 int parseFlags = mDefParseFlags 16705 | PackageParser.PARSE_MUST_BE_APK 16706 | PackageParser.PARSE_IS_SYSTEM 16707 | PackageParser.PARSE_IS_SYSTEM_DIR; 16708 if (locationIsPrivileged(disabledPs.codePath)) { 16709 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16710 } 16711 16712 final PackageParser.Package newPkg; 16713 try { 16714 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16715 0 /* currentTime */, null); 16716 } catch (PackageManagerException e) { 16717 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16718 + e.getMessage()); 16719 return false; 16720 } 16721 try { 16722 // update shared libraries for the newly re-installed system package 16723 updateSharedLibrariesLPr(newPkg, null); 16724 } catch (PackageManagerException e) { 16725 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16726 } 16727 16728 prepareAppDataAfterInstallLIF(newPkg); 16729 16730 // writer 16731 synchronized (mPackages) { 16732 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16733 16734 // Propagate the permissions state as we do not want to drop on the floor 16735 // runtime permissions. The update permissions method below will take 16736 // care of removing obsolete permissions and grant install permissions. 16737 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16738 updatePermissionsLPw(newPkg.packageName, newPkg, 16739 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16740 16741 if (applyUserRestrictions) { 16742 if (DEBUG_REMOVE) { 16743 Slog.d(TAG, "Propagating install state across reinstall"); 16744 } 16745 for (int userId : allUserHandles) { 16746 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16747 if (DEBUG_REMOVE) { 16748 Slog.d(TAG, " user " + userId + " => " + installed); 16749 } 16750 ps.setInstalled(installed, userId); 16751 16752 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16753 } 16754 // Regardless of writeSettings we need to ensure that this restriction 16755 // state propagation is persisted 16756 mSettings.writeAllUsersPackageRestrictionsLPr(); 16757 } 16758 // can downgrade to reader here 16759 if (writeSettings) { 16760 mSettings.writeLPr(); 16761 } 16762 } 16763 return true; 16764 } 16765 16766 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16767 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16768 PackageRemovedInfo outInfo, boolean writeSettings, 16769 PackageParser.Package replacingPackage) { 16770 synchronized (mPackages) { 16771 if (outInfo != null) { 16772 outInfo.uid = ps.appId; 16773 } 16774 16775 if (outInfo != null && outInfo.removedChildPackages != null) { 16776 final int childCount = (ps.childPackageNames != null) 16777 ? ps.childPackageNames.size() : 0; 16778 for (int i = 0; i < childCount; i++) { 16779 String childPackageName = ps.childPackageNames.get(i); 16780 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16781 if (childPs == null) { 16782 return false; 16783 } 16784 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16785 childPackageName); 16786 if (childInfo != null) { 16787 childInfo.uid = childPs.appId; 16788 } 16789 } 16790 } 16791 } 16792 16793 // Delete package data from internal structures and also remove data if flag is set 16794 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16795 16796 // Delete the child packages data 16797 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16798 for (int i = 0; i < childCount; i++) { 16799 PackageSetting childPs; 16800 synchronized (mPackages) { 16801 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16802 } 16803 if (childPs != null) { 16804 PackageRemovedInfo childOutInfo = (outInfo != null 16805 && outInfo.removedChildPackages != null) 16806 ? outInfo.removedChildPackages.get(childPs.name) : null; 16807 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16808 && (replacingPackage != null 16809 && !replacingPackage.hasChildPackage(childPs.name)) 16810 ? flags & ~DELETE_KEEP_DATA : flags; 16811 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16812 deleteFlags, writeSettings); 16813 } 16814 } 16815 16816 // Delete application code and resources only for parent packages 16817 if (ps.parentPackageName == null) { 16818 if (deleteCodeAndResources && (outInfo != null)) { 16819 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16820 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16821 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16822 } 16823 } 16824 16825 return true; 16826 } 16827 16828 @Override 16829 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16830 int userId) { 16831 mContext.enforceCallingOrSelfPermission( 16832 android.Manifest.permission.DELETE_PACKAGES, null); 16833 synchronized (mPackages) { 16834 PackageSetting ps = mSettings.mPackages.get(packageName); 16835 if (ps == null) { 16836 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16837 return false; 16838 } 16839 if (!ps.getInstalled(userId)) { 16840 // Can't block uninstall for an app that is not installed or enabled. 16841 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16842 return false; 16843 } 16844 ps.setBlockUninstall(blockUninstall, userId); 16845 mSettings.writePackageRestrictionsLPr(userId); 16846 } 16847 return true; 16848 } 16849 16850 @Override 16851 public boolean getBlockUninstallForUser(String packageName, int userId) { 16852 synchronized (mPackages) { 16853 PackageSetting ps = mSettings.mPackages.get(packageName); 16854 if (ps == null) { 16855 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16856 return false; 16857 } 16858 return ps.getBlockUninstall(userId); 16859 } 16860 } 16861 16862 @Override 16863 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16864 int callingUid = Binder.getCallingUid(); 16865 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16866 throw new SecurityException( 16867 "setRequiredForSystemUser can only be run by the system or root"); 16868 } 16869 synchronized (mPackages) { 16870 PackageSetting ps = mSettings.mPackages.get(packageName); 16871 if (ps == null) { 16872 Log.w(TAG, "Package doesn't exist: " + packageName); 16873 return false; 16874 } 16875 if (systemUserApp) { 16876 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16877 } else { 16878 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16879 } 16880 mSettings.writeLPr(); 16881 } 16882 return true; 16883 } 16884 16885 /* 16886 * This method handles package deletion in general 16887 */ 16888 private boolean deletePackageLIF(String packageName, UserHandle user, 16889 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16890 PackageRemovedInfo outInfo, boolean writeSettings, 16891 PackageParser.Package replacingPackage) { 16892 if (packageName == null) { 16893 Slog.w(TAG, "Attempt to delete null packageName."); 16894 return false; 16895 } 16896 16897 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16898 16899 PackageSetting ps; 16900 16901 synchronized (mPackages) { 16902 ps = mSettings.mPackages.get(packageName); 16903 if (ps == null) { 16904 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16905 return false; 16906 } 16907 16908 if (ps.parentPackageName != null && (!isSystemApp(ps) 16909 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16910 if (DEBUG_REMOVE) { 16911 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16912 + ((user == null) ? UserHandle.USER_ALL : user)); 16913 } 16914 final int removedUserId = (user != null) ? user.getIdentifier() 16915 : UserHandle.USER_ALL; 16916 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16917 return false; 16918 } 16919 markPackageUninstalledForUserLPw(ps, user); 16920 scheduleWritePackageRestrictionsLocked(user); 16921 return true; 16922 } 16923 } 16924 16925 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16926 && user.getIdentifier() != UserHandle.USER_ALL)) { 16927 // The caller is asking that the package only be deleted for a single 16928 // user. To do this, we just mark its uninstalled state and delete 16929 // its data. If this is a system app, we only allow this to happen if 16930 // they have set the special DELETE_SYSTEM_APP which requests different 16931 // semantics than normal for uninstalling system apps. 16932 markPackageUninstalledForUserLPw(ps, user); 16933 16934 if (!isSystemApp(ps)) { 16935 // Do not uninstall the APK if an app should be cached 16936 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16937 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16938 // Other user still have this package installed, so all 16939 // we need to do is clear this user's data and save that 16940 // it is uninstalled. 16941 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16942 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16943 return false; 16944 } 16945 scheduleWritePackageRestrictionsLocked(user); 16946 return true; 16947 } else { 16948 // We need to set it back to 'installed' so the uninstall 16949 // broadcasts will be sent correctly. 16950 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16951 ps.setInstalled(true, user.getIdentifier()); 16952 } 16953 } else { 16954 // This is a system app, so we assume that the 16955 // other users still have this package installed, so all 16956 // we need to do is clear this user's data and save that 16957 // it is uninstalled. 16958 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16959 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16960 return false; 16961 } 16962 scheduleWritePackageRestrictionsLocked(user); 16963 return true; 16964 } 16965 } 16966 16967 // If we are deleting a composite package for all users, keep track 16968 // of result for each child. 16969 if (ps.childPackageNames != null && outInfo != null) { 16970 synchronized (mPackages) { 16971 final int childCount = ps.childPackageNames.size(); 16972 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16973 for (int i = 0; i < childCount; i++) { 16974 String childPackageName = ps.childPackageNames.get(i); 16975 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16976 childInfo.removedPackage = childPackageName; 16977 outInfo.removedChildPackages.put(childPackageName, childInfo); 16978 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16979 if (childPs != null) { 16980 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16981 } 16982 } 16983 } 16984 } 16985 16986 boolean ret = false; 16987 if (isSystemApp(ps)) { 16988 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16989 // When an updated system application is deleted we delete the existing resources 16990 // as well and fall back to existing code in system partition 16991 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16992 } else { 16993 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16994 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16995 outInfo, writeSettings, replacingPackage); 16996 } 16997 16998 // Take a note whether we deleted the package for all users 16999 if (outInfo != null) { 17000 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 17001 if (outInfo.removedChildPackages != null) { 17002 synchronized (mPackages) { 17003 final int childCount = outInfo.removedChildPackages.size(); 17004 for (int i = 0; i < childCount; i++) { 17005 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 17006 if (childInfo != null) { 17007 childInfo.removedForAllUsers = mPackages.get( 17008 childInfo.removedPackage) == null; 17009 } 17010 } 17011 } 17012 } 17013 // If we uninstalled an update to a system app there may be some 17014 // child packages that appeared as they are declared in the system 17015 // app but were not declared in the update. 17016 if (isSystemApp(ps)) { 17017 synchronized (mPackages) { 17018 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 17019 final int childCount = (updatedPs.childPackageNames != null) 17020 ? updatedPs.childPackageNames.size() : 0; 17021 for (int i = 0; i < childCount; i++) { 17022 String childPackageName = updatedPs.childPackageNames.get(i); 17023 if (outInfo.removedChildPackages == null 17024 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 17025 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 17026 if (childPs == null) { 17027 continue; 17028 } 17029 PackageInstalledInfo installRes = new PackageInstalledInfo(); 17030 installRes.name = childPackageName; 17031 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 17032 installRes.pkg = mPackages.get(childPackageName); 17033 installRes.uid = childPs.pkg.applicationInfo.uid; 17034 if (outInfo.appearedChildPackages == null) { 17035 outInfo.appearedChildPackages = new ArrayMap<>(); 17036 } 17037 outInfo.appearedChildPackages.put(childPackageName, installRes); 17038 } 17039 } 17040 } 17041 } 17042 } 17043 17044 return ret; 17045 } 17046 17047 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 17048 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 17049 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 17050 for (int nextUserId : userIds) { 17051 if (DEBUG_REMOVE) { 17052 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 17053 } 17054 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 17055 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 17056 false /*hidden*/, false /*suspended*/, null, null, null, 17057 false /*blockUninstall*/, 17058 ps.readUserState(nextUserId).domainVerificationStatus, 0); 17059 } 17060 } 17061 17062 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 17063 PackageRemovedInfo outInfo) { 17064 final PackageParser.Package pkg; 17065 synchronized (mPackages) { 17066 pkg = mPackages.get(ps.name); 17067 } 17068 17069 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 17070 : new int[] {userId}; 17071 for (int nextUserId : userIds) { 17072 if (DEBUG_REMOVE) { 17073 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 17074 + nextUserId); 17075 } 17076 17077 destroyAppDataLIF(pkg, userId, 17078 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17079 destroyAppProfilesLIF(pkg, userId); 17080 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 17081 schedulePackageCleaning(ps.name, nextUserId, false); 17082 synchronized (mPackages) { 17083 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 17084 scheduleWritePackageRestrictionsLocked(nextUserId); 17085 } 17086 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 17087 } 17088 } 17089 17090 if (outInfo != null) { 17091 outInfo.removedPackage = ps.name; 17092 outInfo.removedAppId = ps.appId; 17093 outInfo.removedUsers = userIds; 17094 } 17095 17096 return true; 17097 } 17098 17099 private final class ClearStorageConnection implements ServiceConnection { 17100 IMediaContainerService mContainerService; 17101 17102 @Override 17103 public void onServiceConnected(ComponentName name, IBinder service) { 17104 synchronized (this) { 17105 mContainerService = IMediaContainerService.Stub 17106 .asInterface(Binder.allowBlocking(service)); 17107 notifyAll(); 17108 } 17109 } 17110 17111 @Override 17112 public void onServiceDisconnected(ComponentName name) { 17113 } 17114 } 17115 17116 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 17117 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 17118 17119 final boolean mounted; 17120 if (Environment.isExternalStorageEmulated()) { 17121 mounted = true; 17122 } else { 17123 final String status = Environment.getExternalStorageState(); 17124 17125 mounted = status.equals(Environment.MEDIA_MOUNTED) 17126 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 17127 } 17128 17129 if (!mounted) { 17130 return; 17131 } 17132 17133 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 17134 int[] users; 17135 if (userId == UserHandle.USER_ALL) { 17136 users = sUserManager.getUserIds(); 17137 } else { 17138 users = new int[] { userId }; 17139 } 17140 final ClearStorageConnection conn = new ClearStorageConnection(); 17141 if (mContext.bindServiceAsUser( 17142 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 17143 try { 17144 for (int curUser : users) { 17145 long timeout = SystemClock.uptimeMillis() + 5000; 17146 synchronized (conn) { 17147 long now; 17148 while (conn.mContainerService == null && 17149 (now = SystemClock.uptimeMillis()) < timeout) { 17150 try { 17151 conn.wait(timeout - now); 17152 } catch (InterruptedException e) { 17153 } 17154 } 17155 } 17156 if (conn.mContainerService == null) { 17157 return; 17158 } 17159 17160 final UserEnvironment userEnv = new UserEnvironment(curUser); 17161 clearDirectory(conn.mContainerService, 17162 userEnv.buildExternalStorageAppCacheDirs(packageName)); 17163 if (allData) { 17164 clearDirectory(conn.mContainerService, 17165 userEnv.buildExternalStorageAppDataDirs(packageName)); 17166 clearDirectory(conn.mContainerService, 17167 userEnv.buildExternalStorageAppMediaDirs(packageName)); 17168 } 17169 } 17170 } finally { 17171 mContext.unbindService(conn); 17172 } 17173 } 17174 } 17175 17176 @Override 17177 public void clearApplicationProfileData(String packageName) { 17178 enforceSystemOrRoot("Only the system can clear all profile data"); 17179 17180 final PackageParser.Package pkg; 17181 synchronized (mPackages) { 17182 pkg = mPackages.get(packageName); 17183 } 17184 17185 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 17186 synchronized (mInstallLock) { 17187 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 17188 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 17189 true /* removeBaseMarker */); 17190 } 17191 } 17192 } 17193 17194 @Override 17195 public void clearApplicationUserData(final String packageName, 17196 final IPackageDataObserver observer, final int userId) { 17197 mContext.enforceCallingOrSelfPermission( 17198 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 17199 17200 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17201 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 17202 17203 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 17204 throw new SecurityException("Cannot clear data for a protected package: " 17205 + packageName); 17206 } 17207 // Queue up an async operation since the package deletion may take a little while. 17208 mHandler.post(new Runnable() { 17209 public void run() { 17210 mHandler.removeCallbacks(this); 17211 final boolean succeeded; 17212 try (PackageFreezer freezer = freezePackage(packageName, 17213 "clearApplicationUserData")) { 17214 synchronized (mInstallLock) { 17215 succeeded = clearApplicationUserDataLIF(packageName, userId); 17216 } 17217 clearExternalStorageDataSync(packageName, userId, true); 17218 } 17219 if (succeeded) { 17220 // invoke DeviceStorageMonitor's update method to clear any notifications 17221 DeviceStorageMonitorInternal dsm = LocalServices 17222 .getService(DeviceStorageMonitorInternal.class); 17223 if (dsm != null) { 17224 dsm.checkMemory(); 17225 } 17226 } 17227 if(observer != null) { 17228 try { 17229 observer.onRemoveCompleted(packageName, succeeded); 17230 } catch (RemoteException e) { 17231 Log.i(TAG, "Observer no longer exists."); 17232 } 17233 } //end if observer 17234 } //end run 17235 }); 17236 } 17237 17238 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 17239 if (packageName == null) { 17240 Slog.w(TAG, "Attempt to delete null packageName."); 17241 return false; 17242 } 17243 17244 // Try finding details about the requested package 17245 PackageParser.Package pkg; 17246 synchronized (mPackages) { 17247 pkg = mPackages.get(packageName); 17248 if (pkg == null) { 17249 final PackageSetting ps = mSettings.mPackages.get(packageName); 17250 if (ps != null) { 17251 pkg = ps.pkg; 17252 } 17253 } 17254 17255 if (pkg == null) { 17256 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 17257 return false; 17258 } 17259 17260 PackageSetting ps = (PackageSetting) pkg.mExtras; 17261 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17262 } 17263 17264 clearAppDataLIF(pkg, userId, 17265 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17266 17267 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 17268 removeKeystoreDataIfNeeded(userId, appId); 17269 17270 UserManagerInternal umInternal = getUserManagerInternal(); 17271 final int flags; 17272 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17273 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17274 } else if (umInternal.isUserRunning(userId)) { 17275 flags = StorageManager.FLAG_STORAGE_DE; 17276 } else { 17277 flags = 0; 17278 } 17279 prepareAppDataContentsLIF(pkg, userId, flags); 17280 17281 return true; 17282 } 17283 17284 /** 17285 * Reverts user permission state changes (permissions and flags) in 17286 * all packages for a given user. 17287 * 17288 * @param userId The device user for which to do a reset. 17289 */ 17290 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17291 final int packageCount = mPackages.size(); 17292 for (int i = 0; i < packageCount; i++) { 17293 PackageParser.Package pkg = mPackages.valueAt(i); 17294 PackageSetting ps = (PackageSetting) pkg.mExtras; 17295 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17296 } 17297 } 17298 17299 private void resetNetworkPolicies(int userId) { 17300 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17301 } 17302 17303 /** 17304 * Reverts user permission state changes (permissions and flags). 17305 * 17306 * @param ps The package for which to reset. 17307 * @param userId The device user for which to do a reset. 17308 */ 17309 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17310 final PackageSetting ps, final int userId) { 17311 if (ps.pkg == null) { 17312 return; 17313 } 17314 17315 // These are flags that can change base on user actions. 17316 final int userSettableMask = FLAG_PERMISSION_USER_SET 17317 | FLAG_PERMISSION_USER_FIXED 17318 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17319 | FLAG_PERMISSION_REVIEW_REQUIRED; 17320 17321 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17322 | FLAG_PERMISSION_POLICY_FIXED; 17323 17324 boolean writeInstallPermissions = false; 17325 boolean writeRuntimePermissions = false; 17326 17327 final int permissionCount = ps.pkg.requestedPermissions.size(); 17328 for (int i = 0; i < permissionCount; i++) { 17329 String permission = ps.pkg.requestedPermissions.get(i); 17330 17331 BasePermission bp = mSettings.mPermissions.get(permission); 17332 if (bp == null) { 17333 continue; 17334 } 17335 17336 // If shared user we just reset the state to which only this app contributed. 17337 if (ps.sharedUser != null) { 17338 boolean used = false; 17339 final int packageCount = ps.sharedUser.packages.size(); 17340 for (int j = 0; j < packageCount; j++) { 17341 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17342 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17343 && pkg.pkg.requestedPermissions.contains(permission)) { 17344 used = true; 17345 break; 17346 } 17347 } 17348 if (used) { 17349 continue; 17350 } 17351 } 17352 17353 PermissionsState permissionsState = ps.getPermissionsState(); 17354 17355 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17356 17357 // Always clear the user settable flags. 17358 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17359 bp.name) != null; 17360 // If permission review is enabled and this is a legacy app, mark the 17361 // permission as requiring a review as this is the initial state. 17362 int flags = 0; 17363 if (mPermissionReviewRequired 17364 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17365 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17366 } 17367 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17368 if (hasInstallState) { 17369 writeInstallPermissions = true; 17370 } else { 17371 writeRuntimePermissions = true; 17372 } 17373 } 17374 17375 // Below is only runtime permission handling. 17376 if (!bp.isRuntime()) { 17377 continue; 17378 } 17379 17380 // Never clobber system or policy. 17381 if ((oldFlags & policyOrSystemFlags) != 0) { 17382 continue; 17383 } 17384 17385 // If this permission was granted by default, make sure it is. 17386 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17387 if (permissionsState.grantRuntimePermission(bp, userId) 17388 != PERMISSION_OPERATION_FAILURE) { 17389 writeRuntimePermissions = true; 17390 } 17391 // If permission review is enabled the permissions for a legacy apps 17392 // are represented as constantly granted runtime ones, so don't revoke. 17393 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17394 // Otherwise, reset the permission. 17395 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17396 switch (revokeResult) { 17397 case PERMISSION_OPERATION_SUCCESS: 17398 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17399 writeRuntimePermissions = true; 17400 final int appId = ps.appId; 17401 mHandler.post(new Runnable() { 17402 @Override 17403 public void run() { 17404 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17405 } 17406 }); 17407 } break; 17408 } 17409 } 17410 } 17411 17412 // Synchronously write as we are taking permissions away. 17413 if (writeRuntimePermissions) { 17414 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17415 } 17416 17417 // Synchronously write as we are taking permissions away. 17418 if (writeInstallPermissions) { 17419 mSettings.writeLPr(); 17420 } 17421 } 17422 17423 /** 17424 * Remove entries from the keystore daemon. Will only remove it if the 17425 * {@code appId} is valid. 17426 */ 17427 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17428 if (appId < 0) { 17429 return; 17430 } 17431 17432 final KeyStore keyStore = KeyStore.getInstance(); 17433 if (keyStore != null) { 17434 if (userId == UserHandle.USER_ALL) { 17435 for (final int individual : sUserManager.getUserIds()) { 17436 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17437 } 17438 } else { 17439 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17440 } 17441 } else { 17442 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17443 } 17444 } 17445 17446 @Override 17447 public void deleteApplicationCacheFiles(final String packageName, 17448 final IPackageDataObserver observer) { 17449 final int userId = UserHandle.getCallingUserId(); 17450 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17451 } 17452 17453 @Override 17454 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17455 final IPackageDataObserver observer) { 17456 mContext.enforceCallingOrSelfPermission( 17457 android.Manifest.permission.DELETE_CACHE_FILES, null); 17458 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17459 /* requireFullPermission= */ true, /* checkShell= */ false, 17460 "delete application cache files"); 17461 17462 final PackageParser.Package pkg; 17463 synchronized (mPackages) { 17464 pkg = mPackages.get(packageName); 17465 } 17466 17467 // Queue up an async operation since the package deletion may take a little while. 17468 mHandler.post(new Runnable() { 17469 public void run() { 17470 synchronized (mInstallLock) { 17471 final int flags = StorageManager.FLAG_STORAGE_DE 17472 | StorageManager.FLAG_STORAGE_CE; 17473 // We're only clearing cache files, so we don't care if the 17474 // app is unfrozen and still able to run 17475 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17476 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17477 } 17478 clearExternalStorageDataSync(packageName, userId, false); 17479 if (observer != null) { 17480 try { 17481 observer.onRemoveCompleted(packageName, true); 17482 } catch (RemoteException e) { 17483 Log.i(TAG, "Observer no longer exists."); 17484 } 17485 } 17486 } 17487 }); 17488 } 17489 17490 @Override 17491 public void getPackageSizeInfo(final String packageName, int userHandle, 17492 final IPackageStatsObserver observer) { 17493 mContext.enforceCallingOrSelfPermission( 17494 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17495 if (packageName == null) { 17496 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17497 } 17498 17499 PackageStats stats = new PackageStats(packageName, userHandle); 17500 17501 /* 17502 * Queue up an async operation since the package measurement may take a 17503 * little while. 17504 */ 17505 Message msg = mHandler.obtainMessage(INIT_COPY); 17506 msg.obj = new MeasureParams(stats, observer); 17507 mHandler.sendMessage(msg); 17508 } 17509 17510 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17511 final PackageSetting ps; 17512 synchronized (mPackages) { 17513 ps = mSettings.mPackages.get(packageName); 17514 if (ps == null) { 17515 Slog.w(TAG, "Failed to find settings for " + packageName); 17516 return false; 17517 } 17518 } 17519 17520 final String[] packageNames = { packageName }; 17521 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 17522 final String[] codePaths = { ps.codePathString }; 17523 17524 try { 17525 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 17526 ps.appId, ceDataInodes, codePaths, stats); 17527 17528 // For now, ignore code size of packages on system partition 17529 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17530 stats.codeSize = 0; 17531 } 17532 17533 // External clients expect these to be tracked separately 17534 stats.dataSize -= stats.cacheSize; 17535 17536 } catch (InstallerException e) { 17537 Slog.w(TAG, String.valueOf(e)); 17538 return false; 17539 } 17540 17541 return true; 17542 } 17543 17544 private int getUidTargetSdkVersionLockedLPr(int uid) { 17545 Object obj = mSettings.getUserIdLPr(uid); 17546 if (obj instanceof SharedUserSetting) { 17547 final SharedUserSetting sus = (SharedUserSetting) obj; 17548 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17549 final Iterator<PackageSetting> it = sus.packages.iterator(); 17550 while (it.hasNext()) { 17551 final PackageSetting ps = it.next(); 17552 if (ps.pkg != null) { 17553 int v = ps.pkg.applicationInfo.targetSdkVersion; 17554 if (v < vers) vers = v; 17555 } 17556 } 17557 return vers; 17558 } else if (obj instanceof PackageSetting) { 17559 final PackageSetting ps = (PackageSetting) obj; 17560 if (ps.pkg != null) { 17561 return ps.pkg.applicationInfo.targetSdkVersion; 17562 } 17563 } 17564 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17565 } 17566 17567 @Override 17568 public void addPreferredActivity(IntentFilter filter, int match, 17569 ComponentName[] set, ComponentName activity, int userId) { 17570 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17571 "Adding preferred"); 17572 } 17573 17574 private void addPreferredActivityInternal(IntentFilter filter, int match, 17575 ComponentName[] set, ComponentName activity, boolean always, int userId, 17576 String opname) { 17577 // writer 17578 int callingUid = Binder.getCallingUid(); 17579 enforceCrossUserPermission(callingUid, userId, 17580 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17581 if (filter.countActions() == 0) { 17582 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17583 return; 17584 } 17585 synchronized (mPackages) { 17586 if (mContext.checkCallingOrSelfPermission( 17587 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17588 != PackageManager.PERMISSION_GRANTED) { 17589 if (getUidTargetSdkVersionLockedLPr(callingUid) 17590 < Build.VERSION_CODES.FROYO) { 17591 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17592 + callingUid); 17593 return; 17594 } 17595 mContext.enforceCallingOrSelfPermission( 17596 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17597 } 17598 17599 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17600 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17601 + userId + ":"); 17602 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17603 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17604 scheduleWritePackageRestrictionsLocked(userId); 17605 postPreferredActivityChangedBroadcast(userId); 17606 } 17607 } 17608 17609 private void postPreferredActivityChangedBroadcast(int userId) { 17610 mHandler.post(() -> { 17611 final IActivityManager am = ActivityManager.getService(); 17612 if (am == null) { 17613 return; 17614 } 17615 17616 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17617 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17618 try { 17619 am.broadcastIntent(null, intent, null, null, 17620 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17621 null, false, false, userId); 17622 } catch (RemoteException e) { 17623 } 17624 }); 17625 } 17626 17627 @Override 17628 public void replacePreferredActivity(IntentFilter filter, int match, 17629 ComponentName[] set, ComponentName activity, int userId) { 17630 if (filter.countActions() != 1) { 17631 throw new IllegalArgumentException( 17632 "replacePreferredActivity expects filter to have only 1 action."); 17633 } 17634 if (filter.countDataAuthorities() != 0 17635 || filter.countDataPaths() != 0 17636 || filter.countDataSchemes() > 1 17637 || filter.countDataTypes() != 0) { 17638 throw new IllegalArgumentException( 17639 "replacePreferredActivity expects filter to have no data authorities, " + 17640 "paths, or types; and at most one scheme."); 17641 } 17642 17643 final int callingUid = Binder.getCallingUid(); 17644 enforceCrossUserPermission(callingUid, userId, 17645 true /* requireFullPermission */, false /* checkShell */, 17646 "replace preferred activity"); 17647 synchronized (mPackages) { 17648 if (mContext.checkCallingOrSelfPermission( 17649 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17650 != PackageManager.PERMISSION_GRANTED) { 17651 if (getUidTargetSdkVersionLockedLPr(callingUid) 17652 < Build.VERSION_CODES.FROYO) { 17653 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17654 + Binder.getCallingUid()); 17655 return; 17656 } 17657 mContext.enforceCallingOrSelfPermission( 17658 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17659 } 17660 17661 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17662 if (pir != null) { 17663 // Get all of the existing entries that exactly match this filter. 17664 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17665 if (existing != null && existing.size() == 1) { 17666 PreferredActivity cur = existing.get(0); 17667 if (DEBUG_PREFERRED) { 17668 Slog.i(TAG, "Checking replace of preferred:"); 17669 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17670 if (!cur.mPref.mAlways) { 17671 Slog.i(TAG, " -- CUR; not mAlways!"); 17672 } else { 17673 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17674 Slog.i(TAG, " -- CUR: mSet=" 17675 + Arrays.toString(cur.mPref.mSetComponents)); 17676 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17677 Slog.i(TAG, " -- NEW: mMatch=" 17678 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17679 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17680 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17681 } 17682 } 17683 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17684 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17685 && cur.mPref.sameSet(set)) { 17686 // Setting the preferred activity to what it happens to be already 17687 if (DEBUG_PREFERRED) { 17688 Slog.i(TAG, "Replacing with same preferred activity " 17689 + cur.mPref.mShortComponent + " for user " 17690 + userId + ":"); 17691 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17692 } 17693 return; 17694 } 17695 } 17696 17697 if (existing != null) { 17698 if (DEBUG_PREFERRED) { 17699 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17700 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17701 } 17702 for (int i = 0; i < existing.size(); i++) { 17703 PreferredActivity pa = existing.get(i); 17704 if (DEBUG_PREFERRED) { 17705 Slog.i(TAG, "Removing existing preferred activity " 17706 + pa.mPref.mComponent + ":"); 17707 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17708 } 17709 pir.removeFilter(pa); 17710 } 17711 } 17712 } 17713 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17714 "Replacing preferred"); 17715 } 17716 } 17717 17718 @Override 17719 public void clearPackagePreferredActivities(String packageName) { 17720 final int uid = Binder.getCallingUid(); 17721 // writer 17722 synchronized (mPackages) { 17723 PackageParser.Package pkg = mPackages.get(packageName); 17724 if (pkg == null || pkg.applicationInfo.uid != uid) { 17725 if (mContext.checkCallingOrSelfPermission( 17726 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17727 != PackageManager.PERMISSION_GRANTED) { 17728 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17729 < Build.VERSION_CODES.FROYO) { 17730 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17731 + Binder.getCallingUid()); 17732 return; 17733 } 17734 mContext.enforceCallingOrSelfPermission( 17735 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17736 } 17737 } 17738 17739 int user = UserHandle.getCallingUserId(); 17740 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17741 scheduleWritePackageRestrictionsLocked(user); 17742 } 17743 } 17744 } 17745 17746 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17747 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17748 ArrayList<PreferredActivity> removed = null; 17749 boolean changed = false; 17750 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17751 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17752 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17753 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17754 continue; 17755 } 17756 Iterator<PreferredActivity> it = pir.filterIterator(); 17757 while (it.hasNext()) { 17758 PreferredActivity pa = it.next(); 17759 // Mark entry for removal only if it matches the package name 17760 // and the entry is of type "always". 17761 if (packageName == null || 17762 (pa.mPref.mComponent.getPackageName().equals(packageName) 17763 && pa.mPref.mAlways)) { 17764 if (removed == null) { 17765 removed = new ArrayList<PreferredActivity>(); 17766 } 17767 removed.add(pa); 17768 } 17769 } 17770 if (removed != null) { 17771 for (int j=0; j<removed.size(); j++) { 17772 PreferredActivity pa = removed.get(j); 17773 pir.removeFilter(pa); 17774 } 17775 changed = true; 17776 } 17777 } 17778 if (changed) { 17779 postPreferredActivityChangedBroadcast(userId); 17780 } 17781 return changed; 17782 } 17783 17784 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17785 private void clearIntentFilterVerificationsLPw(int userId) { 17786 final int packageCount = mPackages.size(); 17787 for (int i = 0; i < packageCount; i++) { 17788 PackageParser.Package pkg = mPackages.valueAt(i); 17789 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17790 } 17791 } 17792 17793 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17794 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17795 if (userId == UserHandle.USER_ALL) { 17796 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17797 sUserManager.getUserIds())) { 17798 for (int oneUserId : sUserManager.getUserIds()) { 17799 scheduleWritePackageRestrictionsLocked(oneUserId); 17800 } 17801 } 17802 } else { 17803 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17804 scheduleWritePackageRestrictionsLocked(userId); 17805 } 17806 } 17807 } 17808 17809 void clearDefaultBrowserIfNeeded(String packageName) { 17810 for (int oneUserId : sUserManager.getUserIds()) { 17811 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17812 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17813 if (packageName.equals(defaultBrowserPackageName)) { 17814 setDefaultBrowserPackageName(null, oneUserId); 17815 } 17816 } 17817 } 17818 17819 @Override 17820 public void resetApplicationPreferences(int userId) { 17821 mContext.enforceCallingOrSelfPermission( 17822 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17823 final long identity = Binder.clearCallingIdentity(); 17824 // writer 17825 try { 17826 synchronized (mPackages) { 17827 clearPackagePreferredActivitiesLPw(null, userId); 17828 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17829 // TODO: We have to reset the default SMS and Phone. This requires 17830 // significant refactoring to keep all default apps in the package 17831 // manager (cleaner but more work) or have the services provide 17832 // callbacks to the package manager to request a default app reset. 17833 applyFactoryDefaultBrowserLPw(userId); 17834 clearIntentFilterVerificationsLPw(userId); 17835 primeDomainVerificationsLPw(userId); 17836 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17837 scheduleWritePackageRestrictionsLocked(userId); 17838 } 17839 resetNetworkPolicies(userId); 17840 } finally { 17841 Binder.restoreCallingIdentity(identity); 17842 } 17843 } 17844 17845 @Override 17846 public int getPreferredActivities(List<IntentFilter> outFilters, 17847 List<ComponentName> outActivities, String packageName) { 17848 17849 int num = 0; 17850 final int userId = UserHandle.getCallingUserId(); 17851 // reader 17852 synchronized (mPackages) { 17853 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17854 if (pir != null) { 17855 final Iterator<PreferredActivity> it = pir.filterIterator(); 17856 while (it.hasNext()) { 17857 final PreferredActivity pa = it.next(); 17858 if (packageName == null 17859 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17860 && pa.mPref.mAlways)) { 17861 if (outFilters != null) { 17862 outFilters.add(new IntentFilter(pa)); 17863 } 17864 if (outActivities != null) { 17865 outActivities.add(pa.mPref.mComponent); 17866 } 17867 } 17868 } 17869 } 17870 } 17871 17872 return num; 17873 } 17874 17875 @Override 17876 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17877 int userId) { 17878 int callingUid = Binder.getCallingUid(); 17879 if (callingUid != Process.SYSTEM_UID) { 17880 throw new SecurityException( 17881 "addPersistentPreferredActivity can only be run by the system"); 17882 } 17883 if (filter.countActions() == 0) { 17884 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17885 return; 17886 } 17887 synchronized (mPackages) { 17888 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17889 ":"); 17890 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17891 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17892 new PersistentPreferredActivity(filter, activity)); 17893 scheduleWritePackageRestrictionsLocked(userId); 17894 postPreferredActivityChangedBroadcast(userId); 17895 } 17896 } 17897 17898 @Override 17899 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17900 int callingUid = Binder.getCallingUid(); 17901 if (callingUid != Process.SYSTEM_UID) { 17902 throw new SecurityException( 17903 "clearPackagePersistentPreferredActivities can only be run by the system"); 17904 } 17905 ArrayList<PersistentPreferredActivity> removed = null; 17906 boolean changed = false; 17907 synchronized (mPackages) { 17908 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17909 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17910 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17911 .valueAt(i); 17912 if (userId != thisUserId) { 17913 continue; 17914 } 17915 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17916 while (it.hasNext()) { 17917 PersistentPreferredActivity ppa = it.next(); 17918 // Mark entry for removal only if it matches the package name. 17919 if (ppa.mComponent.getPackageName().equals(packageName)) { 17920 if (removed == null) { 17921 removed = new ArrayList<PersistentPreferredActivity>(); 17922 } 17923 removed.add(ppa); 17924 } 17925 } 17926 if (removed != null) { 17927 for (int j=0; j<removed.size(); j++) { 17928 PersistentPreferredActivity ppa = removed.get(j); 17929 ppir.removeFilter(ppa); 17930 } 17931 changed = true; 17932 } 17933 } 17934 17935 if (changed) { 17936 scheduleWritePackageRestrictionsLocked(userId); 17937 postPreferredActivityChangedBroadcast(userId); 17938 } 17939 } 17940 } 17941 17942 /** 17943 * Common machinery for picking apart a restored XML blob and passing 17944 * it to a caller-supplied functor to be applied to the running system. 17945 */ 17946 private void restoreFromXml(XmlPullParser parser, int userId, 17947 String expectedStartTag, BlobXmlRestorer functor) 17948 throws IOException, XmlPullParserException { 17949 int type; 17950 while ((type = parser.next()) != XmlPullParser.START_TAG 17951 && type != XmlPullParser.END_DOCUMENT) { 17952 } 17953 if (type != XmlPullParser.START_TAG) { 17954 // oops didn't find a start tag?! 17955 if (DEBUG_BACKUP) { 17956 Slog.e(TAG, "Didn't find start tag during restore"); 17957 } 17958 return; 17959 } 17960Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17961 // this is supposed to be TAG_PREFERRED_BACKUP 17962 if (!expectedStartTag.equals(parser.getName())) { 17963 if (DEBUG_BACKUP) { 17964 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17965 } 17966 return; 17967 } 17968 17969 // skip interfering stuff, then we're aligned with the backing implementation 17970 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17971Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17972 functor.apply(parser, userId); 17973 } 17974 17975 private interface BlobXmlRestorer { 17976 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17977 } 17978 17979 /** 17980 * Non-Binder method, support for the backup/restore mechanism: write the 17981 * full set of preferred activities in its canonical XML format. Returns the 17982 * XML output as a byte array, or null if there is none. 17983 */ 17984 @Override 17985 public byte[] getPreferredActivityBackup(int userId) { 17986 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17987 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17988 } 17989 17990 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17991 try { 17992 final XmlSerializer serializer = new FastXmlSerializer(); 17993 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17994 serializer.startDocument(null, true); 17995 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17996 17997 synchronized (mPackages) { 17998 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17999 } 18000 18001 serializer.endTag(null, TAG_PREFERRED_BACKUP); 18002 serializer.endDocument(); 18003 serializer.flush(); 18004 } catch (Exception e) { 18005 if (DEBUG_BACKUP) { 18006 Slog.e(TAG, "Unable to write preferred activities for backup", e); 18007 } 18008 return null; 18009 } 18010 18011 return dataStream.toByteArray(); 18012 } 18013 18014 @Override 18015 public void restorePreferredActivities(byte[] backup, int userId) { 18016 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18017 throw new SecurityException("Only the system may call restorePreferredActivities()"); 18018 } 18019 18020 try { 18021 final XmlPullParser parser = Xml.newPullParser(); 18022 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18023 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 18024 new BlobXmlRestorer() { 18025 @Override 18026 public void apply(XmlPullParser parser, int userId) 18027 throws XmlPullParserException, IOException { 18028 synchronized (mPackages) { 18029 mSettings.readPreferredActivitiesLPw(parser, userId); 18030 } 18031 } 18032 } ); 18033 } catch (Exception e) { 18034 if (DEBUG_BACKUP) { 18035 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18036 } 18037 } 18038 } 18039 18040 /** 18041 * Non-Binder method, support for the backup/restore mechanism: write the 18042 * default browser (etc) settings in its canonical XML format. Returns the default 18043 * browser XML representation as a byte array, or null if there is none. 18044 */ 18045 @Override 18046 public byte[] getDefaultAppsBackup(int userId) { 18047 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18048 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 18049 } 18050 18051 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18052 try { 18053 final XmlSerializer serializer = new FastXmlSerializer(); 18054 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18055 serializer.startDocument(null, true); 18056 serializer.startTag(null, TAG_DEFAULT_APPS); 18057 18058 synchronized (mPackages) { 18059 mSettings.writeDefaultAppsLPr(serializer, userId); 18060 } 18061 18062 serializer.endTag(null, TAG_DEFAULT_APPS); 18063 serializer.endDocument(); 18064 serializer.flush(); 18065 } catch (Exception e) { 18066 if (DEBUG_BACKUP) { 18067 Slog.e(TAG, "Unable to write default apps for backup", e); 18068 } 18069 return null; 18070 } 18071 18072 return dataStream.toByteArray(); 18073 } 18074 18075 @Override 18076 public void restoreDefaultApps(byte[] backup, int userId) { 18077 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18078 throw new SecurityException("Only the system may call restoreDefaultApps()"); 18079 } 18080 18081 try { 18082 final XmlPullParser parser = Xml.newPullParser(); 18083 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18084 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 18085 new BlobXmlRestorer() { 18086 @Override 18087 public void apply(XmlPullParser parser, int userId) 18088 throws XmlPullParserException, IOException { 18089 synchronized (mPackages) { 18090 mSettings.readDefaultAppsLPw(parser, userId); 18091 } 18092 } 18093 } ); 18094 } catch (Exception e) { 18095 if (DEBUG_BACKUP) { 18096 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 18097 } 18098 } 18099 } 18100 18101 @Override 18102 public byte[] getIntentFilterVerificationBackup(int userId) { 18103 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18104 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 18105 } 18106 18107 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18108 try { 18109 final XmlSerializer serializer = new FastXmlSerializer(); 18110 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18111 serializer.startDocument(null, true); 18112 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 18113 18114 synchronized (mPackages) { 18115 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 18116 } 18117 18118 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 18119 serializer.endDocument(); 18120 serializer.flush(); 18121 } catch (Exception e) { 18122 if (DEBUG_BACKUP) { 18123 Slog.e(TAG, "Unable to write default apps for backup", e); 18124 } 18125 return null; 18126 } 18127 18128 return dataStream.toByteArray(); 18129 } 18130 18131 @Override 18132 public void restoreIntentFilterVerification(byte[] backup, int userId) { 18133 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18134 throw new SecurityException("Only the system may call restorePreferredActivities()"); 18135 } 18136 18137 try { 18138 final XmlPullParser parser = Xml.newPullParser(); 18139 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18140 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 18141 new BlobXmlRestorer() { 18142 @Override 18143 public void apply(XmlPullParser parser, int userId) 18144 throws XmlPullParserException, IOException { 18145 synchronized (mPackages) { 18146 mSettings.readAllDomainVerificationsLPr(parser, userId); 18147 mSettings.writeLPr(); 18148 } 18149 } 18150 } ); 18151 } catch (Exception e) { 18152 if (DEBUG_BACKUP) { 18153 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18154 } 18155 } 18156 } 18157 18158 @Override 18159 public byte[] getPermissionGrantBackup(int userId) { 18160 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18161 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 18162 } 18163 18164 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 18165 try { 18166 final XmlSerializer serializer = new FastXmlSerializer(); 18167 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 18168 serializer.startDocument(null, true); 18169 serializer.startTag(null, TAG_PERMISSION_BACKUP); 18170 18171 synchronized (mPackages) { 18172 serializeRuntimePermissionGrantsLPr(serializer, userId); 18173 } 18174 18175 serializer.endTag(null, TAG_PERMISSION_BACKUP); 18176 serializer.endDocument(); 18177 serializer.flush(); 18178 } catch (Exception e) { 18179 if (DEBUG_BACKUP) { 18180 Slog.e(TAG, "Unable to write default apps for backup", e); 18181 } 18182 return null; 18183 } 18184 18185 return dataStream.toByteArray(); 18186 } 18187 18188 @Override 18189 public void restorePermissionGrants(byte[] backup, int userId) { 18190 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 18191 throw new SecurityException("Only the system may call restorePermissionGrants()"); 18192 } 18193 18194 try { 18195 final XmlPullParser parser = Xml.newPullParser(); 18196 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 18197 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 18198 new BlobXmlRestorer() { 18199 @Override 18200 public void apply(XmlPullParser parser, int userId) 18201 throws XmlPullParserException, IOException { 18202 synchronized (mPackages) { 18203 processRestoredPermissionGrantsLPr(parser, userId); 18204 } 18205 } 18206 } ); 18207 } catch (Exception e) { 18208 if (DEBUG_BACKUP) { 18209 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 18210 } 18211 } 18212 } 18213 18214 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 18215 throws IOException { 18216 serializer.startTag(null, TAG_ALL_GRANTS); 18217 18218 final int N = mSettings.mPackages.size(); 18219 for (int i = 0; i < N; i++) { 18220 final PackageSetting ps = mSettings.mPackages.valueAt(i); 18221 boolean pkgGrantsKnown = false; 18222 18223 PermissionsState packagePerms = ps.getPermissionsState(); 18224 18225 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 18226 final int grantFlags = state.getFlags(); 18227 // only look at grants that are not system/policy fixed 18228 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 18229 final boolean isGranted = state.isGranted(); 18230 // And only back up the user-twiddled state bits 18231 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 18232 final String packageName = mSettings.mPackages.keyAt(i); 18233 if (!pkgGrantsKnown) { 18234 serializer.startTag(null, TAG_GRANT); 18235 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 18236 pkgGrantsKnown = true; 18237 } 18238 18239 final boolean userSet = 18240 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 18241 final boolean userFixed = 18242 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 18243 final boolean revoke = 18244 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 18245 18246 serializer.startTag(null, TAG_PERMISSION); 18247 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 18248 if (isGranted) { 18249 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 18250 } 18251 if (userSet) { 18252 serializer.attribute(null, ATTR_USER_SET, "true"); 18253 } 18254 if (userFixed) { 18255 serializer.attribute(null, ATTR_USER_FIXED, "true"); 18256 } 18257 if (revoke) { 18258 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 18259 } 18260 serializer.endTag(null, TAG_PERMISSION); 18261 } 18262 } 18263 } 18264 18265 if (pkgGrantsKnown) { 18266 serializer.endTag(null, TAG_GRANT); 18267 } 18268 } 18269 18270 serializer.endTag(null, TAG_ALL_GRANTS); 18271 } 18272 18273 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 18274 throws XmlPullParserException, IOException { 18275 String pkgName = null; 18276 int outerDepth = parser.getDepth(); 18277 int type; 18278 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 18279 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 18280 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18281 continue; 18282 } 18283 18284 final String tagName = parser.getName(); 18285 if (tagName.equals(TAG_GRANT)) { 18286 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18287 if (DEBUG_BACKUP) { 18288 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18289 } 18290 } else if (tagName.equals(TAG_PERMISSION)) { 18291 18292 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18293 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18294 18295 int newFlagSet = 0; 18296 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18297 newFlagSet |= FLAG_PERMISSION_USER_SET; 18298 } 18299 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18300 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18301 } 18302 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18303 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18304 } 18305 if (DEBUG_BACKUP) { 18306 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18307 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18308 } 18309 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18310 if (ps != null) { 18311 // Already installed so we apply the grant immediately 18312 if (DEBUG_BACKUP) { 18313 Slog.v(TAG, " + already installed; applying"); 18314 } 18315 PermissionsState perms = ps.getPermissionsState(); 18316 BasePermission bp = mSettings.mPermissions.get(permName); 18317 if (bp != null) { 18318 if (isGranted) { 18319 perms.grantRuntimePermission(bp, userId); 18320 } 18321 if (newFlagSet != 0) { 18322 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18323 } 18324 } 18325 } else { 18326 // Need to wait for post-restore install to apply the grant 18327 if (DEBUG_BACKUP) { 18328 Slog.v(TAG, " - not yet installed; saving for later"); 18329 } 18330 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18331 isGranted, newFlagSet, userId); 18332 } 18333 } else { 18334 PackageManagerService.reportSettingsProblem(Log.WARN, 18335 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18336 XmlUtils.skipCurrentTag(parser); 18337 } 18338 } 18339 18340 scheduleWriteSettingsLocked(); 18341 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18342 } 18343 18344 @Override 18345 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18346 int sourceUserId, int targetUserId, int flags) { 18347 mContext.enforceCallingOrSelfPermission( 18348 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18349 int callingUid = Binder.getCallingUid(); 18350 enforceOwnerRights(ownerPackage, callingUid); 18351 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18352 if (intentFilter.countActions() == 0) { 18353 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18354 return; 18355 } 18356 synchronized (mPackages) { 18357 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18358 ownerPackage, targetUserId, flags); 18359 CrossProfileIntentResolver resolver = 18360 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18361 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18362 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18363 if (existing != null) { 18364 int size = existing.size(); 18365 for (int i = 0; i < size; i++) { 18366 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18367 return; 18368 } 18369 } 18370 } 18371 resolver.addFilter(newFilter); 18372 scheduleWritePackageRestrictionsLocked(sourceUserId); 18373 } 18374 } 18375 18376 @Override 18377 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18378 mContext.enforceCallingOrSelfPermission( 18379 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18380 int callingUid = Binder.getCallingUid(); 18381 enforceOwnerRights(ownerPackage, callingUid); 18382 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18383 synchronized (mPackages) { 18384 CrossProfileIntentResolver resolver = 18385 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18386 ArraySet<CrossProfileIntentFilter> set = 18387 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18388 for (CrossProfileIntentFilter filter : set) { 18389 if (filter.getOwnerPackage().equals(ownerPackage)) { 18390 resolver.removeFilter(filter); 18391 } 18392 } 18393 scheduleWritePackageRestrictionsLocked(sourceUserId); 18394 } 18395 } 18396 18397 // Enforcing that callingUid is owning pkg on userId 18398 private void enforceOwnerRights(String pkg, int callingUid) { 18399 // The system owns everything. 18400 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18401 return; 18402 } 18403 int callingUserId = UserHandle.getUserId(callingUid); 18404 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18405 if (pi == null) { 18406 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18407 + callingUserId); 18408 } 18409 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18410 throw new SecurityException("Calling uid " + callingUid 18411 + " does not own package " + pkg); 18412 } 18413 } 18414 18415 @Override 18416 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18417 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18418 } 18419 18420 private Intent getHomeIntent() { 18421 Intent intent = new Intent(Intent.ACTION_MAIN); 18422 intent.addCategory(Intent.CATEGORY_HOME); 18423 intent.addCategory(Intent.CATEGORY_DEFAULT); 18424 return intent; 18425 } 18426 18427 private IntentFilter getHomeFilter() { 18428 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18429 filter.addCategory(Intent.CATEGORY_HOME); 18430 filter.addCategory(Intent.CATEGORY_DEFAULT); 18431 return filter; 18432 } 18433 18434 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18435 int userId) { 18436 Intent intent = getHomeIntent(); 18437 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18438 PackageManager.GET_META_DATA, userId); 18439 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18440 true, false, false, userId); 18441 18442 allHomeCandidates.clear(); 18443 if (list != null) { 18444 for (ResolveInfo ri : list) { 18445 allHomeCandidates.add(ri); 18446 } 18447 } 18448 return (preferred == null || preferred.activityInfo == null) 18449 ? null 18450 : new ComponentName(preferred.activityInfo.packageName, 18451 preferred.activityInfo.name); 18452 } 18453 18454 @Override 18455 public void setHomeActivity(ComponentName comp, int userId) { 18456 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18457 getHomeActivitiesAsUser(homeActivities, userId); 18458 18459 boolean found = false; 18460 18461 final int size = homeActivities.size(); 18462 final ComponentName[] set = new ComponentName[size]; 18463 for (int i = 0; i < size; i++) { 18464 final ResolveInfo candidate = homeActivities.get(i); 18465 final ActivityInfo info = candidate.activityInfo; 18466 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18467 set[i] = activityName; 18468 if (!found && activityName.equals(comp)) { 18469 found = true; 18470 } 18471 } 18472 if (!found) { 18473 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18474 + userId); 18475 } 18476 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18477 set, comp, userId); 18478 } 18479 18480 private @Nullable String getSetupWizardPackageName() { 18481 final Intent intent = new Intent(Intent.ACTION_MAIN); 18482 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18483 18484 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18485 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18486 | MATCH_DISABLED_COMPONENTS, 18487 UserHandle.myUserId()); 18488 if (matches.size() == 1) { 18489 return matches.get(0).getComponentInfo().packageName; 18490 } else { 18491 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18492 + ": matches=" + matches); 18493 return null; 18494 } 18495 } 18496 18497 private @Nullable String getStorageManagerPackageName() { 18498 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18499 18500 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18501 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18502 | MATCH_DISABLED_COMPONENTS, 18503 UserHandle.myUserId()); 18504 if (matches.size() == 1) { 18505 return matches.get(0).getComponentInfo().packageName; 18506 } else { 18507 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18508 + matches.size() + ": matches=" + matches); 18509 return null; 18510 } 18511 } 18512 18513 @Override 18514 public void setApplicationEnabledSetting(String appPackageName, 18515 int newState, int flags, int userId, String callingPackage) { 18516 if (!sUserManager.exists(userId)) return; 18517 if (callingPackage == null) { 18518 callingPackage = Integer.toString(Binder.getCallingUid()); 18519 } 18520 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18521 } 18522 18523 @Override 18524 public void setComponentEnabledSetting(ComponentName componentName, 18525 int newState, int flags, int userId) { 18526 if (!sUserManager.exists(userId)) return; 18527 setEnabledSetting(componentName.getPackageName(), 18528 componentName.getClassName(), newState, flags, userId, null); 18529 } 18530 18531 private void setEnabledSetting(final String packageName, String className, int newState, 18532 final int flags, int userId, String callingPackage) { 18533 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18534 || newState == COMPONENT_ENABLED_STATE_ENABLED 18535 || newState == COMPONENT_ENABLED_STATE_DISABLED 18536 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18537 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18538 throw new IllegalArgumentException("Invalid new component state: " 18539 + newState); 18540 } 18541 PackageSetting pkgSetting; 18542 final int uid = Binder.getCallingUid(); 18543 final int permission; 18544 if (uid == Process.SYSTEM_UID) { 18545 permission = PackageManager.PERMISSION_GRANTED; 18546 } else { 18547 permission = mContext.checkCallingOrSelfPermission( 18548 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18549 } 18550 enforceCrossUserPermission(uid, userId, 18551 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18552 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18553 boolean sendNow = false; 18554 boolean isApp = (className == null); 18555 String componentName = isApp ? packageName : className; 18556 int packageUid = -1; 18557 ArrayList<String> components; 18558 18559 // writer 18560 synchronized (mPackages) { 18561 pkgSetting = mSettings.mPackages.get(packageName); 18562 if (pkgSetting == null) { 18563 if (className == null) { 18564 throw new IllegalArgumentException("Unknown package: " + packageName); 18565 } 18566 throw new IllegalArgumentException( 18567 "Unknown component: " + packageName + "/" + className); 18568 } 18569 } 18570 18571 // Limit who can change which apps 18572 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18573 // Don't allow apps that don't have permission to modify other apps 18574 if (!allowedByPermission) { 18575 throw new SecurityException( 18576 "Permission Denial: attempt to change component state from pid=" 18577 + Binder.getCallingPid() 18578 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18579 } 18580 // Don't allow changing protected packages. 18581 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18582 throw new SecurityException("Cannot disable a protected package: " + packageName); 18583 } 18584 } 18585 18586 synchronized (mPackages) { 18587 if (uid == Process.SHELL_UID 18588 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18589 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18590 // unless it is a test package. 18591 int oldState = pkgSetting.getEnabled(userId); 18592 if (className == null 18593 && 18594 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18595 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18596 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18597 && 18598 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18599 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18600 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18601 // ok 18602 } else { 18603 throw new SecurityException( 18604 "Shell cannot change component state for " + packageName + "/" 18605 + className + " to " + newState); 18606 } 18607 } 18608 if (className == null) { 18609 // We're dealing with an application/package level state change 18610 if (pkgSetting.getEnabled(userId) == newState) { 18611 // Nothing to do 18612 return; 18613 } 18614 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18615 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18616 // Don't care about who enables an app. 18617 callingPackage = null; 18618 } 18619 pkgSetting.setEnabled(newState, userId, callingPackage); 18620 // pkgSetting.pkg.mSetEnabled = newState; 18621 } else { 18622 // We're dealing with a component level state change 18623 // First, verify that this is a valid class name. 18624 PackageParser.Package pkg = pkgSetting.pkg; 18625 if (pkg == null || !pkg.hasComponentClassName(className)) { 18626 if (pkg != null && 18627 pkg.applicationInfo.targetSdkVersion >= 18628 Build.VERSION_CODES.JELLY_BEAN) { 18629 throw new IllegalArgumentException("Component class " + className 18630 + " does not exist in " + packageName); 18631 } else { 18632 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18633 + className + " does not exist in " + packageName); 18634 } 18635 } 18636 switch (newState) { 18637 case COMPONENT_ENABLED_STATE_ENABLED: 18638 if (!pkgSetting.enableComponentLPw(className, userId)) { 18639 return; 18640 } 18641 break; 18642 case COMPONENT_ENABLED_STATE_DISABLED: 18643 if (!pkgSetting.disableComponentLPw(className, userId)) { 18644 return; 18645 } 18646 break; 18647 case COMPONENT_ENABLED_STATE_DEFAULT: 18648 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18649 return; 18650 } 18651 break; 18652 default: 18653 Slog.e(TAG, "Invalid new component state: " + newState); 18654 return; 18655 } 18656 } 18657 scheduleWritePackageRestrictionsLocked(userId); 18658 components = mPendingBroadcasts.get(userId, packageName); 18659 final boolean newPackage = components == null; 18660 if (newPackage) { 18661 components = new ArrayList<String>(); 18662 } 18663 if (!components.contains(componentName)) { 18664 components.add(componentName); 18665 } 18666 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18667 sendNow = true; 18668 // Purge entry from pending broadcast list if another one exists already 18669 // since we are sending one right away. 18670 mPendingBroadcasts.remove(userId, packageName); 18671 } else { 18672 if (newPackage) { 18673 mPendingBroadcasts.put(userId, packageName, components); 18674 } 18675 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18676 // Schedule a message 18677 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18678 } 18679 } 18680 } 18681 18682 long callingId = Binder.clearCallingIdentity(); 18683 try { 18684 if (sendNow) { 18685 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18686 sendPackageChangedBroadcast(packageName, 18687 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18688 } 18689 } finally { 18690 Binder.restoreCallingIdentity(callingId); 18691 } 18692 } 18693 18694 @Override 18695 public void flushPackageRestrictionsAsUser(int userId) { 18696 if (!sUserManager.exists(userId)) { 18697 return; 18698 } 18699 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18700 false /* checkShell */, "flushPackageRestrictions"); 18701 synchronized (mPackages) { 18702 mSettings.writePackageRestrictionsLPr(userId); 18703 mDirtyUsers.remove(userId); 18704 if (mDirtyUsers.isEmpty()) { 18705 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18706 } 18707 } 18708 } 18709 18710 private void sendPackageChangedBroadcast(String packageName, 18711 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18712 if (DEBUG_INSTALL) 18713 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18714 + componentNames); 18715 Bundle extras = new Bundle(4); 18716 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18717 String nameList[] = new String[componentNames.size()]; 18718 componentNames.toArray(nameList); 18719 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18720 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18721 extras.putInt(Intent.EXTRA_UID, packageUid); 18722 // If this is not reporting a change of the overall package, then only send it 18723 // to registered receivers. We don't want to launch a swath of apps for every 18724 // little component state change. 18725 final int flags = !componentNames.contains(packageName) 18726 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18727 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18728 new int[] {UserHandle.getUserId(packageUid)}); 18729 } 18730 18731 @Override 18732 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18733 if (!sUserManager.exists(userId)) return; 18734 final int uid = Binder.getCallingUid(); 18735 final int permission = mContext.checkCallingOrSelfPermission( 18736 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18737 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18738 enforceCrossUserPermission(uid, userId, 18739 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18740 // writer 18741 synchronized (mPackages) { 18742 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18743 allowedByPermission, uid, userId)) { 18744 scheduleWritePackageRestrictionsLocked(userId); 18745 } 18746 } 18747 } 18748 18749 @Override 18750 public String getInstallerPackageName(String packageName) { 18751 // reader 18752 synchronized (mPackages) { 18753 return mSettings.getInstallerPackageNameLPr(packageName); 18754 } 18755 } 18756 18757 public boolean isOrphaned(String packageName) { 18758 // reader 18759 synchronized (mPackages) { 18760 return mSettings.isOrphaned(packageName); 18761 } 18762 } 18763 18764 @Override 18765 public int getApplicationEnabledSetting(String packageName, int userId) { 18766 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18767 int uid = Binder.getCallingUid(); 18768 enforceCrossUserPermission(uid, userId, 18769 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18770 // reader 18771 synchronized (mPackages) { 18772 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18773 } 18774 } 18775 18776 @Override 18777 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18778 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18779 int uid = Binder.getCallingUid(); 18780 enforceCrossUserPermission(uid, userId, 18781 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18782 // reader 18783 synchronized (mPackages) { 18784 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18785 } 18786 } 18787 18788 @Override 18789 public void enterSafeMode() { 18790 enforceSystemOrRoot("Only the system can request entering safe mode"); 18791 18792 if (!mSystemReady) { 18793 mSafeMode = true; 18794 } 18795 } 18796 18797 @Override 18798 public void systemReady() { 18799 mSystemReady = true; 18800 18801 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18802 // disabled after already being started. 18803 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18804 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18805 18806 // Read the compatibilty setting when the system is ready. 18807 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18808 mContext.getContentResolver(), 18809 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18810 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18811 if (DEBUG_SETTINGS) { 18812 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18813 } 18814 18815 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18816 18817 synchronized (mPackages) { 18818 // Verify that all of the preferred activity components actually 18819 // exist. It is possible for applications to be updated and at 18820 // that point remove a previously declared activity component that 18821 // had been set as a preferred activity. We try to clean this up 18822 // the next time we encounter that preferred activity, but it is 18823 // possible for the user flow to never be able to return to that 18824 // situation so here we do a sanity check to make sure we haven't 18825 // left any junk around. 18826 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18827 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18828 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18829 removed.clear(); 18830 for (PreferredActivity pa : pir.filterSet()) { 18831 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18832 removed.add(pa); 18833 } 18834 } 18835 if (removed.size() > 0) { 18836 for (int r=0; r<removed.size(); r++) { 18837 PreferredActivity pa = removed.get(r); 18838 Slog.w(TAG, "Removing dangling preferred activity: " 18839 + pa.mPref.mComponent); 18840 pir.removeFilter(pa); 18841 } 18842 mSettings.writePackageRestrictionsLPr( 18843 mSettings.mPreferredActivities.keyAt(i)); 18844 } 18845 } 18846 18847 for (int userId : UserManagerService.getInstance().getUserIds()) { 18848 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18849 grantPermissionsUserIds = ArrayUtils.appendInt( 18850 grantPermissionsUserIds, userId); 18851 } 18852 } 18853 } 18854 sUserManager.systemReady(); 18855 18856 // If we upgraded grant all default permissions before kicking off. 18857 for (int userId : grantPermissionsUserIds) { 18858 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18859 } 18860 18861 // If we did not grant default permissions, we preload from this the 18862 // default permission exceptions lazily to ensure we don't hit the 18863 // disk on a new user creation. 18864 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18865 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18866 } 18867 18868 // Kick off any messages waiting for system ready 18869 if (mPostSystemReadyMessages != null) { 18870 for (Message msg : mPostSystemReadyMessages) { 18871 msg.sendToTarget(); 18872 } 18873 mPostSystemReadyMessages = null; 18874 } 18875 18876 // Watch for external volumes that come and go over time 18877 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18878 storage.registerListener(mStorageListener); 18879 18880 mInstallerService.systemReady(); 18881 mPackageDexOptimizer.systemReady(); 18882 18883 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18884 StorageManagerInternal.class); 18885 StorageManagerInternal.addExternalStoragePolicy( 18886 new StorageManagerInternal.ExternalStorageMountPolicy() { 18887 @Override 18888 public int getMountMode(int uid, String packageName) { 18889 if (Process.isIsolated(uid)) { 18890 return Zygote.MOUNT_EXTERNAL_NONE; 18891 } 18892 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18893 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18894 } 18895 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18896 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18897 } 18898 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18899 return Zygote.MOUNT_EXTERNAL_READ; 18900 } 18901 return Zygote.MOUNT_EXTERNAL_WRITE; 18902 } 18903 18904 @Override 18905 public boolean hasExternalStorage(int uid, String packageName) { 18906 return true; 18907 } 18908 }); 18909 18910 // Now that we're mostly running, clean up stale users and apps 18911 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18912 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18913 } 18914 18915 @Override 18916 public boolean isSafeMode() { 18917 return mSafeMode; 18918 } 18919 18920 @Override 18921 public boolean hasSystemUidErrors() { 18922 return mHasSystemUidErrors; 18923 } 18924 18925 static String arrayToString(int[] array) { 18926 StringBuffer buf = new StringBuffer(128); 18927 buf.append('['); 18928 if (array != null) { 18929 for (int i=0; i<array.length; i++) { 18930 if (i > 0) buf.append(", "); 18931 buf.append(array[i]); 18932 } 18933 } 18934 buf.append(']'); 18935 return buf.toString(); 18936 } 18937 18938 static class DumpState { 18939 public static final int DUMP_LIBS = 1 << 0; 18940 public static final int DUMP_FEATURES = 1 << 1; 18941 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18942 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18943 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18944 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18945 public static final int DUMP_PERMISSIONS = 1 << 6; 18946 public static final int DUMP_PACKAGES = 1 << 7; 18947 public static final int DUMP_SHARED_USERS = 1 << 8; 18948 public static final int DUMP_MESSAGES = 1 << 9; 18949 public static final int DUMP_PROVIDERS = 1 << 10; 18950 public static final int DUMP_VERIFIERS = 1 << 11; 18951 public static final int DUMP_PREFERRED = 1 << 12; 18952 public static final int DUMP_PREFERRED_XML = 1 << 13; 18953 public static final int DUMP_KEYSETS = 1 << 14; 18954 public static final int DUMP_VERSION = 1 << 15; 18955 public static final int DUMP_INSTALLS = 1 << 16; 18956 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18957 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18958 public static final int DUMP_FROZEN = 1 << 19; 18959 public static final int DUMP_DEXOPT = 1 << 20; 18960 public static final int DUMP_COMPILER_STATS = 1 << 21; 18961 18962 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18963 18964 private int mTypes; 18965 18966 private int mOptions; 18967 18968 private boolean mTitlePrinted; 18969 18970 private SharedUserSetting mSharedUser; 18971 18972 public boolean isDumping(int type) { 18973 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18974 return true; 18975 } 18976 18977 return (mTypes & type) != 0; 18978 } 18979 18980 public void setDump(int type) { 18981 mTypes |= type; 18982 } 18983 18984 public boolean isOptionEnabled(int option) { 18985 return (mOptions & option) != 0; 18986 } 18987 18988 public void setOptionEnabled(int option) { 18989 mOptions |= option; 18990 } 18991 18992 public boolean onTitlePrinted() { 18993 final boolean printed = mTitlePrinted; 18994 mTitlePrinted = true; 18995 return printed; 18996 } 18997 18998 public boolean getTitlePrinted() { 18999 return mTitlePrinted; 19000 } 19001 19002 public void setTitlePrinted(boolean enabled) { 19003 mTitlePrinted = enabled; 19004 } 19005 19006 public SharedUserSetting getSharedUser() { 19007 return mSharedUser; 19008 } 19009 19010 public void setSharedUser(SharedUserSetting user) { 19011 mSharedUser = user; 19012 } 19013 } 19014 19015 @Override 19016 public void onShellCommand(FileDescriptor in, FileDescriptor out, 19017 FileDescriptor err, String[] args, ShellCallback callback, 19018 ResultReceiver resultReceiver) { 19019 (new PackageManagerShellCommand(this)).exec( 19020 this, in, out, err, args, callback, resultReceiver); 19021 } 19022 19023 @Override 19024 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 19025 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 19026 != PackageManager.PERMISSION_GRANTED) { 19027 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 19028 + Binder.getCallingPid() 19029 + ", uid=" + Binder.getCallingUid() 19030 + " without permission " 19031 + android.Manifest.permission.DUMP); 19032 return; 19033 } 19034 19035 DumpState dumpState = new DumpState(); 19036 boolean fullPreferred = false; 19037 boolean checkin = false; 19038 19039 String packageName = null; 19040 ArraySet<String> permissionNames = null; 19041 19042 int opti = 0; 19043 while (opti < args.length) { 19044 String opt = args[opti]; 19045 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 19046 break; 19047 } 19048 opti++; 19049 19050 if ("-a".equals(opt)) { 19051 // Right now we only know how to print all. 19052 } else if ("-h".equals(opt)) { 19053 pw.println("Package manager dump options:"); 19054 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 19055 pw.println(" --checkin: dump for a checkin"); 19056 pw.println(" -f: print details of intent filters"); 19057 pw.println(" -h: print this help"); 19058 pw.println(" cmd may be one of:"); 19059 pw.println(" l[ibraries]: list known shared libraries"); 19060 pw.println(" f[eatures]: list device features"); 19061 pw.println(" k[eysets]: print known keysets"); 19062 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 19063 pw.println(" perm[issions]: dump permissions"); 19064 pw.println(" permission [name ...]: dump declaration and use of given permission"); 19065 pw.println(" pref[erred]: print preferred package settings"); 19066 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 19067 pw.println(" prov[iders]: dump content providers"); 19068 pw.println(" p[ackages]: dump installed packages"); 19069 pw.println(" s[hared-users]: dump shared user IDs"); 19070 pw.println(" m[essages]: print collected runtime messages"); 19071 pw.println(" v[erifiers]: print package verifier info"); 19072 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 19073 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 19074 pw.println(" version: print database version info"); 19075 pw.println(" write: write current settings now"); 19076 pw.println(" installs: details about install sessions"); 19077 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 19078 pw.println(" dexopt: dump dexopt state"); 19079 pw.println(" compiler-stats: dump compiler statistics"); 19080 pw.println(" <package.name>: info about given package"); 19081 return; 19082 } else if ("--checkin".equals(opt)) { 19083 checkin = true; 19084 } else if ("-f".equals(opt)) { 19085 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19086 } else { 19087 pw.println("Unknown argument: " + opt + "; use -h for help"); 19088 } 19089 } 19090 19091 // Is the caller requesting to dump a particular piece of data? 19092 if (opti < args.length) { 19093 String cmd = args[opti]; 19094 opti++; 19095 // Is this a package name? 19096 if ("android".equals(cmd) || cmd.contains(".")) { 19097 packageName = cmd; 19098 // When dumping a single package, we always dump all of its 19099 // filter information since the amount of data will be reasonable. 19100 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 19101 } else if ("check-permission".equals(cmd)) { 19102 if (opti >= args.length) { 19103 pw.println("Error: check-permission missing permission argument"); 19104 return; 19105 } 19106 String perm = args[opti]; 19107 opti++; 19108 if (opti >= args.length) { 19109 pw.println("Error: check-permission missing package argument"); 19110 return; 19111 } 19112 String pkg = args[opti]; 19113 opti++; 19114 int user = UserHandle.getUserId(Binder.getCallingUid()); 19115 if (opti < args.length) { 19116 try { 19117 user = Integer.parseInt(args[opti]); 19118 } catch (NumberFormatException e) { 19119 pw.println("Error: check-permission user argument is not a number: " 19120 + args[opti]); 19121 return; 19122 } 19123 } 19124 pw.println(checkPermission(perm, pkg, user)); 19125 return; 19126 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 19127 dumpState.setDump(DumpState.DUMP_LIBS); 19128 } else if ("f".equals(cmd) || "features".equals(cmd)) { 19129 dumpState.setDump(DumpState.DUMP_FEATURES); 19130 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 19131 if (opti >= args.length) { 19132 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 19133 | DumpState.DUMP_SERVICE_RESOLVERS 19134 | DumpState.DUMP_RECEIVER_RESOLVERS 19135 | DumpState.DUMP_CONTENT_RESOLVERS); 19136 } else { 19137 while (opti < args.length) { 19138 String name = args[opti]; 19139 if ("a".equals(name) || "activity".equals(name)) { 19140 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 19141 } else if ("s".equals(name) || "service".equals(name)) { 19142 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 19143 } else if ("r".equals(name) || "receiver".equals(name)) { 19144 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 19145 } else if ("c".equals(name) || "content".equals(name)) { 19146 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 19147 } else { 19148 pw.println("Error: unknown resolver table type: " + name); 19149 return; 19150 } 19151 opti++; 19152 } 19153 } 19154 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 19155 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 19156 } else if ("permission".equals(cmd)) { 19157 if (opti >= args.length) { 19158 pw.println("Error: permission requires permission name"); 19159 return; 19160 } 19161 permissionNames = new ArraySet<>(); 19162 while (opti < args.length) { 19163 permissionNames.add(args[opti]); 19164 opti++; 19165 } 19166 dumpState.setDump(DumpState.DUMP_PERMISSIONS 19167 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 19168 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 19169 dumpState.setDump(DumpState.DUMP_PREFERRED); 19170 } else if ("preferred-xml".equals(cmd)) { 19171 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 19172 if (opti < args.length && "--full".equals(args[opti])) { 19173 fullPreferred = true; 19174 opti++; 19175 } 19176 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 19177 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 19178 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 19179 dumpState.setDump(DumpState.DUMP_PACKAGES); 19180 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 19181 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 19182 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 19183 dumpState.setDump(DumpState.DUMP_PROVIDERS); 19184 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 19185 dumpState.setDump(DumpState.DUMP_MESSAGES); 19186 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 19187 dumpState.setDump(DumpState.DUMP_VERIFIERS); 19188 } else if ("i".equals(cmd) || "ifv".equals(cmd) 19189 || "intent-filter-verifiers".equals(cmd)) { 19190 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 19191 } else if ("version".equals(cmd)) { 19192 dumpState.setDump(DumpState.DUMP_VERSION); 19193 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 19194 dumpState.setDump(DumpState.DUMP_KEYSETS); 19195 } else if ("installs".equals(cmd)) { 19196 dumpState.setDump(DumpState.DUMP_INSTALLS); 19197 } else if ("frozen".equals(cmd)) { 19198 dumpState.setDump(DumpState.DUMP_FROZEN); 19199 } else if ("dexopt".equals(cmd)) { 19200 dumpState.setDump(DumpState.DUMP_DEXOPT); 19201 } else if ("compiler-stats".equals(cmd)) { 19202 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 19203 } else if ("write".equals(cmd)) { 19204 synchronized (mPackages) { 19205 mSettings.writeLPr(); 19206 pw.println("Settings written."); 19207 return; 19208 } 19209 } 19210 } 19211 19212 if (checkin) { 19213 pw.println("vers,1"); 19214 } 19215 19216 // reader 19217 synchronized (mPackages) { 19218 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 19219 if (!checkin) { 19220 if (dumpState.onTitlePrinted()) 19221 pw.println(); 19222 pw.println("Database versions:"); 19223 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 19224 } 19225 } 19226 19227 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 19228 if (!checkin) { 19229 if (dumpState.onTitlePrinted()) 19230 pw.println(); 19231 pw.println("Verifiers:"); 19232 pw.print(" Required: "); 19233 pw.print(mRequiredVerifierPackage); 19234 pw.print(" (uid="); 19235 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19236 UserHandle.USER_SYSTEM)); 19237 pw.println(")"); 19238 } else if (mRequiredVerifierPackage != null) { 19239 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 19240 pw.print(","); 19241 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 19242 UserHandle.USER_SYSTEM)); 19243 } 19244 } 19245 19246 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 19247 packageName == null) { 19248 if (mIntentFilterVerifierComponent != null) { 19249 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 19250 if (!checkin) { 19251 if (dumpState.onTitlePrinted()) 19252 pw.println(); 19253 pw.println("Intent Filter Verifier:"); 19254 pw.print(" Using: "); 19255 pw.print(verifierPackageName); 19256 pw.print(" (uid="); 19257 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19258 UserHandle.USER_SYSTEM)); 19259 pw.println(")"); 19260 } else if (verifierPackageName != null) { 19261 pw.print("ifv,"); pw.print(verifierPackageName); 19262 pw.print(","); 19263 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 19264 UserHandle.USER_SYSTEM)); 19265 } 19266 } else { 19267 pw.println(); 19268 pw.println("No Intent Filter Verifier available!"); 19269 } 19270 } 19271 19272 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 19273 boolean printedHeader = false; 19274 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 19275 while (it.hasNext()) { 19276 String name = it.next(); 19277 SharedLibraryEntry ent = mSharedLibraries.get(name); 19278 if (!checkin) { 19279 if (!printedHeader) { 19280 if (dumpState.onTitlePrinted()) 19281 pw.println(); 19282 pw.println("Libraries:"); 19283 printedHeader = true; 19284 } 19285 pw.print(" "); 19286 } else { 19287 pw.print("lib,"); 19288 } 19289 pw.print(name); 19290 if (!checkin) { 19291 pw.print(" -> "); 19292 } 19293 if (ent.path != null) { 19294 if (!checkin) { 19295 pw.print("(jar) "); 19296 pw.print(ent.path); 19297 } else { 19298 pw.print(",jar,"); 19299 pw.print(ent.path); 19300 } 19301 } else { 19302 if (!checkin) { 19303 pw.print("(apk) "); 19304 pw.print(ent.apk); 19305 } else { 19306 pw.print(",apk,"); 19307 pw.print(ent.apk); 19308 } 19309 } 19310 pw.println(); 19311 } 19312 } 19313 19314 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19315 if (dumpState.onTitlePrinted()) 19316 pw.println(); 19317 if (!checkin) { 19318 pw.println("Features:"); 19319 } 19320 19321 for (FeatureInfo feat : mAvailableFeatures.values()) { 19322 if (checkin) { 19323 pw.print("feat,"); 19324 pw.print(feat.name); 19325 pw.print(","); 19326 pw.println(feat.version); 19327 } else { 19328 pw.print(" "); 19329 pw.print(feat.name); 19330 if (feat.version > 0) { 19331 pw.print(" version="); 19332 pw.print(feat.version); 19333 } 19334 pw.println(); 19335 } 19336 } 19337 } 19338 19339 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19340 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19341 : "Activity Resolver Table:", " ", packageName, 19342 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19343 dumpState.setTitlePrinted(true); 19344 } 19345 } 19346 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19347 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19348 : "Receiver Resolver Table:", " ", packageName, 19349 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19350 dumpState.setTitlePrinted(true); 19351 } 19352 } 19353 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19354 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19355 : "Service Resolver Table:", " ", packageName, 19356 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19357 dumpState.setTitlePrinted(true); 19358 } 19359 } 19360 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19361 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19362 : "Provider Resolver Table:", " ", packageName, 19363 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19364 dumpState.setTitlePrinted(true); 19365 } 19366 } 19367 19368 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19369 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19370 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19371 int user = mSettings.mPreferredActivities.keyAt(i); 19372 if (pir.dump(pw, 19373 dumpState.getTitlePrinted() 19374 ? "\nPreferred Activities User " + user + ":" 19375 : "Preferred Activities User " + user + ":", " ", 19376 packageName, true, false)) { 19377 dumpState.setTitlePrinted(true); 19378 } 19379 } 19380 } 19381 19382 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19383 pw.flush(); 19384 FileOutputStream fout = new FileOutputStream(fd); 19385 BufferedOutputStream str = new BufferedOutputStream(fout); 19386 XmlSerializer serializer = new FastXmlSerializer(); 19387 try { 19388 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19389 serializer.startDocument(null, true); 19390 serializer.setFeature( 19391 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19392 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19393 serializer.endDocument(); 19394 serializer.flush(); 19395 } catch (IllegalArgumentException e) { 19396 pw.println("Failed writing: " + e); 19397 } catch (IllegalStateException e) { 19398 pw.println("Failed writing: " + e); 19399 } catch (IOException e) { 19400 pw.println("Failed writing: " + e); 19401 } 19402 } 19403 19404 if (!checkin 19405 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19406 && packageName == null) { 19407 pw.println(); 19408 int count = mSettings.mPackages.size(); 19409 if (count == 0) { 19410 pw.println("No applications!"); 19411 pw.println(); 19412 } else { 19413 final String prefix = " "; 19414 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19415 if (allPackageSettings.size() == 0) { 19416 pw.println("No domain preferred apps!"); 19417 pw.println(); 19418 } else { 19419 pw.println("App verification status:"); 19420 pw.println(); 19421 count = 0; 19422 for (PackageSetting ps : allPackageSettings) { 19423 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19424 if (ivi == null || ivi.getPackageName() == null) continue; 19425 pw.println(prefix + "Package: " + ivi.getPackageName()); 19426 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19427 pw.println(prefix + "Status: " + ivi.getStatusString()); 19428 pw.println(); 19429 count++; 19430 } 19431 if (count == 0) { 19432 pw.println(prefix + "No app verification established."); 19433 pw.println(); 19434 } 19435 for (int userId : sUserManager.getUserIds()) { 19436 pw.println("App linkages for user " + userId + ":"); 19437 pw.println(); 19438 count = 0; 19439 for (PackageSetting ps : allPackageSettings) { 19440 final long status = ps.getDomainVerificationStatusForUser(userId); 19441 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19442 continue; 19443 } 19444 pw.println(prefix + "Package: " + ps.name); 19445 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19446 String statusStr = IntentFilterVerificationInfo. 19447 getStatusStringFromValue(status); 19448 pw.println(prefix + "Status: " + statusStr); 19449 pw.println(); 19450 count++; 19451 } 19452 if (count == 0) { 19453 pw.println(prefix + "No configured app linkages."); 19454 pw.println(); 19455 } 19456 } 19457 } 19458 } 19459 } 19460 19461 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19462 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19463 if (packageName == null && permissionNames == null) { 19464 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19465 if (iperm == 0) { 19466 if (dumpState.onTitlePrinted()) 19467 pw.println(); 19468 pw.println("AppOp Permissions:"); 19469 } 19470 pw.print(" AppOp Permission "); 19471 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19472 pw.println(":"); 19473 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19474 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19475 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19476 } 19477 } 19478 } 19479 } 19480 19481 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19482 boolean printedSomething = false; 19483 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19484 if (packageName != null && !packageName.equals(p.info.packageName)) { 19485 continue; 19486 } 19487 if (!printedSomething) { 19488 if (dumpState.onTitlePrinted()) 19489 pw.println(); 19490 pw.println("Registered ContentProviders:"); 19491 printedSomething = true; 19492 } 19493 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19494 pw.print(" "); pw.println(p.toString()); 19495 } 19496 printedSomething = false; 19497 for (Map.Entry<String, PackageParser.Provider> entry : 19498 mProvidersByAuthority.entrySet()) { 19499 PackageParser.Provider p = entry.getValue(); 19500 if (packageName != null && !packageName.equals(p.info.packageName)) { 19501 continue; 19502 } 19503 if (!printedSomething) { 19504 if (dumpState.onTitlePrinted()) 19505 pw.println(); 19506 pw.println("ContentProvider Authorities:"); 19507 printedSomething = true; 19508 } 19509 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19510 pw.print(" "); pw.println(p.toString()); 19511 if (p.info != null && p.info.applicationInfo != null) { 19512 final String appInfo = p.info.applicationInfo.toString(); 19513 pw.print(" applicationInfo="); pw.println(appInfo); 19514 } 19515 } 19516 } 19517 19518 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19519 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19520 } 19521 19522 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19523 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19524 } 19525 19526 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19527 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19528 } 19529 19530 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19531 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19532 } 19533 19534 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19535 // XXX should handle packageName != null by dumping only install data that 19536 // the given package is involved with. 19537 if (dumpState.onTitlePrinted()) pw.println(); 19538 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19539 } 19540 19541 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19542 // XXX should handle packageName != null by dumping only install data that 19543 // the given package is involved with. 19544 if (dumpState.onTitlePrinted()) pw.println(); 19545 19546 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19547 ipw.println(); 19548 ipw.println("Frozen packages:"); 19549 ipw.increaseIndent(); 19550 if (mFrozenPackages.size() == 0) { 19551 ipw.println("(none)"); 19552 } else { 19553 for (int i = 0; i < mFrozenPackages.size(); i++) { 19554 ipw.println(mFrozenPackages.valueAt(i)); 19555 } 19556 } 19557 ipw.decreaseIndent(); 19558 } 19559 19560 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19561 if (dumpState.onTitlePrinted()) pw.println(); 19562 dumpDexoptStateLPr(pw, packageName); 19563 } 19564 19565 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19566 if (dumpState.onTitlePrinted()) pw.println(); 19567 dumpCompilerStatsLPr(pw, packageName); 19568 } 19569 19570 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19571 if (dumpState.onTitlePrinted()) pw.println(); 19572 mSettings.dumpReadMessagesLPr(pw, dumpState); 19573 19574 pw.println(); 19575 pw.println("Package warning messages:"); 19576 BufferedReader in = null; 19577 String line = null; 19578 try { 19579 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19580 while ((line = in.readLine()) != null) { 19581 if (line.contains("ignored: updated version")) continue; 19582 pw.println(line); 19583 } 19584 } catch (IOException ignored) { 19585 } finally { 19586 IoUtils.closeQuietly(in); 19587 } 19588 } 19589 19590 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19591 BufferedReader in = null; 19592 String line = null; 19593 try { 19594 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19595 while ((line = in.readLine()) != null) { 19596 if (line.contains("ignored: updated version")) continue; 19597 pw.print("msg,"); 19598 pw.println(line); 19599 } 19600 } catch (IOException ignored) { 19601 } finally { 19602 IoUtils.closeQuietly(in); 19603 } 19604 } 19605 } 19606 } 19607 19608 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19609 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19610 ipw.println(); 19611 ipw.println("Dexopt state:"); 19612 ipw.increaseIndent(); 19613 Collection<PackageParser.Package> packages = null; 19614 if (packageName != null) { 19615 PackageParser.Package targetPackage = mPackages.get(packageName); 19616 if (targetPackage != null) { 19617 packages = Collections.singletonList(targetPackage); 19618 } else { 19619 ipw.println("Unable to find package: " + packageName); 19620 return; 19621 } 19622 } else { 19623 packages = mPackages.values(); 19624 } 19625 19626 for (PackageParser.Package pkg : packages) { 19627 ipw.println("[" + pkg.packageName + "]"); 19628 ipw.increaseIndent(); 19629 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19630 ipw.decreaseIndent(); 19631 } 19632 } 19633 19634 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19635 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19636 ipw.println(); 19637 ipw.println("Compiler stats:"); 19638 ipw.increaseIndent(); 19639 Collection<PackageParser.Package> packages = null; 19640 if (packageName != null) { 19641 PackageParser.Package targetPackage = mPackages.get(packageName); 19642 if (targetPackage != null) { 19643 packages = Collections.singletonList(targetPackage); 19644 } else { 19645 ipw.println("Unable to find package: " + packageName); 19646 return; 19647 } 19648 } else { 19649 packages = mPackages.values(); 19650 } 19651 19652 for (PackageParser.Package pkg : packages) { 19653 ipw.println("[" + pkg.packageName + "]"); 19654 ipw.increaseIndent(); 19655 19656 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19657 if (stats == null) { 19658 ipw.println("(No recorded stats)"); 19659 } else { 19660 stats.dump(ipw); 19661 } 19662 ipw.decreaseIndent(); 19663 } 19664 } 19665 19666 private String dumpDomainString(String packageName) { 19667 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19668 .getList(); 19669 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19670 19671 ArraySet<String> result = new ArraySet<>(); 19672 if (iviList.size() > 0) { 19673 for (IntentFilterVerificationInfo ivi : iviList) { 19674 for (String host : ivi.getDomains()) { 19675 result.add(host); 19676 } 19677 } 19678 } 19679 if (filters != null && filters.size() > 0) { 19680 for (IntentFilter filter : filters) { 19681 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19682 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19683 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19684 result.addAll(filter.getHostsList()); 19685 } 19686 } 19687 } 19688 19689 StringBuilder sb = new StringBuilder(result.size() * 16); 19690 for (String domain : result) { 19691 if (sb.length() > 0) sb.append(" "); 19692 sb.append(domain); 19693 } 19694 return sb.toString(); 19695 } 19696 19697 // ------- apps on sdcard specific code ------- 19698 static final boolean DEBUG_SD_INSTALL = false; 19699 19700 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19701 19702 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19703 19704 private boolean mMediaMounted = false; 19705 19706 static String getEncryptKey() { 19707 try { 19708 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19709 SD_ENCRYPTION_KEYSTORE_NAME); 19710 if (sdEncKey == null) { 19711 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19712 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19713 if (sdEncKey == null) { 19714 Slog.e(TAG, "Failed to create encryption keys"); 19715 return null; 19716 } 19717 } 19718 return sdEncKey; 19719 } catch (NoSuchAlgorithmException nsae) { 19720 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19721 return null; 19722 } catch (IOException ioe) { 19723 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19724 return null; 19725 } 19726 } 19727 19728 /* 19729 * Update media status on PackageManager. 19730 */ 19731 @Override 19732 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19733 int callingUid = Binder.getCallingUid(); 19734 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19735 throw new SecurityException("Media status can only be updated by the system"); 19736 } 19737 // reader; this apparently protects mMediaMounted, but should probably 19738 // be a different lock in that case. 19739 synchronized (mPackages) { 19740 Log.i(TAG, "Updating external media status from " 19741 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19742 + (mediaStatus ? "mounted" : "unmounted")); 19743 if (DEBUG_SD_INSTALL) 19744 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19745 + ", mMediaMounted=" + mMediaMounted); 19746 if (mediaStatus == mMediaMounted) { 19747 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19748 : 0, -1); 19749 mHandler.sendMessage(msg); 19750 return; 19751 } 19752 mMediaMounted = mediaStatus; 19753 } 19754 // Queue up an async operation since the package installation may take a 19755 // little while. 19756 mHandler.post(new Runnable() { 19757 public void run() { 19758 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19759 } 19760 }); 19761 } 19762 19763 /** 19764 * Called by StorageManagerService when the initial ASECs to scan are available. 19765 * Should block until all the ASEC containers are finished being scanned. 19766 */ 19767 public void scanAvailableAsecs() { 19768 updateExternalMediaStatusInner(true, false, false); 19769 } 19770 19771 /* 19772 * Collect information of applications on external media, map them against 19773 * existing containers and update information based on current mount status. 19774 * Please note that we always have to report status if reportStatus has been 19775 * set to true especially when unloading packages. 19776 */ 19777 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19778 boolean externalStorage) { 19779 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19780 int[] uidArr = EmptyArray.INT; 19781 19782 final String[] list = PackageHelper.getSecureContainerList(); 19783 if (ArrayUtils.isEmpty(list)) { 19784 Log.i(TAG, "No secure containers found"); 19785 } else { 19786 // Process list of secure containers and categorize them 19787 // as active or stale based on their package internal state. 19788 19789 // reader 19790 synchronized (mPackages) { 19791 for (String cid : list) { 19792 // Leave stages untouched for now; installer service owns them 19793 if (PackageInstallerService.isStageName(cid)) continue; 19794 19795 if (DEBUG_SD_INSTALL) 19796 Log.i(TAG, "Processing container " + cid); 19797 String pkgName = getAsecPackageName(cid); 19798 if (pkgName == null) { 19799 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19800 continue; 19801 } 19802 if (DEBUG_SD_INSTALL) 19803 Log.i(TAG, "Looking for pkg : " + pkgName); 19804 19805 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19806 if (ps == null) { 19807 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19808 continue; 19809 } 19810 19811 /* 19812 * Skip packages that are not external if we're unmounting 19813 * external storage. 19814 */ 19815 if (externalStorage && !isMounted && !isExternal(ps)) { 19816 continue; 19817 } 19818 19819 final AsecInstallArgs args = new AsecInstallArgs(cid, 19820 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19821 // The package status is changed only if the code path 19822 // matches between settings and the container id. 19823 if (ps.codePathString != null 19824 && ps.codePathString.startsWith(args.getCodePath())) { 19825 if (DEBUG_SD_INSTALL) { 19826 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19827 + " at code path: " + ps.codePathString); 19828 } 19829 19830 // We do have a valid package installed on sdcard 19831 processCids.put(args, ps.codePathString); 19832 final int uid = ps.appId; 19833 if (uid != -1) { 19834 uidArr = ArrayUtils.appendInt(uidArr, uid); 19835 } 19836 } else { 19837 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19838 + ps.codePathString); 19839 } 19840 } 19841 } 19842 19843 Arrays.sort(uidArr); 19844 } 19845 19846 // Process packages with valid entries. 19847 if (isMounted) { 19848 if (DEBUG_SD_INSTALL) 19849 Log.i(TAG, "Loading packages"); 19850 loadMediaPackages(processCids, uidArr, externalStorage); 19851 startCleaningPackages(); 19852 mInstallerService.onSecureContainersAvailable(); 19853 } else { 19854 if (DEBUG_SD_INSTALL) 19855 Log.i(TAG, "Unloading packages"); 19856 unloadMediaPackages(processCids, uidArr, reportStatus); 19857 } 19858 } 19859 19860 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19861 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19862 final int size = infos.size(); 19863 final String[] packageNames = new String[size]; 19864 final int[] packageUids = new int[size]; 19865 for (int i = 0; i < size; i++) { 19866 final ApplicationInfo info = infos.get(i); 19867 packageNames[i] = info.packageName; 19868 packageUids[i] = info.uid; 19869 } 19870 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19871 finishedReceiver); 19872 } 19873 19874 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19875 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19876 sendResourcesChangedBroadcast(mediaStatus, replacing, 19877 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19878 } 19879 19880 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19881 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19882 int size = pkgList.length; 19883 if (size > 0) { 19884 // Send broadcasts here 19885 Bundle extras = new Bundle(); 19886 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19887 if (uidArr != null) { 19888 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19889 } 19890 if (replacing) { 19891 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19892 } 19893 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19894 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19895 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19896 } 19897 } 19898 19899 /* 19900 * Look at potentially valid container ids from processCids If package 19901 * information doesn't match the one on record or package scanning fails, 19902 * the cid is added to list of removeCids. We currently don't delete stale 19903 * containers. 19904 */ 19905 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19906 boolean externalStorage) { 19907 ArrayList<String> pkgList = new ArrayList<String>(); 19908 Set<AsecInstallArgs> keys = processCids.keySet(); 19909 19910 for (AsecInstallArgs args : keys) { 19911 String codePath = processCids.get(args); 19912 if (DEBUG_SD_INSTALL) 19913 Log.i(TAG, "Loading container : " + args.cid); 19914 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19915 try { 19916 // Make sure there are no container errors first. 19917 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19918 Slog.e(TAG, "Failed to mount cid : " + args.cid 19919 + " when installing from sdcard"); 19920 continue; 19921 } 19922 // Check code path here. 19923 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19924 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19925 + " does not match one in settings " + codePath); 19926 continue; 19927 } 19928 // Parse package 19929 int parseFlags = mDefParseFlags; 19930 if (args.isExternalAsec()) { 19931 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19932 } 19933 if (args.isFwdLocked()) { 19934 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19935 } 19936 19937 synchronized (mInstallLock) { 19938 PackageParser.Package pkg = null; 19939 try { 19940 // Sadly we don't know the package name yet to freeze it 19941 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19942 SCAN_IGNORE_FROZEN, 0, null); 19943 } catch (PackageManagerException e) { 19944 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19945 } 19946 // Scan the package 19947 if (pkg != null) { 19948 /* 19949 * TODO why is the lock being held? doPostInstall is 19950 * called in other places without the lock. This needs 19951 * to be straightened out. 19952 */ 19953 // writer 19954 synchronized (mPackages) { 19955 retCode = PackageManager.INSTALL_SUCCEEDED; 19956 pkgList.add(pkg.packageName); 19957 // Post process args 19958 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19959 pkg.applicationInfo.uid); 19960 } 19961 } else { 19962 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19963 } 19964 } 19965 19966 } finally { 19967 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19968 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19969 } 19970 } 19971 } 19972 // writer 19973 synchronized (mPackages) { 19974 // If the platform SDK has changed since the last time we booted, 19975 // we need to re-grant app permission to catch any new ones that 19976 // appear. This is really a hack, and means that apps can in some 19977 // cases get permissions that the user didn't initially explicitly 19978 // allow... it would be nice to have some better way to handle 19979 // this situation. 19980 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19981 : mSettings.getInternalVersion(); 19982 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19983 : StorageManager.UUID_PRIVATE_INTERNAL; 19984 19985 int updateFlags = UPDATE_PERMISSIONS_ALL; 19986 if (ver.sdkVersion != mSdkVersion) { 19987 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19988 + mSdkVersion + "; regranting permissions for external"); 19989 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19990 } 19991 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19992 19993 // Yay, everything is now upgraded 19994 ver.forceCurrent(); 19995 19996 // can downgrade to reader 19997 // Persist settings 19998 mSettings.writeLPr(); 19999 } 20000 // Send a broadcast to let everyone know we are done processing 20001 if (pkgList.size() > 0) { 20002 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 20003 } 20004 } 20005 20006 /* 20007 * Utility method to unload a list of specified containers 20008 */ 20009 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 20010 // Just unmount all valid containers. 20011 for (AsecInstallArgs arg : cidArgs) { 20012 synchronized (mInstallLock) { 20013 arg.doPostDeleteLI(false); 20014 } 20015 } 20016 } 20017 20018 /* 20019 * Unload packages mounted on external media. This involves deleting package 20020 * data from internal structures, sending broadcasts about disabled packages, 20021 * gc'ing to free up references, unmounting all secure containers 20022 * corresponding to packages on external media, and posting a 20023 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 20024 * that we always have to post this message if status has been requested no 20025 * matter what. 20026 */ 20027 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 20028 final boolean reportStatus) { 20029 if (DEBUG_SD_INSTALL) 20030 Log.i(TAG, "unloading media packages"); 20031 ArrayList<String> pkgList = new ArrayList<String>(); 20032 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 20033 final Set<AsecInstallArgs> keys = processCids.keySet(); 20034 for (AsecInstallArgs args : keys) { 20035 String pkgName = args.getPackageName(); 20036 if (DEBUG_SD_INSTALL) 20037 Log.i(TAG, "Trying to unload pkg : " + pkgName); 20038 // Delete package internally 20039 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20040 synchronized (mInstallLock) { 20041 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20042 final boolean res; 20043 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 20044 "unloadMediaPackages")) { 20045 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 20046 null); 20047 } 20048 if (res) { 20049 pkgList.add(pkgName); 20050 } else { 20051 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 20052 failedList.add(args); 20053 } 20054 } 20055 } 20056 20057 // reader 20058 synchronized (mPackages) { 20059 // We didn't update the settings after removing each package; 20060 // write them now for all packages. 20061 mSettings.writeLPr(); 20062 } 20063 20064 // We have to absolutely send UPDATED_MEDIA_STATUS only 20065 // after confirming that all the receivers processed the ordered 20066 // broadcast when packages get disabled, force a gc to clean things up. 20067 // and unload all the containers. 20068 if (pkgList.size() > 0) { 20069 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 20070 new IIntentReceiver.Stub() { 20071 public void performReceive(Intent intent, int resultCode, String data, 20072 Bundle extras, boolean ordered, boolean sticky, 20073 int sendingUser) throws RemoteException { 20074 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 20075 reportStatus ? 1 : 0, 1, keys); 20076 mHandler.sendMessage(msg); 20077 } 20078 }); 20079 } else { 20080 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 20081 keys); 20082 mHandler.sendMessage(msg); 20083 } 20084 } 20085 20086 private void loadPrivatePackages(final VolumeInfo vol) { 20087 mHandler.post(new Runnable() { 20088 @Override 20089 public void run() { 20090 loadPrivatePackagesInner(vol); 20091 } 20092 }); 20093 } 20094 20095 private void loadPrivatePackagesInner(VolumeInfo vol) { 20096 final String volumeUuid = vol.fsUuid; 20097 if (TextUtils.isEmpty(volumeUuid)) { 20098 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 20099 return; 20100 } 20101 20102 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 20103 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 20104 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 20105 20106 final VersionInfo ver; 20107 final List<PackageSetting> packages; 20108 synchronized (mPackages) { 20109 ver = mSettings.findOrCreateVersion(volumeUuid); 20110 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20111 } 20112 20113 for (PackageSetting ps : packages) { 20114 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 20115 synchronized (mInstallLock) { 20116 final PackageParser.Package pkg; 20117 try { 20118 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 20119 loaded.add(pkg.applicationInfo); 20120 20121 } catch (PackageManagerException e) { 20122 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 20123 } 20124 20125 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 20126 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 20127 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 20128 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20129 } 20130 } 20131 } 20132 20133 // Reconcile app data for all started/unlocked users 20134 final StorageManager sm = mContext.getSystemService(StorageManager.class); 20135 final UserManager um = mContext.getSystemService(UserManager.class); 20136 UserManagerInternal umInternal = getUserManagerInternal(); 20137 for (UserInfo user : um.getUsers()) { 20138 final int flags; 20139 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20140 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20141 } else if (umInternal.isUserRunning(user.id)) { 20142 flags = StorageManager.FLAG_STORAGE_DE; 20143 } else { 20144 continue; 20145 } 20146 20147 try { 20148 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 20149 synchronized (mInstallLock) { 20150 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 20151 } 20152 } catch (IllegalStateException e) { 20153 // Device was probably ejected, and we'll process that event momentarily 20154 Slog.w(TAG, "Failed to prepare storage: " + e); 20155 } 20156 } 20157 20158 synchronized (mPackages) { 20159 int updateFlags = UPDATE_PERMISSIONS_ALL; 20160 if (ver.sdkVersion != mSdkVersion) { 20161 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 20162 + mSdkVersion + "; regranting permissions for " + volumeUuid); 20163 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 20164 } 20165 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 20166 20167 // Yay, everything is now upgraded 20168 ver.forceCurrent(); 20169 20170 mSettings.writeLPr(); 20171 } 20172 20173 for (PackageFreezer freezer : freezers) { 20174 freezer.close(); 20175 } 20176 20177 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 20178 sendResourcesChangedBroadcast(true, false, loaded, null); 20179 } 20180 20181 private void unloadPrivatePackages(final VolumeInfo vol) { 20182 mHandler.post(new Runnable() { 20183 @Override 20184 public void run() { 20185 unloadPrivatePackagesInner(vol); 20186 } 20187 }); 20188 } 20189 20190 private void unloadPrivatePackagesInner(VolumeInfo vol) { 20191 final String volumeUuid = vol.fsUuid; 20192 if (TextUtils.isEmpty(volumeUuid)) { 20193 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 20194 return; 20195 } 20196 20197 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 20198 synchronized (mInstallLock) { 20199 synchronized (mPackages) { 20200 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 20201 for (PackageSetting ps : packages) { 20202 if (ps.pkg == null) continue; 20203 20204 final ApplicationInfo info = ps.pkg.applicationInfo; 20205 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 20206 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 20207 20208 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 20209 "unloadPrivatePackagesInner")) { 20210 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 20211 false, null)) { 20212 unloaded.add(info); 20213 } else { 20214 Slog.w(TAG, "Failed to unload " + ps.codePath); 20215 } 20216 } 20217 20218 // Try very hard to release any references to this package 20219 // so we don't risk the system server being killed due to 20220 // open FDs 20221 AttributeCache.instance().removePackage(ps.name); 20222 } 20223 20224 mSettings.writeLPr(); 20225 } 20226 } 20227 20228 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 20229 sendResourcesChangedBroadcast(false, false, unloaded, null); 20230 20231 // Try very hard to release any references to this path so we don't risk 20232 // the system server being killed due to open FDs 20233 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 20234 20235 for (int i = 0; i < 3; i++) { 20236 System.gc(); 20237 System.runFinalization(); 20238 } 20239 } 20240 20241 /** 20242 * Prepare storage areas for given user on all mounted devices. 20243 */ 20244 void prepareUserData(int userId, int userSerial, int flags) { 20245 synchronized (mInstallLock) { 20246 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20247 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20248 final String volumeUuid = vol.getFsUuid(); 20249 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 20250 } 20251 } 20252 } 20253 20254 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 20255 boolean allowRecover) { 20256 // Prepare storage and verify that serial numbers are consistent; if 20257 // there's a mismatch we need to destroy to avoid leaking data 20258 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20259 try { 20260 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 20261 20262 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 20263 UserManagerService.enforceSerialNumber( 20264 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 20265 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20266 UserManagerService.enforceSerialNumber( 20267 Environment.getDataSystemDeDirectory(userId), userSerial); 20268 } 20269 } 20270 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 20271 UserManagerService.enforceSerialNumber( 20272 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 20273 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20274 UserManagerService.enforceSerialNumber( 20275 Environment.getDataSystemCeDirectory(userId), userSerial); 20276 } 20277 } 20278 20279 synchronized (mInstallLock) { 20280 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20281 } 20282 } catch (Exception e) { 20283 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20284 + " because we failed to prepare: " + e); 20285 destroyUserDataLI(volumeUuid, userId, 20286 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20287 20288 if (allowRecover) { 20289 // Try one last time; if we fail again we're really in trouble 20290 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20291 } 20292 } 20293 } 20294 20295 /** 20296 * Destroy storage areas for given user on all mounted devices. 20297 */ 20298 void destroyUserData(int userId, int flags) { 20299 synchronized (mInstallLock) { 20300 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20301 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20302 final String volumeUuid = vol.getFsUuid(); 20303 destroyUserDataLI(volumeUuid, userId, flags); 20304 } 20305 } 20306 } 20307 20308 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20309 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20310 try { 20311 // Clean up app data, profile data, and media data 20312 mInstaller.destroyUserData(volumeUuid, userId, flags); 20313 20314 // Clean up system data 20315 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20316 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20317 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20318 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20319 } 20320 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20321 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20322 } 20323 } 20324 20325 // Data with special labels is now gone, so finish the job 20326 storage.destroyUserStorage(volumeUuid, userId, flags); 20327 20328 } catch (Exception e) { 20329 logCriticalInfo(Log.WARN, 20330 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20331 } 20332 } 20333 20334 /** 20335 * Examine all users present on given mounted volume, and destroy data 20336 * belonging to users that are no longer valid, or whose user ID has been 20337 * recycled. 20338 */ 20339 private void reconcileUsers(String volumeUuid) { 20340 final List<File> files = new ArrayList<>(); 20341 Collections.addAll(files, FileUtils 20342 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20343 Collections.addAll(files, FileUtils 20344 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20345 Collections.addAll(files, FileUtils 20346 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20347 Collections.addAll(files, FileUtils 20348 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20349 for (File file : files) { 20350 if (!file.isDirectory()) continue; 20351 20352 final int userId; 20353 final UserInfo info; 20354 try { 20355 userId = Integer.parseInt(file.getName()); 20356 info = sUserManager.getUserInfo(userId); 20357 } catch (NumberFormatException e) { 20358 Slog.w(TAG, "Invalid user directory " + file); 20359 continue; 20360 } 20361 20362 boolean destroyUser = false; 20363 if (info == null) { 20364 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20365 + " because no matching user was found"); 20366 destroyUser = true; 20367 } else if (!mOnlyCore) { 20368 try { 20369 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20370 } catch (IOException e) { 20371 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20372 + " because we failed to enforce serial number: " + e); 20373 destroyUser = true; 20374 } 20375 } 20376 20377 if (destroyUser) { 20378 synchronized (mInstallLock) { 20379 destroyUserDataLI(volumeUuid, userId, 20380 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20381 } 20382 } 20383 } 20384 } 20385 20386 private void assertPackageKnown(String volumeUuid, String packageName) 20387 throws PackageManagerException { 20388 synchronized (mPackages) { 20389 // Normalize package name to handle renamed packages 20390 packageName = normalizePackageNameLPr(packageName); 20391 20392 final PackageSetting ps = mSettings.mPackages.get(packageName); 20393 if (ps == null) { 20394 throw new PackageManagerException("Package " + packageName + " is unknown"); 20395 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20396 throw new PackageManagerException( 20397 "Package " + packageName + " found on unknown volume " + volumeUuid 20398 + "; expected volume " + ps.volumeUuid); 20399 } 20400 } 20401 } 20402 20403 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20404 throws PackageManagerException { 20405 synchronized (mPackages) { 20406 // Normalize package name to handle renamed packages 20407 packageName = normalizePackageNameLPr(packageName); 20408 20409 final PackageSetting ps = mSettings.mPackages.get(packageName); 20410 if (ps == null) { 20411 throw new PackageManagerException("Package " + packageName + " is unknown"); 20412 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20413 throw new PackageManagerException( 20414 "Package " + packageName + " found on unknown volume " + volumeUuid 20415 + "; expected volume " + ps.volumeUuid); 20416 } else if (!ps.getInstalled(userId)) { 20417 throw new PackageManagerException( 20418 "Package " + packageName + " not installed for user " + userId); 20419 } 20420 } 20421 } 20422 20423 /** 20424 * Examine all apps present on given mounted volume, and destroy apps that 20425 * aren't expected, either due to uninstallation or reinstallation on 20426 * another volume. 20427 */ 20428 private void reconcileApps(String volumeUuid) { 20429 final File[] files = FileUtils 20430 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20431 for (File file : files) { 20432 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20433 && !PackageInstallerService.isStageName(file.getName()); 20434 if (!isPackage) { 20435 // Ignore entries which are not packages 20436 continue; 20437 } 20438 20439 try { 20440 final PackageLite pkg = PackageParser.parsePackageLite(file, 20441 PackageParser.PARSE_MUST_BE_APK); 20442 assertPackageKnown(volumeUuid, pkg.packageName); 20443 20444 } catch (PackageParserException | PackageManagerException e) { 20445 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20446 synchronized (mInstallLock) { 20447 removeCodePathLI(file); 20448 } 20449 } 20450 } 20451 } 20452 20453 /** 20454 * Reconcile all app data for the given user. 20455 * <p> 20456 * Verifies that directories exist and that ownership and labeling is 20457 * correct for all installed apps on all mounted volumes. 20458 */ 20459 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20460 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20461 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20462 final String volumeUuid = vol.getFsUuid(); 20463 synchronized (mInstallLock) { 20464 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20465 } 20466 } 20467 } 20468 20469 /** 20470 * Reconcile all app data on given mounted volume. 20471 * <p> 20472 * Destroys app data that isn't expected, either due to uninstallation or 20473 * reinstallation on another volume. 20474 * <p> 20475 * Verifies that directories exist and that ownership and labeling is 20476 * correct for all installed apps. 20477 */ 20478 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20479 boolean migrateAppData) { 20480 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20481 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20482 20483 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20484 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20485 20486 // First look for stale data that doesn't belong, and check if things 20487 // have changed since we did our last restorecon 20488 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20489 if (StorageManager.isFileEncryptedNativeOrEmulated() 20490 && !StorageManager.isUserKeyUnlocked(userId)) { 20491 throw new RuntimeException( 20492 "Yikes, someone asked us to reconcile CE storage while " + userId 20493 + " was still locked; this would have caused massive data loss!"); 20494 } 20495 20496 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20497 for (File file : files) { 20498 final String packageName = file.getName(); 20499 try { 20500 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20501 } catch (PackageManagerException e) { 20502 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20503 try { 20504 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20505 StorageManager.FLAG_STORAGE_CE, 0); 20506 } catch (InstallerException e2) { 20507 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20508 } 20509 } 20510 } 20511 } 20512 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20513 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20514 for (File file : files) { 20515 final String packageName = file.getName(); 20516 try { 20517 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20518 } catch (PackageManagerException e) { 20519 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20520 try { 20521 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20522 StorageManager.FLAG_STORAGE_DE, 0); 20523 } catch (InstallerException e2) { 20524 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20525 } 20526 } 20527 } 20528 } 20529 20530 // Ensure that data directories are ready to roll for all packages 20531 // installed for this volume and user 20532 final List<PackageSetting> packages; 20533 synchronized (mPackages) { 20534 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20535 } 20536 int preparedCount = 0; 20537 for (PackageSetting ps : packages) { 20538 final String packageName = ps.name; 20539 if (ps.pkg == null) { 20540 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20541 // TODO: might be due to legacy ASEC apps; we should circle back 20542 // and reconcile again once they're scanned 20543 continue; 20544 } 20545 20546 if (ps.getInstalled(userId)) { 20547 prepareAppDataLIF(ps.pkg, userId, flags); 20548 20549 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20550 // We may have just shuffled around app data directories, so 20551 // prepare them one more time 20552 prepareAppDataLIF(ps.pkg, userId, flags); 20553 } 20554 20555 preparedCount++; 20556 } 20557 } 20558 20559 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20560 } 20561 20562 /** 20563 * Prepare app data for the given app just after it was installed or 20564 * upgraded. This method carefully only touches users that it's installed 20565 * for, and it forces a restorecon to handle any seinfo changes. 20566 * <p> 20567 * Verifies that directories exist and that ownership and labeling is 20568 * correct for all installed apps. If there is an ownership mismatch, it 20569 * will try recovering system apps by wiping data; third-party app data is 20570 * left intact. 20571 * <p> 20572 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20573 */ 20574 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20575 final PackageSetting ps; 20576 synchronized (mPackages) { 20577 ps = mSettings.mPackages.get(pkg.packageName); 20578 mSettings.writeKernelMappingLPr(ps); 20579 } 20580 20581 final UserManager um = mContext.getSystemService(UserManager.class); 20582 UserManagerInternal umInternal = getUserManagerInternal(); 20583 for (UserInfo user : um.getUsers()) { 20584 final int flags; 20585 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20586 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20587 } else if (umInternal.isUserRunning(user.id)) { 20588 flags = StorageManager.FLAG_STORAGE_DE; 20589 } else { 20590 continue; 20591 } 20592 20593 if (ps.getInstalled(user.id)) { 20594 // TODO: when user data is locked, mark that we're still dirty 20595 prepareAppDataLIF(pkg, user.id, flags); 20596 } 20597 } 20598 } 20599 20600 /** 20601 * Prepare app data for the given app. 20602 * <p> 20603 * Verifies that directories exist and that ownership and labeling is 20604 * correct for all installed apps. If there is an ownership mismatch, this 20605 * will try recovering system apps by wiping data; third-party app data is 20606 * left intact. 20607 */ 20608 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20609 if (pkg == null) { 20610 Slog.wtf(TAG, "Package was null!", new Throwable()); 20611 return; 20612 } 20613 prepareAppDataLeafLIF(pkg, userId, flags); 20614 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20615 for (int i = 0; i < childCount; i++) { 20616 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20617 } 20618 } 20619 20620 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20621 if (DEBUG_APP_DATA) { 20622 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20623 + Integer.toHexString(flags)); 20624 } 20625 20626 final String volumeUuid = pkg.volumeUuid; 20627 final String packageName = pkg.packageName; 20628 final ApplicationInfo app = pkg.applicationInfo; 20629 final int appId = UserHandle.getAppId(app.uid); 20630 20631 Preconditions.checkNotNull(app.seinfo); 20632 20633 long ceDataInode = -1; 20634 try { 20635 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20636 appId, app.seinfo, app.targetSdkVersion); 20637 } catch (InstallerException e) { 20638 if (app.isSystemApp()) { 20639 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20640 + ", but trying to recover: " + e); 20641 destroyAppDataLeafLIF(pkg, userId, flags); 20642 try { 20643 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20644 appId, app.seinfo, app.targetSdkVersion); 20645 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20646 } catch (InstallerException e2) { 20647 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20648 } 20649 } else { 20650 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20651 } 20652 } 20653 20654 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 20655 // TODO: mark this structure as dirty so we persist it! 20656 synchronized (mPackages) { 20657 final PackageSetting ps = mSettings.mPackages.get(packageName); 20658 if (ps != null) { 20659 ps.setCeDataInode(ceDataInode, userId); 20660 } 20661 } 20662 } 20663 20664 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20665 } 20666 20667 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20668 if (pkg == null) { 20669 Slog.wtf(TAG, "Package was null!", new Throwable()); 20670 return; 20671 } 20672 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20673 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20674 for (int i = 0; i < childCount; i++) { 20675 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20676 } 20677 } 20678 20679 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20680 final String volumeUuid = pkg.volumeUuid; 20681 final String packageName = pkg.packageName; 20682 final ApplicationInfo app = pkg.applicationInfo; 20683 20684 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20685 // Create a native library symlink only if we have native libraries 20686 // and if the native libraries are 32 bit libraries. We do not provide 20687 // this symlink for 64 bit libraries. 20688 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20689 final String nativeLibPath = app.nativeLibraryDir; 20690 try { 20691 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20692 nativeLibPath, userId); 20693 } catch (InstallerException e) { 20694 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20695 } 20696 } 20697 } 20698 } 20699 20700 /** 20701 * For system apps on non-FBE devices, this method migrates any existing 20702 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20703 * requested by the app. 20704 */ 20705 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20706 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20707 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20708 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20709 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20710 try { 20711 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20712 storageTarget); 20713 } catch (InstallerException e) { 20714 logCriticalInfo(Log.WARN, 20715 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20716 } 20717 return true; 20718 } else { 20719 return false; 20720 } 20721 } 20722 20723 public PackageFreezer freezePackage(String packageName, String killReason) { 20724 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20725 } 20726 20727 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20728 return new PackageFreezer(packageName, userId, killReason); 20729 } 20730 20731 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20732 String killReason) { 20733 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20734 } 20735 20736 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20737 String killReason) { 20738 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20739 return new PackageFreezer(); 20740 } else { 20741 return freezePackage(packageName, userId, killReason); 20742 } 20743 } 20744 20745 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20746 String killReason) { 20747 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20748 } 20749 20750 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20751 String killReason) { 20752 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20753 return new PackageFreezer(); 20754 } else { 20755 return freezePackage(packageName, userId, killReason); 20756 } 20757 } 20758 20759 /** 20760 * Class that freezes and kills the given package upon creation, and 20761 * unfreezes it upon closing. This is typically used when doing surgery on 20762 * app code/data to prevent the app from running while you're working. 20763 */ 20764 private class PackageFreezer implements AutoCloseable { 20765 private final String mPackageName; 20766 private final PackageFreezer[] mChildren; 20767 20768 private final boolean mWeFroze; 20769 20770 private final AtomicBoolean mClosed = new AtomicBoolean(); 20771 private final CloseGuard mCloseGuard = CloseGuard.get(); 20772 20773 /** 20774 * Create and return a stub freezer that doesn't actually do anything, 20775 * typically used when someone requested 20776 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20777 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20778 */ 20779 public PackageFreezer() { 20780 mPackageName = null; 20781 mChildren = null; 20782 mWeFroze = false; 20783 mCloseGuard.open("close"); 20784 } 20785 20786 public PackageFreezer(String packageName, int userId, String killReason) { 20787 synchronized (mPackages) { 20788 mPackageName = packageName; 20789 mWeFroze = mFrozenPackages.add(mPackageName); 20790 20791 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20792 if (ps != null) { 20793 killApplication(ps.name, ps.appId, userId, killReason); 20794 } 20795 20796 final PackageParser.Package p = mPackages.get(packageName); 20797 if (p != null && p.childPackages != null) { 20798 final int N = p.childPackages.size(); 20799 mChildren = new PackageFreezer[N]; 20800 for (int i = 0; i < N; i++) { 20801 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20802 userId, killReason); 20803 } 20804 } else { 20805 mChildren = null; 20806 } 20807 } 20808 mCloseGuard.open("close"); 20809 } 20810 20811 @Override 20812 protected void finalize() throws Throwable { 20813 try { 20814 mCloseGuard.warnIfOpen(); 20815 close(); 20816 } finally { 20817 super.finalize(); 20818 } 20819 } 20820 20821 @Override 20822 public void close() { 20823 mCloseGuard.close(); 20824 if (mClosed.compareAndSet(false, true)) { 20825 synchronized (mPackages) { 20826 if (mWeFroze) { 20827 mFrozenPackages.remove(mPackageName); 20828 } 20829 20830 if (mChildren != null) { 20831 for (PackageFreezer freezer : mChildren) { 20832 freezer.close(); 20833 } 20834 } 20835 } 20836 } 20837 } 20838 } 20839 20840 /** 20841 * Verify that given package is currently frozen. 20842 */ 20843 private void checkPackageFrozen(String packageName) { 20844 synchronized (mPackages) { 20845 if (!mFrozenPackages.contains(packageName)) { 20846 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20847 } 20848 } 20849 } 20850 20851 @Override 20852 public int movePackage(final String packageName, final String volumeUuid) { 20853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20854 20855 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20856 final int moveId = mNextMoveId.getAndIncrement(); 20857 mHandler.post(new Runnable() { 20858 @Override 20859 public void run() { 20860 try { 20861 movePackageInternal(packageName, volumeUuid, moveId, user); 20862 } catch (PackageManagerException e) { 20863 Slog.w(TAG, "Failed to move " + packageName, e); 20864 mMoveCallbacks.notifyStatusChanged(moveId, 20865 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20866 } 20867 } 20868 }); 20869 return moveId; 20870 } 20871 20872 private void movePackageInternal(final String packageName, final String volumeUuid, 20873 final int moveId, UserHandle user) throws PackageManagerException { 20874 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20875 final PackageManager pm = mContext.getPackageManager(); 20876 20877 final boolean currentAsec; 20878 final String currentVolumeUuid; 20879 final File codeFile; 20880 final String installerPackageName; 20881 final String packageAbiOverride; 20882 final int appId; 20883 final String seinfo; 20884 final String label; 20885 final int targetSdkVersion; 20886 final PackageFreezer freezer; 20887 final int[] installedUserIds; 20888 20889 // reader 20890 synchronized (mPackages) { 20891 final PackageParser.Package pkg = mPackages.get(packageName); 20892 final PackageSetting ps = mSettings.mPackages.get(packageName); 20893 if (pkg == null || ps == null) { 20894 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20895 } 20896 20897 if (pkg.applicationInfo.isSystemApp()) { 20898 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20899 "Cannot move system application"); 20900 } 20901 20902 if (pkg.applicationInfo.isExternalAsec()) { 20903 currentAsec = true; 20904 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20905 } else if (pkg.applicationInfo.isForwardLocked()) { 20906 currentAsec = true; 20907 currentVolumeUuid = "forward_locked"; 20908 } else { 20909 currentAsec = false; 20910 currentVolumeUuid = ps.volumeUuid; 20911 20912 final File probe = new File(pkg.codePath); 20913 final File probeOat = new File(probe, "oat"); 20914 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20915 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20916 "Move only supported for modern cluster style installs"); 20917 } 20918 } 20919 20920 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20921 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20922 "Package already moved to " + volumeUuid); 20923 } 20924 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20925 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20926 "Device admin cannot be moved"); 20927 } 20928 20929 if (mFrozenPackages.contains(packageName)) { 20930 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20931 "Failed to move already frozen package"); 20932 } 20933 20934 codeFile = new File(pkg.codePath); 20935 installerPackageName = ps.installerPackageName; 20936 packageAbiOverride = ps.cpuAbiOverrideString; 20937 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20938 seinfo = pkg.applicationInfo.seinfo; 20939 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20940 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20941 freezer = freezePackage(packageName, "movePackageInternal"); 20942 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20943 } 20944 20945 final Bundle extras = new Bundle(); 20946 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20947 extras.putString(Intent.EXTRA_TITLE, label); 20948 mMoveCallbacks.notifyCreated(moveId, extras); 20949 20950 int installFlags; 20951 final boolean moveCompleteApp; 20952 final File measurePath; 20953 20954 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20955 installFlags = INSTALL_INTERNAL; 20956 moveCompleteApp = !currentAsec; 20957 measurePath = Environment.getDataAppDirectory(volumeUuid); 20958 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20959 installFlags = INSTALL_EXTERNAL; 20960 moveCompleteApp = false; 20961 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20962 } else { 20963 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20964 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20965 || !volume.isMountedWritable()) { 20966 freezer.close(); 20967 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20968 "Move location not mounted private volume"); 20969 } 20970 20971 Preconditions.checkState(!currentAsec); 20972 20973 installFlags = INSTALL_INTERNAL; 20974 moveCompleteApp = true; 20975 measurePath = Environment.getDataAppDirectory(volumeUuid); 20976 } 20977 20978 final PackageStats stats = new PackageStats(null, -1); 20979 synchronized (mInstaller) { 20980 for (int userId : installedUserIds) { 20981 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20982 freezer.close(); 20983 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20984 "Failed to measure package size"); 20985 } 20986 } 20987 } 20988 20989 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20990 + stats.dataSize); 20991 20992 final long startFreeBytes = measurePath.getFreeSpace(); 20993 final long sizeBytes; 20994 if (moveCompleteApp) { 20995 sizeBytes = stats.codeSize + stats.dataSize; 20996 } else { 20997 sizeBytes = stats.codeSize; 20998 } 20999 21000 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 21001 freezer.close(); 21002 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 21003 "Not enough free space to move"); 21004 } 21005 21006 mMoveCallbacks.notifyStatusChanged(moveId, 10); 21007 21008 final CountDownLatch installedLatch = new CountDownLatch(1); 21009 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 21010 @Override 21011 public void onUserActionRequired(Intent intent) throws RemoteException { 21012 throw new IllegalStateException(); 21013 } 21014 21015 @Override 21016 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 21017 Bundle extras) throws RemoteException { 21018 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 21019 + PackageManager.installStatusToString(returnCode, msg)); 21020 21021 installedLatch.countDown(); 21022 freezer.close(); 21023 21024 final int status = PackageManager.installStatusToPublicStatus(returnCode); 21025 switch (status) { 21026 case PackageInstaller.STATUS_SUCCESS: 21027 mMoveCallbacks.notifyStatusChanged(moveId, 21028 PackageManager.MOVE_SUCCEEDED); 21029 break; 21030 case PackageInstaller.STATUS_FAILURE_STORAGE: 21031 mMoveCallbacks.notifyStatusChanged(moveId, 21032 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 21033 break; 21034 default: 21035 mMoveCallbacks.notifyStatusChanged(moveId, 21036 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21037 break; 21038 } 21039 } 21040 }; 21041 21042 final MoveInfo move; 21043 if (moveCompleteApp) { 21044 // Kick off a thread to report progress estimates 21045 new Thread() { 21046 @Override 21047 public void run() { 21048 while (true) { 21049 try { 21050 if (installedLatch.await(1, TimeUnit.SECONDS)) { 21051 break; 21052 } 21053 } catch (InterruptedException ignored) { 21054 } 21055 21056 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 21057 final int progress = 10 + (int) MathUtils.constrain( 21058 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 21059 mMoveCallbacks.notifyStatusChanged(moveId, progress); 21060 } 21061 } 21062 }.start(); 21063 21064 final String dataAppName = codeFile.getName(); 21065 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 21066 dataAppName, appId, seinfo, targetSdkVersion); 21067 } else { 21068 move = null; 21069 } 21070 21071 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 21072 21073 final Message msg = mHandler.obtainMessage(INIT_COPY); 21074 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 21075 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 21076 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 21077 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 21078 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 21079 msg.obj = params; 21080 21081 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 21082 System.identityHashCode(msg.obj)); 21083 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 21084 System.identityHashCode(msg.obj)); 21085 21086 mHandler.sendMessage(msg); 21087 } 21088 21089 @Override 21090 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 21091 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21092 21093 final int realMoveId = mNextMoveId.getAndIncrement(); 21094 final Bundle extras = new Bundle(); 21095 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 21096 mMoveCallbacks.notifyCreated(realMoveId, extras); 21097 21098 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 21099 @Override 21100 public void onCreated(int moveId, Bundle extras) { 21101 // Ignored 21102 } 21103 21104 @Override 21105 public void onStatusChanged(int moveId, int status, long estMillis) { 21106 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 21107 } 21108 }; 21109 21110 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21111 storage.setPrimaryStorageUuid(volumeUuid, callback); 21112 return realMoveId; 21113 } 21114 21115 @Override 21116 public int getMoveStatus(int moveId) { 21117 mContext.enforceCallingOrSelfPermission( 21118 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21119 return mMoveCallbacks.mLastStatus.get(moveId); 21120 } 21121 21122 @Override 21123 public void registerMoveCallback(IPackageMoveObserver callback) { 21124 mContext.enforceCallingOrSelfPermission( 21125 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21126 mMoveCallbacks.register(callback); 21127 } 21128 21129 @Override 21130 public void unregisterMoveCallback(IPackageMoveObserver callback) { 21131 mContext.enforceCallingOrSelfPermission( 21132 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 21133 mMoveCallbacks.unregister(callback); 21134 } 21135 21136 @Override 21137 public boolean setInstallLocation(int loc) { 21138 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 21139 null); 21140 if (getInstallLocation() == loc) { 21141 return true; 21142 } 21143 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 21144 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 21145 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 21146 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 21147 return true; 21148 } 21149 return false; 21150 } 21151 21152 @Override 21153 public int getInstallLocation() { 21154 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 21155 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 21156 PackageHelper.APP_INSTALL_AUTO); 21157 } 21158 21159 /** Called by UserManagerService */ 21160 void cleanUpUser(UserManagerService userManager, int userHandle) { 21161 synchronized (mPackages) { 21162 mDirtyUsers.remove(userHandle); 21163 mUserNeedsBadging.delete(userHandle); 21164 mSettings.removeUserLPw(userHandle); 21165 mPendingBroadcasts.remove(userHandle); 21166 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 21167 removeUnusedPackagesLPw(userManager, userHandle); 21168 } 21169 } 21170 21171 /** 21172 * We're removing userHandle and would like to remove any downloaded packages 21173 * that are no longer in use by any other user. 21174 * @param userHandle the user being removed 21175 */ 21176 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 21177 final boolean DEBUG_CLEAN_APKS = false; 21178 int [] users = userManager.getUserIds(); 21179 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 21180 while (psit.hasNext()) { 21181 PackageSetting ps = psit.next(); 21182 if (ps.pkg == null) { 21183 continue; 21184 } 21185 final String packageName = ps.pkg.packageName; 21186 // Skip over if system app 21187 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 21188 continue; 21189 } 21190 if (DEBUG_CLEAN_APKS) { 21191 Slog.i(TAG, "Checking package " + packageName); 21192 } 21193 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 21194 if (keep) { 21195 if (DEBUG_CLEAN_APKS) { 21196 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 21197 } 21198 } else { 21199 for (int i = 0; i < users.length; i++) { 21200 if (users[i] != userHandle && ps.getInstalled(users[i])) { 21201 keep = true; 21202 if (DEBUG_CLEAN_APKS) { 21203 Slog.i(TAG, " Keeping package " + packageName + " for user " 21204 + users[i]); 21205 } 21206 break; 21207 } 21208 } 21209 } 21210 if (!keep) { 21211 if (DEBUG_CLEAN_APKS) { 21212 Slog.i(TAG, " Removing package " + packageName); 21213 } 21214 mHandler.post(new Runnable() { 21215 public void run() { 21216 deletePackageX(packageName, userHandle, 0); 21217 } //end run 21218 }); 21219 } 21220 } 21221 } 21222 21223 /** Called by UserManagerService */ 21224 void createNewUser(int userId, String[] disallowedPackages) { 21225 synchronized (mInstallLock) { 21226 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 21227 } 21228 synchronized (mPackages) { 21229 scheduleWritePackageRestrictionsLocked(userId); 21230 scheduleWritePackageListLocked(userId); 21231 applyFactoryDefaultBrowserLPw(userId); 21232 primeDomainVerificationsLPw(userId); 21233 } 21234 } 21235 21236 void onNewUserCreated(final int userId) { 21237 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21238 // If permission review for legacy apps is required, we represent 21239 // dagerous permissions for such apps as always granted runtime 21240 // permissions to keep per user flag state whether review is needed. 21241 // Hence, if a new user is added we have to propagate dangerous 21242 // permission grants for these legacy apps. 21243 if (mPermissionReviewRequired) { 21244 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 21245 | UPDATE_PERMISSIONS_REPLACE_ALL); 21246 } 21247 } 21248 21249 @Override 21250 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 21251 mContext.enforceCallingOrSelfPermission( 21252 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 21253 "Only package verification agents can read the verifier device identity"); 21254 21255 synchronized (mPackages) { 21256 return mSettings.getVerifierDeviceIdentityLPw(); 21257 } 21258 } 21259 21260 @Override 21261 public void setPermissionEnforced(String permission, boolean enforced) { 21262 // TODO: Now that we no longer change GID for storage, this should to away. 21263 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 21264 "setPermissionEnforced"); 21265 if (READ_EXTERNAL_STORAGE.equals(permission)) { 21266 synchronized (mPackages) { 21267 if (mSettings.mReadExternalStorageEnforced == null 21268 || mSettings.mReadExternalStorageEnforced != enforced) { 21269 mSettings.mReadExternalStorageEnforced = enforced; 21270 mSettings.writeLPr(); 21271 } 21272 } 21273 // kill any non-foreground processes so we restart them and 21274 // grant/revoke the GID. 21275 final IActivityManager am = ActivityManager.getService(); 21276 if (am != null) { 21277 final long token = Binder.clearCallingIdentity(); 21278 try { 21279 am.killProcessesBelowForeground("setPermissionEnforcement"); 21280 } catch (RemoteException e) { 21281 } finally { 21282 Binder.restoreCallingIdentity(token); 21283 } 21284 } 21285 } else { 21286 throw new IllegalArgumentException("No selective enforcement for " + permission); 21287 } 21288 } 21289 21290 @Override 21291 @Deprecated 21292 public boolean isPermissionEnforced(String permission) { 21293 return true; 21294 } 21295 21296 @Override 21297 public boolean isStorageLow() { 21298 final long token = Binder.clearCallingIdentity(); 21299 try { 21300 final DeviceStorageMonitorInternal 21301 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21302 if (dsm != null) { 21303 return dsm.isMemoryLow(); 21304 } else { 21305 return false; 21306 } 21307 } finally { 21308 Binder.restoreCallingIdentity(token); 21309 } 21310 } 21311 21312 @Override 21313 public IPackageInstaller getPackageInstaller() { 21314 return mInstallerService; 21315 } 21316 21317 private boolean userNeedsBadging(int userId) { 21318 int index = mUserNeedsBadging.indexOfKey(userId); 21319 if (index < 0) { 21320 final UserInfo userInfo; 21321 final long token = Binder.clearCallingIdentity(); 21322 try { 21323 userInfo = sUserManager.getUserInfo(userId); 21324 } finally { 21325 Binder.restoreCallingIdentity(token); 21326 } 21327 final boolean b; 21328 if (userInfo != null && userInfo.isManagedProfile()) { 21329 b = true; 21330 } else { 21331 b = false; 21332 } 21333 mUserNeedsBadging.put(userId, b); 21334 return b; 21335 } 21336 return mUserNeedsBadging.valueAt(index); 21337 } 21338 21339 @Override 21340 public KeySet getKeySetByAlias(String packageName, String alias) { 21341 if (packageName == null || alias == null) { 21342 return null; 21343 } 21344 synchronized(mPackages) { 21345 final PackageParser.Package pkg = mPackages.get(packageName); 21346 if (pkg == null) { 21347 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21348 throw new IllegalArgumentException("Unknown package: " + packageName); 21349 } 21350 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21351 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21352 } 21353 } 21354 21355 @Override 21356 public KeySet getSigningKeySet(String packageName) { 21357 if (packageName == null) { 21358 return null; 21359 } 21360 synchronized(mPackages) { 21361 final PackageParser.Package pkg = mPackages.get(packageName); 21362 if (pkg == null) { 21363 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21364 throw new IllegalArgumentException("Unknown package: " + packageName); 21365 } 21366 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21367 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21368 throw new SecurityException("May not access signing KeySet of other apps."); 21369 } 21370 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21371 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21372 } 21373 } 21374 21375 @Override 21376 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21377 if (packageName == null || ks == null) { 21378 return false; 21379 } 21380 synchronized(mPackages) { 21381 final PackageParser.Package pkg = mPackages.get(packageName); 21382 if (pkg == null) { 21383 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21384 throw new IllegalArgumentException("Unknown package: " + packageName); 21385 } 21386 IBinder ksh = ks.getToken(); 21387 if (ksh instanceof KeySetHandle) { 21388 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21389 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21390 } 21391 return false; 21392 } 21393 } 21394 21395 @Override 21396 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21397 if (packageName == null || ks == null) { 21398 return false; 21399 } 21400 synchronized(mPackages) { 21401 final PackageParser.Package pkg = mPackages.get(packageName); 21402 if (pkg == null) { 21403 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21404 throw new IllegalArgumentException("Unknown package: " + packageName); 21405 } 21406 IBinder ksh = ks.getToken(); 21407 if (ksh instanceof KeySetHandle) { 21408 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21409 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21410 } 21411 return false; 21412 } 21413 } 21414 21415 private void deletePackageIfUnusedLPr(final String packageName) { 21416 PackageSetting ps = mSettings.mPackages.get(packageName); 21417 if (ps == null) { 21418 return; 21419 } 21420 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21421 // TODO Implement atomic delete if package is unused 21422 // It is currently possible that the package will be deleted even if it is installed 21423 // after this method returns. 21424 mHandler.post(new Runnable() { 21425 public void run() { 21426 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21427 } 21428 }); 21429 } 21430 } 21431 21432 /** 21433 * Check and throw if the given before/after packages would be considered a 21434 * downgrade. 21435 */ 21436 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21437 throws PackageManagerException { 21438 if (after.versionCode < before.mVersionCode) { 21439 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21440 "Update version code " + after.versionCode + " is older than current " 21441 + before.mVersionCode); 21442 } else if (after.versionCode == before.mVersionCode) { 21443 if (after.baseRevisionCode < before.baseRevisionCode) { 21444 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21445 "Update base revision code " + after.baseRevisionCode 21446 + " is older than current " + before.baseRevisionCode); 21447 } 21448 21449 if (!ArrayUtils.isEmpty(after.splitNames)) { 21450 for (int i = 0; i < after.splitNames.length; i++) { 21451 final String splitName = after.splitNames[i]; 21452 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21453 if (j != -1) { 21454 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21455 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21456 "Update split " + splitName + " revision code " 21457 + after.splitRevisionCodes[i] + " is older than current " 21458 + before.splitRevisionCodes[j]); 21459 } 21460 } 21461 } 21462 } 21463 } 21464 } 21465 21466 private static class MoveCallbacks extends Handler { 21467 private static final int MSG_CREATED = 1; 21468 private static final int MSG_STATUS_CHANGED = 2; 21469 21470 private final RemoteCallbackList<IPackageMoveObserver> 21471 mCallbacks = new RemoteCallbackList<>(); 21472 21473 private final SparseIntArray mLastStatus = new SparseIntArray(); 21474 21475 public MoveCallbacks(Looper looper) { 21476 super(looper); 21477 } 21478 21479 public void register(IPackageMoveObserver callback) { 21480 mCallbacks.register(callback); 21481 } 21482 21483 public void unregister(IPackageMoveObserver callback) { 21484 mCallbacks.unregister(callback); 21485 } 21486 21487 @Override 21488 public void handleMessage(Message msg) { 21489 final SomeArgs args = (SomeArgs) msg.obj; 21490 final int n = mCallbacks.beginBroadcast(); 21491 for (int i = 0; i < n; i++) { 21492 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21493 try { 21494 invokeCallback(callback, msg.what, args); 21495 } catch (RemoteException ignored) { 21496 } 21497 } 21498 mCallbacks.finishBroadcast(); 21499 args.recycle(); 21500 } 21501 21502 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21503 throws RemoteException { 21504 switch (what) { 21505 case MSG_CREATED: { 21506 callback.onCreated(args.argi1, (Bundle) args.arg2); 21507 break; 21508 } 21509 case MSG_STATUS_CHANGED: { 21510 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21511 break; 21512 } 21513 } 21514 } 21515 21516 private void notifyCreated(int moveId, Bundle extras) { 21517 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21518 21519 final SomeArgs args = SomeArgs.obtain(); 21520 args.argi1 = moveId; 21521 args.arg2 = extras; 21522 obtainMessage(MSG_CREATED, args).sendToTarget(); 21523 } 21524 21525 private void notifyStatusChanged(int moveId, int status) { 21526 notifyStatusChanged(moveId, status, -1); 21527 } 21528 21529 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21530 Slog.v(TAG, "Move " + moveId + " status " + status); 21531 21532 final SomeArgs args = SomeArgs.obtain(); 21533 args.argi1 = moveId; 21534 args.argi2 = status; 21535 args.arg3 = estMillis; 21536 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21537 21538 synchronized (mLastStatus) { 21539 mLastStatus.put(moveId, status); 21540 } 21541 } 21542 } 21543 21544 private final static class OnPermissionChangeListeners extends Handler { 21545 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21546 21547 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21548 new RemoteCallbackList<>(); 21549 21550 public OnPermissionChangeListeners(Looper looper) { 21551 super(looper); 21552 } 21553 21554 @Override 21555 public void handleMessage(Message msg) { 21556 switch (msg.what) { 21557 case MSG_ON_PERMISSIONS_CHANGED: { 21558 final int uid = msg.arg1; 21559 handleOnPermissionsChanged(uid); 21560 } break; 21561 } 21562 } 21563 21564 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21565 mPermissionListeners.register(listener); 21566 21567 } 21568 21569 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21570 mPermissionListeners.unregister(listener); 21571 } 21572 21573 public void onPermissionsChanged(int uid) { 21574 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21575 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21576 } 21577 } 21578 21579 private void handleOnPermissionsChanged(int uid) { 21580 final int count = mPermissionListeners.beginBroadcast(); 21581 try { 21582 for (int i = 0; i < count; i++) { 21583 IOnPermissionsChangeListener callback = mPermissionListeners 21584 .getBroadcastItem(i); 21585 try { 21586 callback.onPermissionsChanged(uid); 21587 } catch (RemoteException e) { 21588 Log.e(TAG, "Permission listener is dead", e); 21589 } 21590 } 21591 } finally { 21592 mPermissionListeners.finishBroadcast(); 21593 } 21594 } 21595 } 21596 21597 private class PackageManagerInternalImpl extends PackageManagerInternal { 21598 @Override 21599 public void setLocationPackagesProvider(PackagesProvider provider) { 21600 synchronized (mPackages) { 21601 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21602 } 21603 } 21604 21605 @Override 21606 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21607 synchronized (mPackages) { 21608 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21609 } 21610 } 21611 21612 @Override 21613 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21614 synchronized (mPackages) { 21615 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21616 } 21617 } 21618 21619 @Override 21620 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21621 synchronized (mPackages) { 21622 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21623 } 21624 } 21625 21626 @Override 21627 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21628 synchronized (mPackages) { 21629 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21630 } 21631 } 21632 21633 @Override 21634 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21635 synchronized (mPackages) { 21636 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21637 } 21638 } 21639 21640 @Override 21641 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21642 synchronized (mPackages) { 21643 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21644 packageName, userId); 21645 } 21646 } 21647 21648 @Override 21649 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21650 synchronized (mPackages) { 21651 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21652 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21653 packageName, userId); 21654 } 21655 } 21656 21657 @Override 21658 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21659 synchronized (mPackages) { 21660 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21661 packageName, userId); 21662 } 21663 } 21664 21665 @Override 21666 public void setKeepUninstalledPackages(final List<String> packageList) { 21667 Preconditions.checkNotNull(packageList); 21668 List<String> removedFromList = null; 21669 synchronized (mPackages) { 21670 if (mKeepUninstalledPackages != null) { 21671 final int packagesCount = mKeepUninstalledPackages.size(); 21672 for (int i = 0; i < packagesCount; i++) { 21673 String oldPackage = mKeepUninstalledPackages.get(i); 21674 if (packageList != null && packageList.contains(oldPackage)) { 21675 continue; 21676 } 21677 if (removedFromList == null) { 21678 removedFromList = new ArrayList<>(); 21679 } 21680 removedFromList.add(oldPackage); 21681 } 21682 } 21683 mKeepUninstalledPackages = new ArrayList<>(packageList); 21684 if (removedFromList != null) { 21685 final int removedCount = removedFromList.size(); 21686 for (int i = 0; i < removedCount; i++) { 21687 deletePackageIfUnusedLPr(removedFromList.get(i)); 21688 } 21689 } 21690 } 21691 } 21692 21693 @Override 21694 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21695 synchronized (mPackages) { 21696 // If we do not support permission review, done. 21697 if (!mPermissionReviewRequired) { 21698 return false; 21699 } 21700 21701 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21702 if (packageSetting == null) { 21703 return false; 21704 } 21705 21706 // Permission review applies only to apps not supporting the new permission model. 21707 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21708 return false; 21709 } 21710 21711 // Legacy apps have the permission and get user consent on launch. 21712 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21713 return permissionsState.isPermissionReviewRequired(userId); 21714 } 21715 } 21716 21717 @Override 21718 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21719 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21720 } 21721 21722 @Override 21723 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21724 int userId) { 21725 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21726 } 21727 21728 @Override 21729 public void setDeviceAndProfileOwnerPackages( 21730 int deviceOwnerUserId, String deviceOwnerPackage, 21731 SparseArray<String> profileOwnerPackages) { 21732 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21733 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21734 } 21735 21736 @Override 21737 public boolean isPackageDataProtected(int userId, String packageName) { 21738 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21739 } 21740 21741 @Override 21742 public boolean isPackageEphemeral(int userId, String packageName) { 21743 synchronized (mPackages) { 21744 PackageParser.Package p = mPackages.get(packageName); 21745 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21746 } 21747 } 21748 21749 @Override 21750 public boolean wasPackageEverLaunched(String packageName, int userId) { 21751 synchronized (mPackages) { 21752 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21753 } 21754 } 21755 21756 @Override 21757 public void grantRuntimePermission(String packageName, String name, int userId, 21758 boolean overridePolicy) { 21759 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21760 overridePolicy); 21761 } 21762 21763 @Override 21764 public void revokeRuntimePermission(String packageName, String name, int userId, 21765 boolean overridePolicy) { 21766 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21767 overridePolicy); 21768 } 21769 21770 @Override 21771 public String getNameForUid(int uid) { 21772 return PackageManagerService.this.getNameForUid(uid); 21773 } 21774 21775 @Override 21776 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21777 Intent origIntent, String resolvedType, Intent launchIntent, 21778 String callingPackage, int userId) { 21779 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21780 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21781 } 21782 21783 public String getSetupWizardPackageName() { 21784 return mSetupWizardPackage; 21785 } 21786 } 21787 21788 @Override 21789 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21790 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21791 synchronized (mPackages) { 21792 final long identity = Binder.clearCallingIdentity(); 21793 try { 21794 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21795 packageNames, userId); 21796 } finally { 21797 Binder.restoreCallingIdentity(identity); 21798 } 21799 } 21800 } 21801 21802 private static void enforceSystemOrPhoneCaller(String tag) { 21803 int callingUid = Binder.getCallingUid(); 21804 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21805 throw new SecurityException( 21806 "Cannot call " + tag + " from UID " + callingUid); 21807 } 21808 } 21809 21810 boolean isHistoricalPackageUsageAvailable() { 21811 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21812 } 21813 21814 /** 21815 * Return a <b>copy</b> of the collection of packages known to the package manager. 21816 * @return A copy of the values of mPackages. 21817 */ 21818 Collection<PackageParser.Package> getPackages() { 21819 synchronized (mPackages) { 21820 return new ArrayList<>(mPackages.values()); 21821 } 21822 } 21823 21824 /** 21825 * Logs process start information (including base APK hash) to the security log. 21826 * @hide 21827 */ 21828 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21829 String apkFile, int pid) { 21830 if (!SecurityLog.isLoggingEnabled()) { 21831 return; 21832 } 21833 Bundle data = new Bundle(); 21834 data.putLong("startTimestamp", System.currentTimeMillis()); 21835 data.putString("processName", processName); 21836 data.putInt("uid", uid); 21837 data.putString("seinfo", seinfo); 21838 data.putString("apkFile", apkFile); 21839 data.putInt("pid", pid); 21840 Message msg = mProcessLoggingHandler.obtainMessage( 21841 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21842 msg.setData(data); 21843 mProcessLoggingHandler.sendMessage(msg); 21844 } 21845 21846 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21847 return mCompilerStats.getPackageStats(pkgName); 21848 } 21849 21850 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21851 return getOrCreateCompilerPackageStats(pkg.packageName); 21852 } 21853 21854 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21855 return mCompilerStats.getOrCreatePackageStats(pkgName); 21856 } 21857 21858 public void deleteCompilerPackageStats(String pkgName) { 21859 mCompilerStats.deletePackageStats(pkgName); 21860 } 21861} 21862