PackageManagerService.java revision bbdd8e4a3b4bd9bcf4574005b42bed83b4d4ed31
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.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.InstantAppInfo; 132import android.content.pm.EphemeralRequest; 133import android.content.pm.EphemeralResolveInfo; 134import android.content.pm.EphemeralResponse; 135import android.content.pm.FallbackCategoryProvider; 136import android.content.pm.FeatureInfo; 137import android.content.pm.IOnPermissionsChangeListener; 138import android.content.pm.IPackageDataObserver; 139import android.content.pm.IPackageDeleteObserver; 140import android.content.pm.IPackageDeleteObserver2; 141import android.content.pm.IPackageInstallObserver2; 142import android.content.pm.IPackageInstaller; 143import android.content.pm.IPackageManager; 144import android.content.pm.IPackageMoveObserver; 145import android.content.pm.IPackageStatsObserver; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.SELinuxUtil; 168import android.content.pm.ServiceInfo; 169import android.content.pm.SharedLibraryInfo; 170import android.content.pm.Signature; 171import android.content.pm.UserInfo; 172import android.content.pm.VerifierDeviceIdentity; 173import android.content.pm.VerifierInfo; 174import android.content.pm.VersionedPackage; 175import android.content.res.Resources; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageManagerInternal; 208import android.os.storage.StorageEventListener; 209import android.os.storage.StorageManager; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.system.ErrnoException; 217import android.system.Os; 218import android.text.TextUtils; 219import android.text.format.DateUtils; 220import android.util.ArrayMap; 221import android.util.ArraySet; 222import android.util.Base64; 223import android.util.DisplayMetrics; 224import android.util.EventLog; 225import android.util.ExceptionUtils; 226import android.util.Log; 227import android.util.LogPrinter; 228import android.util.MathUtils; 229import android.util.PackageUtils; 230import android.util.Pair; 231import android.util.PrintStreamPrinter; 232import android.util.Slog; 233import android.util.SparseArray; 234import android.util.SparseBooleanArray; 235import android.util.SparseIntArray; 236import android.util.Xml; 237import android.util.jar.StrictJarFile; 238import android.view.Display; 239 240import com.android.internal.R; 241import com.android.internal.annotations.GuardedBy; 242import com.android.internal.app.IMediaContainerService; 243import com.android.internal.app.ResolverActivity; 244import com.android.internal.content.NativeLibraryHelper; 245import com.android.internal.content.PackageHelper; 246import com.android.internal.logging.MetricsLogger; 247import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 248import com.android.internal.os.IParcelFileDescriptorFactory; 249import com.android.internal.os.RoSystemProperties; 250import com.android.internal.os.SomeArgs; 251import com.android.internal.os.Zygote; 252import com.android.internal.telephony.CarrierAppUtils; 253import com.android.internal.util.ArrayUtils; 254import com.android.internal.util.FastPrintWriter; 255import com.android.internal.util.FastXmlSerializer; 256import com.android.internal.util.IndentingPrintWriter; 257import com.android.internal.util.Preconditions; 258import com.android.internal.util.XmlUtils; 259import com.android.server.AttributeCache; 260import com.android.server.BackgroundDexOptJobService; 261import com.android.server.EventLogTags; 262import com.android.server.FgThread; 263import com.android.server.IntentResolver; 264import com.android.server.LocalServices; 265import com.android.server.ServiceThread; 266import com.android.server.SystemConfig; 267import com.android.server.Watchdog; 268import com.android.server.net.NetworkPolicyManagerInternal; 269import com.android.server.pm.Installer.InstallerException; 270import com.android.server.pm.PermissionsState.PermissionState; 271import com.android.server.pm.Settings.DatabaseVersion; 272import com.android.server.pm.Settings.VersionInfo; 273import com.android.server.pm.dex.DexManager; 274import com.android.server.storage.DeviceStorageMonitorInternal; 275 276import dalvik.system.CloseGuard; 277import dalvik.system.DexFile; 278import dalvik.system.VMRuntime; 279 280import libcore.io.IoUtils; 281import libcore.util.EmptyArray; 282 283import org.xmlpull.v1.XmlPullParser; 284import org.xmlpull.v1.XmlPullParserException; 285import org.xmlpull.v1.XmlSerializer; 286 287import java.io.BufferedOutputStream; 288import java.io.BufferedReader; 289import java.io.ByteArrayInputStream; 290import java.io.ByteArrayOutputStream; 291import java.io.File; 292import java.io.FileDescriptor; 293import java.io.FileInputStream; 294import java.io.FileNotFoundException; 295import java.io.FileOutputStream; 296import java.io.FileReader; 297import java.io.FilenameFilter; 298import java.io.IOException; 299import java.io.PrintWriter; 300import java.nio.charset.StandardCharsets; 301import java.security.DigestInputStream; 302import java.security.MessageDigest; 303import java.security.NoSuchAlgorithmException; 304import java.security.PublicKey; 305import java.security.SecureRandom; 306import java.security.cert.Certificate; 307import java.security.cert.CertificateEncodingException; 308import java.security.cert.CertificateException; 309import java.text.SimpleDateFormat; 310import java.util.ArrayList; 311import java.util.Arrays; 312import java.util.Collection; 313import java.util.Collections; 314import java.util.Comparator; 315import java.util.Date; 316import java.util.HashSet; 317import java.util.HashMap; 318import java.util.Iterator; 319import java.util.List; 320import java.util.Map; 321import java.util.Objects; 322import java.util.Set; 323import java.util.concurrent.CountDownLatch; 324import java.util.concurrent.TimeUnit; 325import java.util.concurrent.atomic.AtomicBoolean; 326import java.util.concurrent.atomic.AtomicInteger; 327 328/** 329 * Keep track of all those APKs everywhere. 330 * <p> 331 * Internally there are two important locks: 332 * <ul> 333 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 334 * and other related state. It is a fine-grained lock that should only be held 335 * momentarily, as it's one of the most contended locks in the system. 336 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 337 * operations typically involve heavy lifting of application data on disk. Since 338 * {@code installd} is single-threaded, and it's operations can often be slow, 339 * this lock should never be acquired while already holding {@link #mPackages}. 340 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 341 * holding {@link #mInstallLock}. 342 * </ul> 343 * Many internal methods rely on the caller to hold the appropriate locks, and 344 * this contract is expressed through method name suffixes: 345 * <ul> 346 * <li>fooLI(): the caller must hold {@link #mInstallLock} 347 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 348 * being modified must be frozen 349 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 350 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 351 * </ul> 352 * <p> 353 * Because this class is very central to the platform's security; please run all 354 * CTS and unit tests whenever making modifications: 355 * 356 * <pre> 357 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 358 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 359 * </pre> 360 */ 361public class PackageManagerService extends IPackageManager.Stub { 362 static final String TAG = "PackageManager"; 363 static final boolean DEBUG_SETTINGS = false; 364 static final boolean DEBUG_PREFERRED = false; 365 static final boolean DEBUG_UPGRADE = false; 366 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 367 private static final boolean DEBUG_BACKUP = false; 368 private static final boolean DEBUG_INSTALL = false; 369 private static final boolean DEBUG_REMOVE = false; 370 private static final boolean DEBUG_BROADCASTS = false; 371 private static final boolean DEBUG_SHOW_INFO = false; 372 private static final boolean DEBUG_PACKAGE_INFO = false; 373 private static final boolean DEBUG_INTENT_MATCHING = false; 374 private static final boolean DEBUG_PACKAGE_SCANNING = false; 375 private static final boolean DEBUG_VERIFY = false; 376 private static final boolean DEBUG_FILTERS = false; 377 378 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 379 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 380 // user, but by default initialize to this. 381 public static final boolean DEBUG_DEXOPT = false; 382 383 private static final boolean DEBUG_ABI_SELECTION = false; 384 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 385 private static final boolean DEBUG_TRIAGED_MISSING = false; 386 private static final boolean DEBUG_APP_DATA = false; 387 388 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 389 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 390 391 private static final boolean DISABLE_EPHEMERAL_APPS = false; 392 private static final boolean HIDE_EPHEMERAL_APIS = false; 393 394 private static final boolean ENABLE_QUOTA = 395 SystemProperties.getBoolean("persist.fw.quota", false); 396 397 private static final int RADIO_UID = Process.PHONE_UID; 398 private static final int LOG_UID = Process.LOG_UID; 399 private static final int NFC_UID = Process.NFC_UID; 400 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 401 private static final int SHELL_UID = Process.SHELL_UID; 402 403 // Cap the size of permission trees that 3rd party apps can define 404 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 405 406 // Suffix used during package installation when copying/moving 407 // package apks to install directory. 408 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 409 410 static final int SCAN_NO_DEX = 1<<1; 411 static final int SCAN_FORCE_DEX = 1<<2; 412 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 413 static final int SCAN_NEW_INSTALL = 1<<4; 414 static final int SCAN_UPDATE_TIME = 1<<5; 415 static final int SCAN_BOOTING = 1<<6; 416 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 417 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 418 static final int SCAN_REPLACING = 1<<9; 419 static final int SCAN_REQUIRE_KNOWN = 1<<10; 420 static final int SCAN_MOVE = 1<<11; 421 static final int SCAN_INITIAL = 1<<12; 422 static final int SCAN_CHECK_ONLY = 1<<13; 423 static final int SCAN_DONT_KILL_APP = 1<<14; 424 static final int SCAN_IGNORE_FROZEN = 1<<15; 425 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 426 static final int SCAN_AS_INSTANT_APP = 1<<17; 427 static final int SCAN_AS_FULL_APP = 1<<18; 428 /** Should not be with the scan flags */ 429 static final int FLAGS_REMOVE_CHATTY = 1<<31; 430 431 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 432 433 private static final int[] EMPTY_INT_ARRAY = new int[0]; 434 435 /** 436 * Timeout (in milliseconds) after which the watchdog should declare that 437 * our handler thread is wedged. The usual default for such things is one 438 * minute but we sometimes do very lengthy I/O operations on this thread, 439 * such as installing multi-gigabyte applications, so ours needs to be longer. 440 */ 441 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 442 443 /** 444 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 445 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 446 * settings entry if available, otherwise we use the hardcoded default. If it's been 447 * more than this long since the last fstrim, we force one during the boot sequence. 448 * 449 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 450 * one gets run at the next available charging+idle time. This final mandatory 451 * no-fstrim check kicks in only of the other scheduling criteria is never met. 452 */ 453 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 454 455 /** 456 * Whether verification is enabled by default. 457 */ 458 private static final boolean DEFAULT_VERIFY_ENABLE = true; 459 460 /** 461 * The default maximum time to wait for the verification agent to return in 462 * milliseconds. 463 */ 464 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 465 466 /** 467 * The default response for package verification timeout. 468 * 469 * This can be either PackageManager.VERIFICATION_ALLOW or 470 * PackageManager.VERIFICATION_REJECT. 471 */ 472 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 473 474 static final String PLATFORM_PACKAGE_NAME = "android"; 475 476 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 477 478 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 479 DEFAULT_CONTAINER_PACKAGE, 480 "com.android.defcontainer.DefaultContainerService"); 481 482 private static final String KILL_APP_REASON_GIDS_CHANGED = 483 "permission grant or revoke changed gids"; 484 485 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 486 "permissions revoked"; 487 488 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 489 490 private static final String PACKAGE_SCHEME = "package"; 491 492 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 493 /** 494 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 495 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 496 * VENDOR_OVERLAY_DIR. 497 */ 498 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 499 /** 500 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 501 * is in VENDOR_OVERLAY_THEME_PROPERTY. 502 */ 503 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 504 = "persist.vendor.overlay.theme"; 505 506 /** Permission grant: not grant the permission. */ 507 private static final int GRANT_DENIED = 1; 508 509 /** Permission grant: grant the permission as an install permission. */ 510 private static final int GRANT_INSTALL = 2; 511 512 /** Permission grant: grant the permission as a runtime one. */ 513 private static final int GRANT_RUNTIME = 3; 514 515 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 516 private static final int GRANT_UPGRADE = 4; 517 518 /** Canonical intent used to identify what counts as a "web browser" app */ 519 private static final Intent sBrowserIntent; 520 static { 521 sBrowserIntent = new Intent(); 522 sBrowserIntent.setAction(Intent.ACTION_VIEW); 523 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 524 sBrowserIntent.setData(Uri.parse("http:")); 525 } 526 527 /** 528 * The set of all protected actions [i.e. those actions for which a high priority 529 * intent filter is disallowed]. 530 */ 531 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 532 static { 533 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 534 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 535 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 536 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 537 } 538 539 // Compilation reasons. 540 public static final int REASON_FIRST_BOOT = 0; 541 public static final int REASON_BOOT = 1; 542 public static final int REASON_INSTALL = 2; 543 public static final int REASON_BACKGROUND_DEXOPT = 3; 544 public static final int REASON_AB_OTA = 4; 545 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 546 public static final int REASON_SHARED_APK = 6; 547 public static final int REASON_FORCED_DEXOPT = 7; 548 public static final int REASON_CORE_APP = 8; 549 550 public static final int REASON_LAST = REASON_CORE_APP; 551 552 /** All dangerous permission names in the same order as the events in MetricsEvent */ 553 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 554 Manifest.permission.READ_CALENDAR, 555 Manifest.permission.WRITE_CALENDAR, 556 Manifest.permission.CAMERA, 557 Manifest.permission.READ_CONTACTS, 558 Manifest.permission.WRITE_CONTACTS, 559 Manifest.permission.GET_ACCOUNTS, 560 Manifest.permission.ACCESS_FINE_LOCATION, 561 Manifest.permission.ACCESS_COARSE_LOCATION, 562 Manifest.permission.RECORD_AUDIO, 563 Manifest.permission.READ_PHONE_STATE, 564 Manifest.permission.CALL_PHONE, 565 Manifest.permission.READ_CALL_LOG, 566 Manifest.permission.WRITE_CALL_LOG, 567 Manifest.permission.ADD_VOICEMAIL, 568 Manifest.permission.USE_SIP, 569 Manifest.permission.PROCESS_OUTGOING_CALLS, 570 Manifest.permission.READ_CELL_BROADCASTS, 571 Manifest.permission.BODY_SENSORS, 572 Manifest.permission.SEND_SMS, 573 Manifest.permission.RECEIVE_SMS, 574 Manifest.permission.READ_SMS, 575 Manifest.permission.RECEIVE_WAP_PUSH, 576 Manifest.permission.RECEIVE_MMS, 577 Manifest.permission.READ_EXTERNAL_STORAGE, 578 Manifest.permission.WRITE_EXTERNAL_STORAGE, 579 Manifest.permission.READ_PHONE_NUMBER); 580 581 582 /** 583 * Version number for the package parser cache. Increment this whenever the format or 584 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 585 */ 586 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 587 588 /** 589 * Whether the package parser cache is enabled. 590 */ 591 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 592 593 final ServiceThread mHandlerThread; 594 595 final PackageHandler mHandler; 596 597 private final ProcessLoggingHandler mProcessLoggingHandler; 598 599 /** 600 * Messages for {@link #mHandler} that need to wait for system ready before 601 * being dispatched. 602 */ 603 private ArrayList<Message> mPostSystemReadyMessages; 604 605 final int mSdkVersion = Build.VERSION.SDK_INT; 606 607 final Context mContext; 608 final boolean mFactoryTest; 609 final boolean mOnlyCore; 610 final DisplayMetrics mMetrics; 611 final int mDefParseFlags; 612 final String[] mSeparateProcesses; 613 final boolean mIsUpgrade; 614 final boolean mIsPreNUpgrade; 615 final boolean mIsPreNMR1Upgrade; 616 617 @GuardedBy("mPackages") 618 private boolean mDexOptDialogShown; 619 620 /** The location for ASEC container files on internal storage. */ 621 final String mAsecInternalPath; 622 623 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 624 // LOCK HELD. Can be called with mInstallLock held. 625 @GuardedBy("mInstallLock") 626 final Installer mInstaller; 627 628 /** Directory where installed third-party apps stored */ 629 final File mAppInstallDir; 630 631 /** 632 * Directory to which applications installed internally have their 633 * 32 bit native libraries copied. 634 */ 635 private File mAppLib32InstallDir; 636 637 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 638 // apps. 639 final File mDrmAppPrivateInstallDir; 640 641 // ---------------------------------------------------------------- 642 643 // Lock for state used when installing and doing other long running 644 // operations. Methods that must be called with this lock held have 645 // the suffix "LI". 646 final Object mInstallLock = new Object(); 647 648 // ---------------------------------------------------------------- 649 650 // Keys are String (package name), values are Package. This also serves 651 // as the lock for the global state. Methods that must be called with 652 // this lock held have the prefix "LP". 653 @GuardedBy("mPackages") 654 final ArrayMap<String, PackageParser.Package> mPackages = 655 new ArrayMap<String, PackageParser.Package>(); 656 657 final ArrayMap<String, Set<String>> mKnownCodebase = 658 new ArrayMap<String, Set<String>>(); 659 660 // Tracks available target package names -> overlay package paths. 661 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 662 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 663 664 /** 665 * Tracks new system packages [received in an OTA] that we expect to 666 * find updated user-installed versions. Keys are package name, values 667 * are package location. 668 */ 669 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 670 /** 671 * Tracks high priority intent filters for protected actions. During boot, certain 672 * filter actions are protected and should never be allowed to have a high priority 673 * intent filter for them. However, there is one, and only one exception -- the 674 * setup wizard. It must be able to define a high priority intent filter for these 675 * actions to ensure there are no escapes from the wizard. We need to delay processing 676 * of these during boot as we need to look at all of the system packages in order 677 * to know which component is the setup wizard. 678 */ 679 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 680 /** 681 * Whether or not processing protected filters should be deferred. 682 */ 683 private boolean mDeferProtectedFilters = true; 684 685 /** 686 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 687 */ 688 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 689 /** 690 * Whether or not system app permissions should be promoted from install to runtime. 691 */ 692 boolean mPromoteSystemApps; 693 694 @GuardedBy("mPackages") 695 final Settings mSettings; 696 697 /** 698 * Set of package names that are currently "frozen", which means active 699 * surgery is being done on the code/data for that package. The platform 700 * will refuse to launch frozen packages to avoid race conditions. 701 * 702 * @see PackageFreezer 703 */ 704 @GuardedBy("mPackages") 705 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 706 707 final ProtectedPackages mProtectedPackages; 708 709 boolean mFirstBoot; 710 711 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 712 713 // System configuration read by SystemConfig. 714 final int[] mGlobalGids; 715 final SparseArray<ArraySet<String>> mSystemPermissions; 716 @GuardedBy("mAvailableFeatures") 717 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 718 719 // If mac_permissions.xml was found for seinfo labeling. 720 boolean mFoundPolicyFile; 721 722 private final InstantAppRegistry mInstantAppRegistry; 723 724 @GuardedBy("mPackages") 725 int mChangedPackagesSequenceNumber; 726 /** 727 * List of changed [installed, removed or updated] packages. 728 * mapping from user id -> sequence number -> package name 729 */ 730 @GuardedBy("mPackages") 731 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 732 /** 733 * The sequence number of the last change to a package. 734 * mapping from user id -> package name -> sequence number 735 */ 736 @GuardedBy("mPackages") 737 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 738 739 public static final class SharedLibraryEntry { 740 public final String path; 741 public final String apk; 742 public final SharedLibraryInfo info; 743 744 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 745 String declaringPackageName, int declaringPackageVersionCode) { 746 path = _path; 747 apk = _apk; 748 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 749 declaringPackageName, declaringPackageVersionCode), null); 750 } 751 } 752 753 // Currently known shared libraries. 754 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 755 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 756 new ArrayMap<>(); 757 758 // All available activities, for your resolving pleasure. 759 final ActivityIntentResolver mActivities = 760 new ActivityIntentResolver(); 761 762 // All available receivers, for your resolving pleasure. 763 final ActivityIntentResolver mReceivers = 764 new ActivityIntentResolver(); 765 766 // All available services, for your resolving pleasure. 767 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 768 769 // All available providers, for your resolving pleasure. 770 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 771 772 // Mapping from provider base names (first directory in content URI codePath) 773 // to the provider information. 774 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 775 new ArrayMap<String, PackageParser.Provider>(); 776 777 // Mapping from instrumentation class names to info about them. 778 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 779 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 780 781 // Mapping from permission names to info about them. 782 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 783 new ArrayMap<String, PackageParser.PermissionGroup>(); 784 785 // Packages whose data we have transfered into another package, thus 786 // should no longer exist. 787 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 788 789 // Broadcast actions that are only available to the system. 790 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 791 792 /** List of packages waiting for verification. */ 793 final SparseArray<PackageVerificationState> mPendingVerification 794 = new SparseArray<PackageVerificationState>(); 795 796 /** Set of packages associated with each app op permission. */ 797 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 798 799 final PackageInstallerService mInstallerService; 800 801 private final PackageDexOptimizer mPackageDexOptimizer; 802 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 803 // is used by other apps). 804 private final DexManager mDexManager; 805 806 private AtomicInteger mNextMoveId = new AtomicInteger(); 807 private final MoveCallbacks mMoveCallbacks; 808 809 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 810 811 // Cache of users who need badging. 812 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 813 814 /** Token for keys in mPendingVerification. */ 815 private int mPendingVerificationToken = 0; 816 817 volatile boolean mSystemReady; 818 volatile boolean mSafeMode; 819 volatile boolean mHasSystemUidErrors; 820 821 ApplicationInfo mAndroidApplication; 822 final ActivityInfo mResolveActivity = new ActivityInfo(); 823 final ResolveInfo mResolveInfo = new ResolveInfo(); 824 ComponentName mResolveComponentName; 825 PackageParser.Package mPlatformPackage; 826 ComponentName mCustomResolverComponentName; 827 828 boolean mResolverReplaced = false; 829 830 private final @Nullable ComponentName mIntentFilterVerifierComponent; 831 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 832 833 private int mIntentFilterVerificationToken = 0; 834 835 /** The service connection to the ephemeral resolver */ 836 final EphemeralResolverConnection mEphemeralResolverConnection; 837 838 /** Component used to install ephemeral applications */ 839 ComponentName mEphemeralInstallerComponent; 840 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 841 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 842 843 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 844 = new SparseArray<IntentFilterVerificationState>(); 845 846 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 847 848 // List of packages names to keep cached, even if they are uninstalled for all users 849 private List<String> mKeepUninstalledPackages; 850 851 private UserManagerInternal mUserManagerInternal; 852 853 private File mCacheDir; 854 855 private ArraySet<String> mPrivappPermissionsViolations; 856 857 private static class IFVerificationParams { 858 PackageParser.Package pkg; 859 boolean replacing; 860 int userId; 861 int verifierUid; 862 863 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 864 int _userId, int _verifierUid) { 865 pkg = _pkg; 866 replacing = _replacing; 867 userId = _userId; 868 replacing = _replacing; 869 verifierUid = _verifierUid; 870 } 871 } 872 873 private interface IntentFilterVerifier<T extends IntentFilter> { 874 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 875 T filter, String packageName); 876 void startVerifications(int userId); 877 void receiveVerificationResponse(int verificationId); 878 } 879 880 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 881 private Context mContext; 882 private ComponentName mIntentFilterVerifierComponent; 883 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 884 885 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 886 mContext = context; 887 mIntentFilterVerifierComponent = verifierComponent; 888 } 889 890 private String getDefaultScheme() { 891 return IntentFilter.SCHEME_HTTPS; 892 } 893 894 @Override 895 public void startVerifications(int userId) { 896 // Launch verifications requests 897 int count = mCurrentIntentFilterVerifications.size(); 898 for (int n=0; n<count; n++) { 899 int verificationId = mCurrentIntentFilterVerifications.get(n); 900 final IntentFilterVerificationState ivs = 901 mIntentFilterVerificationStates.get(verificationId); 902 903 String packageName = ivs.getPackageName(); 904 905 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 906 final int filterCount = filters.size(); 907 ArraySet<String> domainsSet = new ArraySet<>(); 908 for (int m=0; m<filterCount; m++) { 909 PackageParser.ActivityIntentInfo filter = filters.get(m); 910 domainsSet.addAll(filter.getHostsList()); 911 } 912 synchronized (mPackages) { 913 if (mSettings.createIntentFilterVerificationIfNeededLPw( 914 packageName, domainsSet) != null) { 915 scheduleWriteSettingsLocked(); 916 } 917 } 918 sendVerificationRequest(userId, verificationId, ivs); 919 } 920 mCurrentIntentFilterVerifications.clear(); 921 } 922 923 private void sendVerificationRequest(int userId, int verificationId, 924 IntentFilterVerificationState ivs) { 925 926 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 927 verificationIntent.putExtra( 928 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 929 verificationId); 930 verificationIntent.putExtra( 931 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 932 getDefaultScheme()); 933 verificationIntent.putExtra( 934 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 935 ivs.getHostsString()); 936 verificationIntent.putExtra( 937 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 938 ivs.getPackageName()); 939 verificationIntent.setComponent(mIntentFilterVerifierComponent); 940 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 941 942 UserHandle user = new UserHandle(userId); 943 mContext.sendBroadcastAsUser(verificationIntent, user); 944 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 945 "Sending IntentFilter verification broadcast"); 946 } 947 948 public void receiveVerificationResponse(int verificationId) { 949 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 950 951 final boolean verified = ivs.isVerified(); 952 953 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 954 final int count = filters.size(); 955 if (DEBUG_DOMAIN_VERIFICATION) { 956 Slog.i(TAG, "Received verification response " + verificationId 957 + " for " + count + " filters, verified=" + verified); 958 } 959 for (int n=0; n<count; n++) { 960 PackageParser.ActivityIntentInfo filter = filters.get(n); 961 filter.setVerified(verified); 962 963 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 964 + " verified with result:" + verified + " and hosts:" 965 + ivs.getHostsString()); 966 } 967 968 mIntentFilterVerificationStates.remove(verificationId); 969 970 final String packageName = ivs.getPackageName(); 971 IntentFilterVerificationInfo ivi = null; 972 973 synchronized (mPackages) { 974 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 975 } 976 if (ivi == null) { 977 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 978 + verificationId + " packageName:" + packageName); 979 return; 980 } 981 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 982 "Updating IntentFilterVerificationInfo for package " + packageName 983 +" verificationId:" + verificationId); 984 985 synchronized (mPackages) { 986 if (verified) { 987 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 988 } else { 989 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 990 } 991 scheduleWriteSettingsLocked(); 992 993 final int userId = ivs.getUserId(); 994 if (userId != UserHandle.USER_ALL) { 995 final int userStatus = 996 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 997 998 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 999 boolean needUpdate = false; 1000 1001 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1002 // already been set by the User thru the Disambiguation dialog 1003 switch (userStatus) { 1004 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1005 if (verified) { 1006 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1007 } else { 1008 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1009 } 1010 needUpdate = true; 1011 break; 1012 1013 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1014 if (verified) { 1015 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1016 needUpdate = true; 1017 } 1018 break; 1019 1020 default: 1021 // Nothing to do 1022 } 1023 1024 if (needUpdate) { 1025 mSettings.updateIntentFilterVerificationStatusLPw( 1026 packageName, updatedStatus, userId); 1027 scheduleWritePackageRestrictionsLocked(userId); 1028 } 1029 } 1030 } 1031 } 1032 1033 @Override 1034 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1035 ActivityIntentInfo filter, String packageName) { 1036 if (!hasValidDomains(filter)) { 1037 return false; 1038 } 1039 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1040 if (ivs == null) { 1041 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1042 packageName); 1043 } 1044 if (DEBUG_DOMAIN_VERIFICATION) { 1045 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1046 } 1047 ivs.addFilter(filter); 1048 return true; 1049 } 1050 1051 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1052 int userId, int verificationId, String packageName) { 1053 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1054 verifierUid, userId, packageName); 1055 ivs.setPendingState(); 1056 synchronized (mPackages) { 1057 mIntentFilterVerificationStates.append(verificationId, ivs); 1058 mCurrentIntentFilterVerifications.add(verificationId); 1059 } 1060 return ivs; 1061 } 1062 } 1063 1064 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1065 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1066 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1067 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1068 } 1069 1070 // Set of pending broadcasts for aggregating enable/disable of components. 1071 static class PendingPackageBroadcasts { 1072 // for each user id, a map of <package name -> components within that package> 1073 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1074 1075 public PendingPackageBroadcasts() { 1076 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1077 } 1078 1079 public ArrayList<String> get(int userId, String packageName) { 1080 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1081 return packages.get(packageName); 1082 } 1083 1084 public void put(int userId, String packageName, ArrayList<String> components) { 1085 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1086 packages.put(packageName, components); 1087 } 1088 1089 public void remove(int userId, String packageName) { 1090 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1091 if (packages != null) { 1092 packages.remove(packageName); 1093 } 1094 } 1095 1096 public void remove(int userId) { 1097 mUidMap.remove(userId); 1098 } 1099 1100 public int userIdCount() { 1101 return mUidMap.size(); 1102 } 1103 1104 public int userIdAt(int n) { 1105 return mUidMap.keyAt(n); 1106 } 1107 1108 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1109 return mUidMap.get(userId); 1110 } 1111 1112 public int size() { 1113 // total number of pending broadcast entries across all userIds 1114 int num = 0; 1115 for (int i = 0; i< mUidMap.size(); i++) { 1116 num += mUidMap.valueAt(i).size(); 1117 } 1118 return num; 1119 } 1120 1121 public void clear() { 1122 mUidMap.clear(); 1123 } 1124 1125 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1126 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1127 if (map == null) { 1128 map = new ArrayMap<String, ArrayList<String>>(); 1129 mUidMap.put(userId, map); 1130 } 1131 return map; 1132 } 1133 } 1134 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1135 1136 // Service Connection to remote media container service to copy 1137 // package uri's from external media onto secure containers 1138 // or internal storage. 1139 private IMediaContainerService mContainerService = null; 1140 1141 static final int SEND_PENDING_BROADCAST = 1; 1142 static final int MCS_BOUND = 3; 1143 static final int END_COPY = 4; 1144 static final int INIT_COPY = 5; 1145 static final int MCS_UNBIND = 6; 1146 static final int START_CLEANING_PACKAGE = 7; 1147 static final int FIND_INSTALL_LOC = 8; 1148 static final int POST_INSTALL = 9; 1149 static final int MCS_RECONNECT = 10; 1150 static final int MCS_GIVE_UP = 11; 1151 static final int UPDATED_MEDIA_STATUS = 12; 1152 static final int WRITE_SETTINGS = 13; 1153 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1154 static final int PACKAGE_VERIFIED = 15; 1155 static final int CHECK_PENDING_VERIFICATION = 16; 1156 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1157 static final int INTENT_FILTER_VERIFIED = 18; 1158 static final int WRITE_PACKAGE_LIST = 19; 1159 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1160 1161 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1162 1163 // Delay time in millisecs 1164 static final int BROADCAST_DELAY = 10 * 1000; 1165 1166 static UserManagerService sUserManager; 1167 1168 // Stores a list of users whose package restrictions file needs to be updated 1169 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1170 1171 final private DefaultContainerConnection mDefContainerConn = 1172 new DefaultContainerConnection(); 1173 class DefaultContainerConnection implements ServiceConnection { 1174 public void onServiceConnected(ComponentName name, IBinder service) { 1175 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1176 final IMediaContainerService imcs = IMediaContainerService.Stub 1177 .asInterface(Binder.allowBlocking(service)); 1178 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1179 } 1180 1181 public void onServiceDisconnected(ComponentName name) { 1182 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1183 } 1184 } 1185 1186 // Recordkeeping of restore-after-install operations that are currently in flight 1187 // between the Package Manager and the Backup Manager 1188 static class PostInstallData { 1189 public InstallArgs args; 1190 public PackageInstalledInfo res; 1191 1192 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1193 args = _a; 1194 res = _r; 1195 } 1196 } 1197 1198 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1199 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1200 1201 // XML tags for backup/restore of various bits of state 1202 private static final String TAG_PREFERRED_BACKUP = "pa"; 1203 private static final String TAG_DEFAULT_APPS = "da"; 1204 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1205 1206 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1207 private static final String TAG_ALL_GRANTS = "rt-grants"; 1208 private static final String TAG_GRANT = "grant"; 1209 private static final String ATTR_PACKAGE_NAME = "pkg"; 1210 1211 private static final String TAG_PERMISSION = "perm"; 1212 private static final String ATTR_PERMISSION_NAME = "name"; 1213 private static final String ATTR_IS_GRANTED = "g"; 1214 private static final String ATTR_USER_SET = "set"; 1215 private static final String ATTR_USER_FIXED = "fixed"; 1216 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1217 1218 // System/policy permission grants are not backed up 1219 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1220 FLAG_PERMISSION_POLICY_FIXED 1221 | FLAG_PERMISSION_SYSTEM_FIXED 1222 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1223 1224 // And we back up these user-adjusted states 1225 private static final int USER_RUNTIME_GRANT_MASK = 1226 FLAG_PERMISSION_USER_SET 1227 | FLAG_PERMISSION_USER_FIXED 1228 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1229 1230 final @Nullable String mRequiredVerifierPackage; 1231 final @NonNull String mRequiredInstallerPackage; 1232 final @NonNull String mRequiredUninstallerPackage; 1233 final @Nullable String mSetupWizardPackage; 1234 final @Nullable String mStorageManagerPackage; 1235 final @NonNull String mServicesSystemSharedLibraryPackageName; 1236 final @NonNull String mSharedSystemSharedLibraryPackageName; 1237 1238 final boolean mPermissionReviewRequired; 1239 1240 private final PackageUsage mPackageUsage = new PackageUsage(); 1241 private final CompilerStats mCompilerStats = new CompilerStats(); 1242 1243 class PackageHandler extends Handler { 1244 private boolean mBound = false; 1245 final ArrayList<HandlerParams> mPendingInstalls = 1246 new ArrayList<HandlerParams>(); 1247 1248 private boolean connectToService() { 1249 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1250 " DefaultContainerService"); 1251 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1252 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1253 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1254 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1255 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1256 mBound = true; 1257 return true; 1258 } 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 return false; 1261 } 1262 1263 private void disconnectService() { 1264 mContainerService = null; 1265 mBound = false; 1266 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1267 mContext.unbindService(mDefContainerConn); 1268 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1269 } 1270 1271 PackageHandler(Looper looper) { 1272 super(looper); 1273 } 1274 1275 public void handleMessage(Message msg) { 1276 try { 1277 doHandleMessage(msg); 1278 } finally { 1279 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1280 } 1281 } 1282 1283 void doHandleMessage(Message msg) { 1284 switch (msg.what) { 1285 case INIT_COPY: { 1286 HandlerParams params = (HandlerParams) msg.obj; 1287 int idx = mPendingInstalls.size(); 1288 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1289 // If a bind was already initiated we dont really 1290 // need to do anything. The pending install 1291 // will be processed later on. 1292 if (!mBound) { 1293 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1294 System.identityHashCode(mHandler)); 1295 // If this is the only one pending we might 1296 // have to bind to the service again. 1297 if (!connectToService()) { 1298 Slog.e(TAG, "Failed to bind to media container service"); 1299 params.serviceError(); 1300 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1301 System.identityHashCode(mHandler)); 1302 if (params.traceMethod != null) { 1303 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1304 params.traceCookie); 1305 } 1306 return; 1307 } else { 1308 // Once we bind to the service, the first 1309 // pending request will be processed. 1310 mPendingInstalls.add(idx, params); 1311 } 1312 } else { 1313 mPendingInstalls.add(idx, params); 1314 // Already bound to the service. Just make 1315 // sure we trigger off processing the first request. 1316 if (idx == 0) { 1317 mHandler.sendEmptyMessage(MCS_BOUND); 1318 } 1319 } 1320 break; 1321 } 1322 case MCS_BOUND: { 1323 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1324 if (msg.obj != null) { 1325 mContainerService = (IMediaContainerService) msg.obj; 1326 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1327 System.identityHashCode(mHandler)); 1328 } 1329 if (mContainerService == null) { 1330 if (!mBound) { 1331 // Something seriously wrong since we are not bound and we are not 1332 // waiting for connection. Bail out. 1333 Slog.e(TAG, "Cannot bind to media container service"); 1334 for (HandlerParams params : mPendingInstalls) { 1335 // Indicate service bind error 1336 params.serviceError(); 1337 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1338 System.identityHashCode(params)); 1339 if (params.traceMethod != null) { 1340 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1341 params.traceMethod, params.traceCookie); 1342 } 1343 return; 1344 } 1345 mPendingInstalls.clear(); 1346 } else { 1347 Slog.w(TAG, "Waiting to connect to media container service"); 1348 } 1349 } else if (mPendingInstalls.size() > 0) { 1350 HandlerParams params = mPendingInstalls.get(0); 1351 if (params != null) { 1352 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1353 System.identityHashCode(params)); 1354 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1355 if (params.startCopy()) { 1356 // We are done... look for more work or to 1357 // go idle. 1358 if (DEBUG_SD_INSTALL) Log.i(TAG, 1359 "Checking for more work or unbind..."); 1360 // Delete pending install 1361 if (mPendingInstalls.size() > 0) { 1362 mPendingInstalls.remove(0); 1363 } 1364 if (mPendingInstalls.size() == 0) { 1365 if (mBound) { 1366 if (DEBUG_SD_INSTALL) Log.i(TAG, 1367 "Posting delayed MCS_UNBIND"); 1368 removeMessages(MCS_UNBIND); 1369 Message ubmsg = obtainMessage(MCS_UNBIND); 1370 // Unbind after a little delay, to avoid 1371 // continual thrashing. 1372 sendMessageDelayed(ubmsg, 10000); 1373 } 1374 } else { 1375 // There are more pending requests in queue. 1376 // Just post MCS_BOUND message to trigger processing 1377 // of next pending install. 1378 if (DEBUG_SD_INSTALL) Log.i(TAG, 1379 "Posting MCS_BOUND for next work"); 1380 mHandler.sendEmptyMessage(MCS_BOUND); 1381 } 1382 } 1383 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1384 } 1385 } else { 1386 // Should never happen ideally. 1387 Slog.w(TAG, "Empty queue"); 1388 } 1389 break; 1390 } 1391 case MCS_RECONNECT: { 1392 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1393 if (mPendingInstalls.size() > 0) { 1394 if (mBound) { 1395 disconnectService(); 1396 } 1397 if (!connectToService()) { 1398 Slog.e(TAG, "Failed to bind to media container service"); 1399 for (HandlerParams params : mPendingInstalls) { 1400 // Indicate service bind error 1401 params.serviceError(); 1402 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1403 System.identityHashCode(params)); 1404 } 1405 mPendingInstalls.clear(); 1406 } 1407 } 1408 break; 1409 } 1410 case MCS_UNBIND: { 1411 // If there is no actual work left, then time to unbind. 1412 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1413 1414 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1415 if (mBound) { 1416 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1417 1418 disconnectService(); 1419 } 1420 } else if (mPendingInstalls.size() > 0) { 1421 // There are more pending requests in queue. 1422 // Just post MCS_BOUND message to trigger processing 1423 // of next pending install. 1424 mHandler.sendEmptyMessage(MCS_BOUND); 1425 } 1426 1427 break; 1428 } 1429 case MCS_GIVE_UP: { 1430 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1431 HandlerParams params = mPendingInstalls.remove(0); 1432 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1433 System.identityHashCode(params)); 1434 break; 1435 } 1436 case SEND_PENDING_BROADCAST: { 1437 String packages[]; 1438 ArrayList<String> components[]; 1439 int size = 0; 1440 int uids[]; 1441 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1442 synchronized (mPackages) { 1443 if (mPendingBroadcasts == null) { 1444 return; 1445 } 1446 size = mPendingBroadcasts.size(); 1447 if (size <= 0) { 1448 // Nothing to be done. Just return 1449 return; 1450 } 1451 packages = new String[size]; 1452 components = new ArrayList[size]; 1453 uids = new int[size]; 1454 int i = 0; // filling out the above arrays 1455 1456 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1457 int packageUserId = mPendingBroadcasts.userIdAt(n); 1458 Iterator<Map.Entry<String, ArrayList<String>>> it 1459 = mPendingBroadcasts.packagesForUserId(packageUserId) 1460 .entrySet().iterator(); 1461 while (it.hasNext() && i < size) { 1462 Map.Entry<String, ArrayList<String>> ent = it.next(); 1463 packages[i] = ent.getKey(); 1464 components[i] = ent.getValue(); 1465 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1466 uids[i] = (ps != null) 1467 ? UserHandle.getUid(packageUserId, ps.appId) 1468 : -1; 1469 i++; 1470 } 1471 } 1472 size = i; 1473 mPendingBroadcasts.clear(); 1474 } 1475 // Send broadcasts 1476 for (int i = 0; i < size; i++) { 1477 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1478 } 1479 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1480 break; 1481 } 1482 case START_CLEANING_PACKAGE: { 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1484 final String packageName = (String)msg.obj; 1485 final int userId = msg.arg1; 1486 final boolean andCode = msg.arg2 != 0; 1487 synchronized (mPackages) { 1488 if (userId == UserHandle.USER_ALL) { 1489 int[] users = sUserManager.getUserIds(); 1490 for (int user : users) { 1491 mSettings.addPackageToCleanLPw( 1492 new PackageCleanItem(user, packageName, andCode)); 1493 } 1494 } else { 1495 mSettings.addPackageToCleanLPw( 1496 new PackageCleanItem(userId, packageName, andCode)); 1497 } 1498 } 1499 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1500 startCleaningPackages(); 1501 } break; 1502 case POST_INSTALL: { 1503 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1504 1505 PostInstallData data = mRunningInstalls.get(msg.arg1); 1506 final boolean didRestore = (msg.arg2 != 0); 1507 mRunningInstalls.delete(msg.arg1); 1508 1509 if (data != null) { 1510 InstallArgs args = data.args; 1511 PackageInstalledInfo parentRes = data.res; 1512 1513 final boolean grantPermissions = (args.installFlags 1514 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1515 final boolean killApp = (args.installFlags 1516 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1517 final String[] grantedPermissions = args.installGrantPermissions; 1518 1519 // Handle the parent package 1520 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1521 grantedPermissions, didRestore, args.installerPackageName, 1522 args.observer); 1523 1524 // Handle the child packages 1525 final int childCount = (parentRes.addedChildPackages != null) 1526 ? parentRes.addedChildPackages.size() : 0; 1527 for (int i = 0; i < childCount; i++) { 1528 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1529 handlePackagePostInstall(childRes, grantPermissions, killApp, 1530 grantedPermissions, false, args.installerPackageName, 1531 args.observer); 1532 } 1533 1534 // Log tracing if needed 1535 if (args.traceMethod != null) { 1536 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1537 args.traceCookie); 1538 } 1539 } else { 1540 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1541 } 1542 1543 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1544 } break; 1545 case UPDATED_MEDIA_STATUS: { 1546 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1547 boolean reportStatus = msg.arg1 == 1; 1548 boolean doGc = msg.arg2 == 1; 1549 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1550 if (doGc) { 1551 // Force a gc to clear up stale containers. 1552 Runtime.getRuntime().gc(); 1553 } 1554 if (msg.obj != null) { 1555 @SuppressWarnings("unchecked") 1556 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1557 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1558 // Unload containers 1559 unloadAllContainers(args); 1560 } 1561 if (reportStatus) { 1562 try { 1563 if (DEBUG_SD_INSTALL) Log.i(TAG, 1564 "Invoking StorageManagerService call back"); 1565 PackageHelper.getStorageManager().finishMediaUpdate(); 1566 } catch (RemoteException e) { 1567 Log.e(TAG, "StorageManagerService not running?"); 1568 } 1569 } 1570 } break; 1571 case WRITE_SETTINGS: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 removeMessages(WRITE_SETTINGS); 1575 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1576 mSettings.writeLPr(); 1577 mDirtyUsers.clear(); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case WRITE_PACKAGE_RESTRICTIONS: { 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1583 synchronized (mPackages) { 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 for (int userId : mDirtyUsers) { 1586 mSettings.writePackageRestrictionsLPr(userId); 1587 } 1588 mDirtyUsers.clear(); 1589 } 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1591 } break; 1592 case WRITE_PACKAGE_LIST: { 1593 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1594 synchronized (mPackages) { 1595 removeMessages(WRITE_PACKAGE_LIST); 1596 mSettings.writePackageListLPr(msg.arg1); 1597 } 1598 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1599 } break; 1600 case CHECK_PENDING_VERIFICATION: { 1601 final int verificationId = msg.arg1; 1602 final PackageVerificationState state = mPendingVerification.get(verificationId); 1603 1604 if ((state != null) && !state.timeoutExtended()) { 1605 final InstallArgs args = state.getInstallArgs(); 1606 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1607 1608 Slog.i(TAG, "Verification timed out for " + originUri); 1609 mPendingVerification.remove(verificationId); 1610 1611 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1612 1613 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1614 Slog.i(TAG, "Continuing with installation of " + originUri); 1615 state.setVerifierResponse(Binder.getCallingUid(), 1616 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1617 broadcastPackageVerified(verificationId, originUri, 1618 PackageManager.VERIFICATION_ALLOW, 1619 state.getInstallArgs().getUser()); 1620 try { 1621 ret = args.copyApk(mContainerService, true); 1622 } catch (RemoteException e) { 1623 Slog.e(TAG, "Could not contact the ContainerService"); 1624 } 1625 } else { 1626 broadcastPackageVerified(verificationId, originUri, 1627 PackageManager.VERIFICATION_REJECT, 1628 state.getInstallArgs().getUser()); 1629 } 1630 1631 Trace.asyncTraceEnd( 1632 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1633 1634 processPendingInstall(args, ret); 1635 mHandler.sendEmptyMessage(MCS_UNBIND); 1636 } 1637 break; 1638 } 1639 case PACKAGE_VERIFIED: { 1640 final int verificationId = msg.arg1; 1641 1642 final PackageVerificationState state = mPendingVerification.get(verificationId); 1643 if (state == null) { 1644 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1645 break; 1646 } 1647 1648 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1649 1650 state.setVerifierResponse(response.callerUid, response.code); 1651 1652 if (state.isVerificationComplete()) { 1653 mPendingVerification.remove(verificationId); 1654 1655 final InstallArgs args = state.getInstallArgs(); 1656 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1657 1658 int ret; 1659 if (state.isInstallAllowed()) { 1660 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1661 broadcastPackageVerified(verificationId, originUri, 1662 response.code, state.getInstallArgs().getUser()); 1663 try { 1664 ret = args.copyApk(mContainerService, true); 1665 } catch (RemoteException e) { 1666 Slog.e(TAG, "Could not contact the ContainerService"); 1667 } 1668 } else { 1669 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1670 } 1671 1672 Trace.asyncTraceEnd( 1673 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1674 1675 processPendingInstall(args, ret); 1676 mHandler.sendEmptyMessage(MCS_UNBIND); 1677 } 1678 1679 break; 1680 } 1681 case START_INTENT_FILTER_VERIFICATIONS: { 1682 IFVerificationParams params = (IFVerificationParams) msg.obj; 1683 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1684 params.replacing, params.pkg); 1685 break; 1686 } 1687 case INTENT_FILTER_VERIFIED: { 1688 final int verificationId = msg.arg1; 1689 1690 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1691 verificationId); 1692 if (state == null) { 1693 Slog.w(TAG, "Invalid IntentFilter verification token " 1694 + verificationId + " received"); 1695 break; 1696 } 1697 1698 final int userId = state.getUserId(); 1699 1700 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1701 "Processing IntentFilter verification with token:" 1702 + verificationId + " and userId:" + userId); 1703 1704 final IntentFilterVerificationResponse response = 1705 (IntentFilterVerificationResponse) msg.obj; 1706 1707 state.setVerifierResponse(response.callerUid, response.code); 1708 1709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1710 "IntentFilter verification with token:" + verificationId 1711 + " and userId:" + userId 1712 + " is settings verifier response with response code:" 1713 + response.code); 1714 1715 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1716 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1717 + response.getFailedDomainsString()); 1718 } 1719 1720 if (state.isVerificationComplete()) { 1721 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1722 } else { 1723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1724 "IntentFilter verification with token:" + verificationId 1725 + " was not said to be complete"); 1726 } 1727 1728 break; 1729 } 1730 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1731 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1732 mEphemeralResolverConnection, 1733 (EphemeralRequest) msg.obj, 1734 mEphemeralInstallerActivity, 1735 mHandler); 1736 } 1737 } 1738 } 1739 } 1740 1741 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1742 boolean killApp, String[] grantedPermissions, 1743 boolean launchedForRestore, String installerPackage, 1744 IPackageInstallObserver2 installObserver) { 1745 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1746 // Send the removed broadcasts 1747 if (res.removedInfo != null) { 1748 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1749 } 1750 1751 // Now that we successfully installed the package, grant runtime 1752 // permissions if requested before broadcasting the install. Also 1753 // for legacy apps in permission review mode we clear the permission 1754 // review flag which is used to emulate runtime permissions for 1755 // legacy apps. 1756 if (grantPermissions) { 1757 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1758 } 1759 1760 final boolean update = res.removedInfo != null 1761 && res.removedInfo.removedPackage != null; 1762 1763 // If this is the first time we have child packages for a disabled privileged 1764 // app that had no children, we grant requested runtime permissions to the new 1765 // children if the parent on the system image had them already granted. 1766 if (res.pkg.parentPackage != null) { 1767 synchronized (mPackages) { 1768 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1769 } 1770 } 1771 1772 synchronized (mPackages) { 1773 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1774 } 1775 1776 final String packageName = res.pkg.applicationInfo.packageName; 1777 1778 // Determine the set of users who are adding this package for 1779 // the first time vs. those who are seeing an update. 1780 int[] firstUsers = EMPTY_INT_ARRAY; 1781 int[] updateUsers = EMPTY_INT_ARRAY; 1782 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1783 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1784 for (int newUser : res.newUsers) { 1785 if (ps.getInstantApp(newUser)) { 1786 continue; 1787 } 1788 if (allNewUsers) { 1789 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1790 continue; 1791 } 1792 boolean isNew = true; 1793 for (int origUser : res.origUsers) { 1794 if (origUser == newUser) { 1795 isNew = false; 1796 break; 1797 } 1798 } 1799 if (isNew) { 1800 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1801 } else { 1802 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1803 } 1804 } 1805 1806 // Send installed broadcasts if the package is not a static shared lib. 1807 if (res.pkg.staticSharedLibName == null) { 1808 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1809 1810 // Send added for users that see the package for the first time 1811 // sendPackageAddedForNewUsers also deals with system apps 1812 int appId = UserHandle.getAppId(res.uid); 1813 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1814 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1815 1816 // Send added for users that don't see the package for the first time 1817 Bundle extras = new Bundle(1); 1818 extras.putInt(Intent.EXTRA_UID, res.uid); 1819 if (update) { 1820 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1821 } 1822 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1823 extras, 0 /*flags*/, null /*targetPackage*/, 1824 null /*finishedReceiver*/, updateUsers); 1825 1826 // Send replaced for users that don't see the package for the first time 1827 if (update) { 1828 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1829 packageName, extras, 0 /*flags*/, 1830 null /*targetPackage*/, null /*finishedReceiver*/, 1831 updateUsers); 1832 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1833 null /*package*/, null /*extras*/, 0 /*flags*/, 1834 packageName /*targetPackage*/, 1835 null /*finishedReceiver*/, updateUsers); 1836 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1837 // First-install and we did a restore, so we're responsible for the 1838 // first-launch broadcast. 1839 if (DEBUG_BACKUP) { 1840 Slog.i(TAG, "Post-restore of " + packageName 1841 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1842 } 1843 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1844 } 1845 1846 // Send broadcast package appeared if forward locked/external for all users 1847 // treat asec-hosted packages like removable media on upgrade 1848 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1849 if (DEBUG_INSTALL) { 1850 Slog.i(TAG, "upgrading pkg " + res.pkg 1851 + " is ASEC-hosted -> AVAILABLE"); 1852 } 1853 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1854 ArrayList<String> pkgList = new ArrayList<>(1); 1855 pkgList.add(packageName); 1856 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1857 } 1858 } 1859 1860 // Work that needs to happen on first install within each user 1861 if (firstUsers != null && firstUsers.length > 0) { 1862 synchronized (mPackages) { 1863 for (int userId : firstUsers) { 1864 // If this app is a browser and it's newly-installed for some 1865 // users, clear any default-browser state in those users. The 1866 // app's nature doesn't depend on the user, so we can just check 1867 // its browser nature in any user and generalize. 1868 if (packageIsBrowser(packageName, userId)) { 1869 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1870 } 1871 1872 // We may also need to apply pending (restored) runtime 1873 // permission grants within these users. 1874 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1875 } 1876 } 1877 } 1878 1879 // Log current value of "unknown sources" setting 1880 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1881 getUnknownSourcesSettings()); 1882 1883 // Force a gc to clear up things 1884 Runtime.getRuntime().gc(); 1885 1886 // Remove the replaced package's older resources safely now 1887 // We delete after a gc for applications on sdcard. 1888 if (res.removedInfo != null && res.removedInfo.args != null) { 1889 synchronized (mInstallLock) { 1890 res.removedInfo.args.doPostDeleteLI(true); 1891 } 1892 } 1893 1894 // Notify DexManager that the package was installed for new users. 1895 // The updated users should already be indexed and the package code paths 1896 // should not change. 1897 // Don't notify the manager for ephemeral apps as they are not expected to 1898 // survive long enough to benefit of background optimizations. 1899 for (int userId : firstUsers) { 1900 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1901 mDexManager.notifyPackageInstalled(info, userId); 1902 } 1903 } 1904 1905 // If someone is watching installs - notify them 1906 if (installObserver != null) { 1907 try { 1908 Bundle extras = extrasForInstallResult(res); 1909 installObserver.onPackageInstalled(res.name, res.returnCode, 1910 res.returnMsg, extras); 1911 } catch (RemoteException e) { 1912 Slog.i(TAG, "Observer no longer exists."); 1913 } 1914 } 1915 } 1916 1917 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1918 PackageParser.Package pkg) { 1919 if (pkg.parentPackage == null) { 1920 return; 1921 } 1922 if (pkg.requestedPermissions == null) { 1923 return; 1924 } 1925 final PackageSetting disabledSysParentPs = mSettings 1926 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1927 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1928 || !disabledSysParentPs.isPrivileged() 1929 || (disabledSysParentPs.childPackageNames != null 1930 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1931 return; 1932 } 1933 final int[] allUserIds = sUserManager.getUserIds(); 1934 final int permCount = pkg.requestedPermissions.size(); 1935 for (int i = 0; i < permCount; i++) { 1936 String permission = pkg.requestedPermissions.get(i); 1937 BasePermission bp = mSettings.mPermissions.get(permission); 1938 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1939 continue; 1940 } 1941 for (int userId : allUserIds) { 1942 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1943 permission, userId)) { 1944 grantRuntimePermission(pkg.packageName, permission, userId); 1945 } 1946 } 1947 } 1948 } 1949 1950 private StorageEventListener mStorageListener = new StorageEventListener() { 1951 @Override 1952 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1953 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1954 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1955 final String volumeUuid = vol.getFsUuid(); 1956 1957 // Clean up any users or apps that were removed or recreated 1958 // while this volume was missing 1959 sUserManager.reconcileUsers(volumeUuid); 1960 reconcileApps(volumeUuid); 1961 1962 // Clean up any install sessions that expired or were 1963 // cancelled while this volume was missing 1964 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1965 1966 loadPrivatePackages(vol); 1967 1968 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1969 unloadPrivatePackages(vol); 1970 } 1971 } 1972 1973 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1974 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1975 updateExternalMediaStatus(true, false); 1976 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1977 updateExternalMediaStatus(false, false); 1978 } 1979 } 1980 } 1981 1982 @Override 1983 public void onVolumeForgotten(String fsUuid) { 1984 if (TextUtils.isEmpty(fsUuid)) { 1985 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1986 return; 1987 } 1988 1989 // Remove any apps installed on the forgotten volume 1990 synchronized (mPackages) { 1991 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1992 for (PackageSetting ps : packages) { 1993 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1994 deletePackageVersioned(new VersionedPackage(ps.name, 1995 PackageManager.VERSION_CODE_HIGHEST), 1996 new LegacyPackageDeleteObserver(null).getBinder(), 1997 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1998 // Try very hard to release any references to this package 1999 // so we don't risk the system server being killed due to 2000 // open FDs 2001 AttributeCache.instance().removePackage(ps.name); 2002 } 2003 2004 mSettings.onVolumeForgotten(fsUuid); 2005 mSettings.writeLPr(); 2006 } 2007 } 2008 }; 2009 2010 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2011 String[] grantedPermissions) { 2012 for (int userId : userIds) { 2013 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2014 } 2015 } 2016 2017 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2018 String[] grantedPermissions) { 2019 SettingBase sb = (SettingBase) pkg.mExtras; 2020 if (sb == null) { 2021 return; 2022 } 2023 2024 PermissionsState permissionsState = sb.getPermissionsState(); 2025 2026 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2027 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2028 2029 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2030 >= Build.VERSION_CODES.M; 2031 2032 for (String permission : pkg.requestedPermissions) { 2033 final BasePermission bp; 2034 synchronized (mPackages) { 2035 bp = mSettings.mPermissions.get(permission); 2036 } 2037 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2038 && (grantedPermissions == null 2039 || ArrayUtils.contains(grantedPermissions, permission))) { 2040 final int flags = permissionsState.getPermissionFlags(permission, userId); 2041 if (supportsRuntimePermissions) { 2042 // Installer cannot change immutable permissions. 2043 if ((flags & immutableFlags) == 0) { 2044 grantRuntimePermission(pkg.packageName, permission, userId); 2045 } 2046 } else if (mPermissionReviewRequired) { 2047 // In permission review mode we clear the review flag when we 2048 // are asked to install the app with all permissions granted. 2049 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2050 updatePermissionFlags(permission, pkg.packageName, 2051 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2052 } 2053 } 2054 } 2055 } 2056 } 2057 2058 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2059 Bundle extras = null; 2060 switch (res.returnCode) { 2061 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2062 extras = new Bundle(); 2063 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2064 res.origPermission); 2065 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2066 res.origPackage); 2067 break; 2068 } 2069 case PackageManager.INSTALL_SUCCEEDED: { 2070 extras = new Bundle(); 2071 extras.putBoolean(Intent.EXTRA_REPLACING, 2072 res.removedInfo != null && res.removedInfo.removedPackage != null); 2073 break; 2074 } 2075 } 2076 return extras; 2077 } 2078 2079 void scheduleWriteSettingsLocked() { 2080 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2081 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2082 } 2083 } 2084 2085 void scheduleWritePackageListLocked(int userId) { 2086 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2087 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2088 msg.arg1 = userId; 2089 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2090 } 2091 } 2092 2093 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2094 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2095 scheduleWritePackageRestrictionsLocked(userId); 2096 } 2097 2098 void scheduleWritePackageRestrictionsLocked(int userId) { 2099 final int[] userIds = (userId == UserHandle.USER_ALL) 2100 ? sUserManager.getUserIds() : new int[]{userId}; 2101 for (int nextUserId : userIds) { 2102 if (!sUserManager.exists(nextUserId)) return; 2103 mDirtyUsers.add(nextUserId); 2104 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2105 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2106 } 2107 } 2108 } 2109 2110 public static PackageManagerService main(Context context, Installer installer, 2111 boolean factoryTest, boolean onlyCore) { 2112 // Self-check for initial settings. 2113 PackageManagerServiceCompilerMapping.checkProperties(); 2114 2115 PackageManagerService m = new PackageManagerService(context, installer, 2116 factoryTest, onlyCore); 2117 m.enableSystemUserPackages(); 2118 ServiceManager.addService("package", m); 2119 return m; 2120 } 2121 2122 private void enableSystemUserPackages() { 2123 if (!UserManager.isSplitSystemUser()) { 2124 return; 2125 } 2126 // For system user, enable apps based on the following conditions: 2127 // - app is whitelisted or belong to one of these groups: 2128 // -- system app which has no launcher icons 2129 // -- system app which has INTERACT_ACROSS_USERS permission 2130 // -- system IME app 2131 // - app is not in the blacklist 2132 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2133 Set<String> enableApps = new ArraySet<>(); 2134 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2135 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2136 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2137 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2138 enableApps.addAll(wlApps); 2139 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2140 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2141 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2142 enableApps.removeAll(blApps); 2143 Log.i(TAG, "Applications installed for system user: " + enableApps); 2144 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2145 UserHandle.SYSTEM); 2146 final int allAppsSize = allAps.size(); 2147 synchronized (mPackages) { 2148 for (int i = 0; i < allAppsSize; i++) { 2149 String pName = allAps.get(i); 2150 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2151 // Should not happen, but we shouldn't be failing if it does 2152 if (pkgSetting == null) { 2153 continue; 2154 } 2155 boolean install = enableApps.contains(pName); 2156 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2157 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2158 + " for system user"); 2159 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2160 } 2161 } 2162 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2163 } 2164 } 2165 2166 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2167 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2168 Context.DISPLAY_SERVICE); 2169 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2170 } 2171 2172 /** 2173 * Requests that files preopted on a secondary system partition be copied to the data partition 2174 * if possible. Note that the actual copying of the files is accomplished by init for security 2175 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2176 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2177 */ 2178 private static void requestCopyPreoptedFiles() { 2179 final int WAIT_TIME_MS = 100; 2180 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2181 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2182 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2183 // We will wait for up to 100 seconds. 2184 final long timeStart = SystemClock.uptimeMillis(); 2185 final long timeEnd = timeStart + 100 * 1000; 2186 long timeNow = timeStart; 2187 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2188 try { 2189 Thread.sleep(WAIT_TIME_MS); 2190 } catch (InterruptedException e) { 2191 // Do nothing 2192 } 2193 timeNow = SystemClock.uptimeMillis(); 2194 if (timeNow > timeEnd) { 2195 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2196 Slog.wtf(TAG, "cppreopt did not finish!"); 2197 break; 2198 } 2199 } 2200 2201 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2202 } 2203 } 2204 2205 public PackageManagerService(Context context, Installer installer, 2206 boolean factoryTest, boolean onlyCore) { 2207 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2208 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2209 SystemClock.uptimeMillis()); 2210 2211 if (mSdkVersion <= 0) { 2212 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2213 } 2214 2215 mContext = context; 2216 2217 mPermissionReviewRequired = context.getResources().getBoolean( 2218 R.bool.config_permissionReviewRequired); 2219 2220 mFactoryTest = factoryTest; 2221 mOnlyCore = onlyCore; 2222 mMetrics = new DisplayMetrics(); 2223 mSettings = new Settings(mPackages); 2224 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2225 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2226 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2227 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2228 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2229 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2230 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2231 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2232 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 2237 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2238 if (separateProcesses != null && separateProcesses.length() > 0) { 2239 if ("*".equals(separateProcesses)) { 2240 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2241 mSeparateProcesses = null; 2242 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2243 } else { 2244 mDefParseFlags = 0; 2245 mSeparateProcesses = separateProcesses.split(","); 2246 Slog.w(TAG, "Running with debug.separate_processes: " 2247 + separateProcesses); 2248 } 2249 } else { 2250 mDefParseFlags = 0; 2251 mSeparateProcesses = null; 2252 } 2253 2254 mInstaller = installer; 2255 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2256 "*dexopt*"); 2257 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2258 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2259 2260 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2261 FgThread.get().getLooper()); 2262 2263 getDefaultDisplayMetrics(context, mMetrics); 2264 2265 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2266 SystemConfig systemConfig = SystemConfig.getInstance(); 2267 mGlobalGids = systemConfig.getGlobalGids(); 2268 mSystemPermissions = systemConfig.getSystemPermissions(); 2269 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2270 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2271 2272 mProtectedPackages = new ProtectedPackages(mContext); 2273 2274 synchronized (mInstallLock) { 2275 // writer 2276 synchronized (mPackages) { 2277 mHandlerThread = new ServiceThread(TAG, 2278 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2279 mHandlerThread.start(); 2280 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2281 mProcessLoggingHandler = new ProcessLoggingHandler(); 2282 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2283 2284 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2285 mInstantAppRegistry = new InstantAppRegistry(this); 2286 2287 File dataDir = Environment.getDataDirectory(); 2288 mAppInstallDir = new File(dataDir, "app"); 2289 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2290 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2291 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2292 sUserManager = new UserManagerService(context, this, 2293 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2294 2295 // Propagate permission configuration in to package manager. 2296 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2297 = systemConfig.getPermissions(); 2298 for (int i=0; i<permConfig.size(); i++) { 2299 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2300 BasePermission bp = mSettings.mPermissions.get(perm.name); 2301 if (bp == null) { 2302 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2303 mSettings.mPermissions.put(perm.name, bp); 2304 } 2305 if (perm.gids != null) { 2306 bp.setGids(perm.gids, perm.perUser); 2307 } 2308 } 2309 2310 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2311 final int builtInLibCount = libConfig.size(); 2312 for (int i = 0; i < builtInLibCount; i++) { 2313 String name = libConfig.keyAt(i); 2314 String path = libConfig.valueAt(i); 2315 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2316 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2317 } 2318 2319 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2320 2321 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2322 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2323 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2324 2325 // Clean up orphaned packages for which the code path doesn't exist 2326 // and they are an update to a system app - caused by bug/32321269 2327 final int packageSettingCount = mSettings.mPackages.size(); 2328 for (int i = packageSettingCount - 1; i >= 0; i--) { 2329 PackageSetting ps = mSettings.mPackages.valueAt(i); 2330 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2331 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2332 mSettings.mPackages.removeAt(i); 2333 mSettings.enableSystemPackageLPw(ps.name); 2334 } 2335 } 2336 2337 if (mFirstBoot) { 2338 requestCopyPreoptedFiles(); 2339 } 2340 2341 String customResolverActivity = Resources.getSystem().getString( 2342 R.string.config_customResolverActivity); 2343 if (TextUtils.isEmpty(customResolverActivity)) { 2344 customResolverActivity = null; 2345 } else { 2346 mCustomResolverComponentName = ComponentName.unflattenFromString( 2347 customResolverActivity); 2348 } 2349 2350 long startTime = SystemClock.uptimeMillis(); 2351 2352 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2353 startTime); 2354 2355 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2356 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2357 2358 if (bootClassPath == null) { 2359 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2360 } 2361 2362 if (systemServerClassPath == null) { 2363 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2364 } 2365 2366 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2367 final String[] dexCodeInstructionSets = 2368 getDexCodeInstructionSets( 2369 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2370 2371 /** 2372 * Ensure all external libraries have had dexopt run on them. 2373 */ 2374 if (mSharedLibraries.size() > 0) { 2375 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2376 // NOTE: For now, we're compiling these system "shared libraries" 2377 // (and framework jars) into all available architectures. It's possible 2378 // to compile them only when we come across an app that uses them (there's 2379 // already logic for that in scanPackageLI) but that adds some complexity. 2380 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2381 final int libCount = mSharedLibraries.size(); 2382 for (int i = 0; i < libCount; i++) { 2383 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2384 final int versionCount = versionedLib.size(); 2385 for (int j = 0; j < versionCount; j++) { 2386 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2387 final String libPath = libEntry.path != null 2388 ? libEntry.path : libEntry.apk; 2389 if (libPath == null) { 2390 continue; 2391 } 2392 try { 2393 // Shared libraries do not have profiles so we perform a full 2394 // AOT compilation (if needed). 2395 int dexoptNeeded = DexFile.getDexOptNeeded( 2396 libPath, dexCodeInstructionSet, 2397 getCompilerFilterForReason(REASON_SHARED_APK), 2398 false /* newProfile */); 2399 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2400 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2401 dexCodeInstructionSet, dexoptNeeded, null, 2402 DEXOPT_PUBLIC, 2403 getCompilerFilterForReason(REASON_SHARED_APK), 2404 StorageManager.UUID_PRIVATE_INTERNAL, 2405 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2406 } 2407 } catch (FileNotFoundException e) { 2408 Slog.w(TAG, "Library not found: " + libPath); 2409 } catch (IOException | InstallerException e) { 2410 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2411 + e.getMessage()); 2412 } 2413 } 2414 } 2415 } 2416 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2417 } 2418 2419 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2420 2421 final VersionInfo ver = mSettings.getInternalVersion(); 2422 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2423 2424 // when upgrading from pre-M, promote system app permissions from install to runtime 2425 mPromoteSystemApps = 2426 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2427 2428 // When upgrading from pre-N, we need to handle package extraction like first boot, 2429 // as there is no profiling data available. 2430 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2431 2432 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2433 2434 // save off the names of pre-existing system packages prior to scanning; we don't 2435 // want to automatically grant runtime permissions for new system apps 2436 if (mPromoteSystemApps) { 2437 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2438 while (pkgSettingIter.hasNext()) { 2439 PackageSetting ps = pkgSettingIter.next(); 2440 if (isSystemApp(ps)) { 2441 mExistingSystemPackages.add(ps.name); 2442 } 2443 } 2444 } 2445 2446 mCacheDir = preparePackageParserCache(mIsUpgrade); 2447 2448 // Set flag to monitor and not change apk file paths when 2449 // scanning install directories. 2450 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2451 2452 if (mIsUpgrade || mFirstBoot) { 2453 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2454 } 2455 2456 // Collect vendor overlay packages. (Do this before scanning any apps.) 2457 // For security and version matching reason, only consider 2458 // overlay packages if they reside in the right directory. 2459 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2460 if (overlayThemeDir.isEmpty()) { 2461 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2462 } 2463 if (!overlayThemeDir.isEmpty()) { 2464 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2465 | PackageParser.PARSE_IS_SYSTEM 2466 | PackageParser.PARSE_IS_SYSTEM_DIR 2467 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2468 } 2469 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2470 | PackageParser.PARSE_IS_SYSTEM 2471 | PackageParser.PARSE_IS_SYSTEM_DIR 2472 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2473 2474 // Find base frameworks (resource packages without code). 2475 scanDirTracedLI(frameworkDir, mDefParseFlags 2476 | PackageParser.PARSE_IS_SYSTEM 2477 | PackageParser.PARSE_IS_SYSTEM_DIR 2478 | PackageParser.PARSE_IS_PRIVILEGED, 2479 scanFlags | SCAN_NO_DEX, 0); 2480 2481 // Collected privileged system packages. 2482 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2483 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2484 | PackageParser.PARSE_IS_SYSTEM 2485 | PackageParser.PARSE_IS_SYSTEM_DIR 2486 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2487 2488 // Collect ordinary system packages. 2489 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2490 scanDirTracedLI(systemAppDir, mDefParseFlags 2491 | PackageParser.PARSE_IS_SYSTEM 2492 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2493 2494 // Collect all vendor packages. 2495 File vendorAppDir = new File("/vendor/app"); 2496 try { 2497 vendorAppDir = vendorAppDir.getCanonicalFile(); 2498 } catch (IOException e) { 2499 // failed to look up canonical path, continue with original one 2500 } 2501 scanDirTracedLI(vendorAppDir, mDefParseFlags 2502 | PackageParser.PARSE_IS_SYSTEM 2503 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2504 2505 // Collect all OEM packages. 2506 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2507 scanDirTracedLI(oemAppDir, mDefParseFlags 2508 | PackageParser.PARSE_IS_SYSTEM 2509 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2510 2511 // Prune any system packages that no longer exist. 2512 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2513 if (!mOnlyCore) { 2514 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2515 while (psit.hasNext()) { 2516 PackageSetting ps = psit.next(); 2517 2518 /* 2519 * If this is not a system app, it can't be a 2520 * disable system app. 2521 */ 2522 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2523 continue; 2524 } 2525 2526 /* 2527 * If the package is scanned, it's not erased. 2528 */ 2529 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2530 if (scannedPkg != null) { 2531 /* 2532 * If the system app is both scanned and in the 2533 * disabled packages list, then it must have been 2534 * added via OTA. Remove it from the currently 2535 * scanned package so the previously user-installed 2536 * application can be scanned. 2537 */ 2538 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2539 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2540 + ps.name + "; removing system app. Last known codePath=" 2541 + ps.codePathString + ", installStatus=" + ps.installStatus 2542 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2543 + scannedPkg.mVersionCode); 2544 removePackageLI(scannedPkg, true); 2545 mExpectingBetter.put(ps.name, ps.codePath); 2546 } 2547 2548 continue; 2549 } 2550 2551 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2552 psit.remove(); 2553 logCriticalInfo(Log.WARN, "System package " + ps.name 2554 + " no longer exists; it's data will be wiped"); 2555 // Actual deletion of code and data will be handled by later 2556 // reconciliation step 2557 } else { 2558 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2559 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2560 possiblyDeletedUpdatedSystemApps.add(ps.name); 2561 } 2562 } 2563 } 2564 } 2565 2566 //look for any incomplete package installations 2567 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2568 for (int i = 0; i < deletePkgsList.size(); i++) { 2569 // Actual deletion of code and data will be handled by later 2570 // reconciliation step 2571 final String packageName = deletePkgsList.get(i).name; 2572 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2573 synchronized (mPackages) { 2574 mSettings.removePackageLPw(packageName); 2575 } 2576 } 2577 2578 //delete tmp files 2579 deleteTempPackageFiles(); 2580 2581 // Remove any shared userIDs that have no associated packages 2582 mSettings.pruneSharedUsersLPw(); 2583 2584 if (!mOnlyCore) { 2585 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2586 SystemClock.uptimeMillis()); 2587 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2588 2589 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2590 | PackageParser.PARSE_FORWARD_LOCK, 2591 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2592 2593 /** 2594 * Remove disable package settings for any updated system 2595 * apps that were removed via an OTA. If they're not a 2596 * previously-updated app, remove them completely. 2597 * Otherwise, just revoke their system-level permissions. 2598 */ 2599 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2600 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2601 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2602 2603 String msg; 2604 if (deletedPkg == null) { 2605 msg = "Updated system package " + deletedAppName 2606 + " no longer exists; it's data will be wiped"; 2607 // Actual deletion of code and data will be handled by later 2608 // reconciliation step 2609 } else { 2610 msg = "Updated system app + " + deletedAppName 2611 + " no longer present; removing system privileges for " 2612 + deletedAppName; 2613 2614 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2615 2616 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2617 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2618 } 2619 logCriticalInfo(Log.WARN, msg); 2620 } 2621 2622 /** 2623 * Make sure all system apps that we expected to appear on 2624 * the userdata partition actually showed up. If they never 2625 * appeared, crawl back and revive the system version. 2626 */ 2627 for (int i = 0; i < mExpectingBetter.size(); i++) { 2628 final String packageName = mExpectingBetter.keyAt(i); 2629 if (!mPackages.containsKey(packageName)) { 2630 final File scanFile = mExpectingBetter.valueAt(i); 2631 2632 logCriticalInfo(Log.WARN, "Expected better " + packageName 2633 + " but never showed up; reverting to system"); 2634 2635 int reparseFlags = mDefParseFlags; 2636 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2637 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2638 | PackageParser.PARSE_IS_SYSTEM_DIR 2639 | PackageParser.PARSE_IS_PRIVILEGED; 2640 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2641 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2642 | PackageParser.PARSE_IS_SYSTEM_DIR; 2643 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2644 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2645 | PackageParser.PARSE_IS_SYSTEM_DIR; 2646 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2647 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR; 2649 } else { 2650 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2651 continue; 2652 } 2653 2654 mSettings.enableSystemPackageLPw(packageName); 2655 2656 try { 2657 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2658 } catch (PackageManagerException e) { 2659 Slog.e(TAG, "Failed to parse original system package: " 2660 + e.getMessage()); 2661 } 2662 } 2663 } 2664 } 2665 mExpectingBetter.clear(); 2666 2667 // Resolve the storage manager. 2668 mStorageManagerPackage = getStorageManagerPackageName(); 2669 2670 // Resolve protected action filters. Only the setup wizard is allowed to 2671 // have a high priority filter for these actions. 2672 mSetupWizardPackage = getSetupWizardPackageName(); 2673 if (mProtectedFilters.size() > 0) { 2674 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2675 Slog.i(TAG, "No setup wizard;" 2676 + " All protected intents capped to priority 0"); 2677 } 2678 for (ActivityIntentInfo filter : mProtectedFilters) { 2679 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2680 if (DEBUG_FILTERS) { 2681 Slog.i(TAG, "Found setup wizard;" 2682 + " allow priority " + filter.getPriority() + ";" 2683 + " package: " + filter.activity.info.packageName 2684 + " activity: " + filter.activity.className 2685 + " priority: " + filter.getPriority()); 2686 } 2687 // skip setup wizard; allow it to keep the high priority filter 2688 continue; 2689 } 2690 Slog.w(TAG, "Protected action; cap priority to 0;" 2691 + " package: " + filter.activity.info.packageName 2692 + " activity: " + filter.activity.className 2693 + " origPrio: " + filter.getPriority()); 2694 filter.setPriority(0); 2695 } 2696 } 2697 mDeferProtectedFilters = false; 2698 mProtectedFilters.clear(); 2699 2700 // Now that we know all of the shared libraries, update all clients to have 2701 // the correct library paths. 2702 updateAllSharedLibrariesLPw(null); 2703 2704 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2705 // NOTE: We ignore potential failures here during a system scan (like 2706 // the rest of the commands above) because there's precious little we 2707 // can do about it. A settings error is reported, though. 2708 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2709 } 2710 2711 // Now that we know all the packages we are keeping, 2712 // read and update their last usage times. 2713 mPackageUsage.read(mPackages); 2714 mCompilerStats.read(); 2715 2716 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2717 SystemClock.uptimeMillis()); 2718 Slog.i(TAG, "Time to scan packages: " 2719 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2720 + " seconds"); 2721 2722 // If the platform SDK has changed since the last time we booted, 2723 // we need to re-grant app permission to catch any new ones that 2724 // appear. This is really a hack, and means that apps can in some 2725 // cases get permissions that the user didn't initially explicitly 2726 // allow... it would be nice to have some better way to handle 2727 // this situation. 2728 int updateFlags = UPDATE_PERMISSIONS_ALL; 2729 if (ver.sdkVersion != mSdkVersion) { 2730 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2731 + mSdkVersion + "; regranting permissions for internal storage"); 2732 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2733 } 2734 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2735 ver.sdkVersion = mSdkVersion; 2736 2737 // If this is the first boot or an update from pre-M, and it is a normal 2738 // boot, then we need to initialize the default preferred apps across 2739 // all defined users. 2740 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2741 for (UserInfo user : sUserManager.getUsers(true)) { 2742 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2743 applyFactoryDefaultBrowserLPw(user.id); 2744 primeDomainVerificationsLPw(user.id); 2745 } 2746 } 2747 2748 // Prepare storage for system user really early during boot, 2749 // since core system apps like SettingsProvider and SystemUI 2750 // can't wait for user to start 2751 final int storageFlags; 2752 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2753 storageFlags = StorageManager.FLAG_STORAGE_DE; 2754 } else { 2755 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2756 } 2757 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2758 storageFlags, true /* migrateAppData */); 2759 2760 // If this is first boot after an OTA, and a normal boot, then 2761 // we need to clear code cache directories. 2762 // Note that we do *not* clear the application profiles. These remain valid 2763 // across OTAs and are used to drive profile verification (post OTA) and 2764 // profile compilation (without waiting to collect a fresh set of profiles). 2765 if (mIsUpgrade && !onlyCore) { 2766 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2767 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2768 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2769 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2770 // No apps are running this early, so no need to freeze 2771 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2772 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2773 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2774 } 2775 } 2776 ver.fingerprint = Build.FINGERPRINT; 2777 } 2778 2779 checkDefaultBrowser(); 2780 2781 // clear only after permissions and other defaults have been updated 2782 mExistingSystemPackages.clear(); 2783 mPromoteSystemApps = false; 2784 2785 // All the changes are done during package scanning. 2786 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2787 2788 // can downgrade to reader 2789 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2790 mSettings.writeLPr(); 2791 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2792 2793 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2794 // early on (before the package manager declares itself as early) because other 2795 // components in the system server might ask for package contexts for these apps. 2796 // 2797 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2798 // (i.e, that the data partition is unavailable). 2799 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2800 long start = System.nanoTime(); 2801 List<PackageParser.Package> coreApps = new ArrayList<>(); 2802 for (PackageParser.Package pkg : mPackages.values()) { 2803 if (pkg.coreApp) { 2804 coreApps.add(pkg); 2805 } 2806 } 2807 2808 int[] stats = performDexOptUpgrade(coreApps, false, 2809 getCompilerFilterForReason(REASON_CORE_APP)); 2810 2811 final int elapsedTimeSeconds = 2812 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2813 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2814 2815 if (DEBUG_DEXOPT) { 2816 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2817 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2818 } 2819 2820 2821 // TODO: Should we log these stats to tron too ? 2822 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2823 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2824 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2825 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2826 } 2827 2828 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2829 SystemClock.uptimeMillis()); 2830 2831 if (!mOnlyCore) { 2832 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2833 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2834 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2835 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2836 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2837 mIntentFilterVerifierComponent); 2838 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2839 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2840 SharedLibraryInfo.VERSION_UNDEFINED); 2841 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2842 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2843 SharedLibraryInfo.VERSION_UNDEFINED); 2844 } else { 2845 mRequiredVerifierPackage = null; 2846 mRequiredInstallerPackage = null; 2847 mRequiredUninstallerPackage = null; 2848 mIntentFilterVerifierComponent = null; 2849 mIntentFilterVerifier = null; 2850 mServicesSystemSharedLibraryPackageName = null; 2851 mSharedSystemSharedLibraryPackageName = null; 2852 } 2853 2854 mInstallerService = new PackageInstallerService(context, this); 2855 2856 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2857 if (ephemeralResolverComponent != null) { 2858 if (DEBUG_EPHEMERAL) { 2859 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2860 } 2861 mEphemeralResolverConnection = 2862 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2863 } else { 2864 mEphemeralResolverConnection = null; 2865 } 2866 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2867 if (mEphemeralInstallerComponent != null) { 2868 if (DEBUG_EPHEMERAL) { 2869 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2870 } 2871 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2872 } 2873 2874 // Read and update the usage of dex files. 2875 // Do this at the end of PM init so that all the packages have their 2876 // data directory reconciled. 2877 // At this point we know the code paths of the packages, so we can validate 2878 // the disk file and build the internal cache. 2879 // The usage file is expected to be small so loading and verifying it 2880 // should take a fairly small time compare to the other activities (e.g. package 2881 // scanning). 2882 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2883 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2884 for (int userId : currentUserIds) { 2885 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2886 } 2887 mDexManager.load(userPackages); 2888 } // synchronized (mPackages) 2889 } // synchronized (mInstallLock) 2890 2891 // Now after opening every single application zip, make sure they 2892 // are all flushed. Not really needed, but keeps things nice and 2893 // tidy. 2894 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2895 Runtime.getRuntime().gc(); 2896 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2897 2898 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2899 FallbackCategoryProvider.loadFallbacks(); 2900 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2901 2902 // The initial scanning above does many calls into installd while 2903 // holding the mPackages lock, but we're mostly interested in yelling 2904 // once we have a booted system. 2905 mInstaller.setWarnIfHeld(mPackages); 2906 2907 // Expose private service for system components to use. 2908 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2909 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2910 } 2911 2912 private static File preparePackageParserCache(boolean isUpgrade) { 2913 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2914 return null; 2915 } 2916 2917 // Disable package parsing on eng builds to allow for faster incremental development. 2918 if ("eng".equals(Build.TYPE)) { 2919 return null; 2920 } 2921 2922 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2923 Slog.i(TAG, "Disabling package parser cache due to system property."); 2924 return null; 2925 } 2926 2927 // The base directory for the package parser cache lives under /data/system/. 2928 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2929 "package_cache"); 2930 if (cacheBaseDir == null) { 2931 return null; 2932 } 2933 2934 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2935 // This also serves to "GC" unused entries when the package cache version changes (which 2936 // can only happen during upgrades). 2937 if (isUpgrade) { 2938 FileUtils.deleteContents(cacheBaseDir); 2939 } 2940 2941 2942 // Return the versioned package cache directory. This is something like 2943 // "/data/system/package_cache/1" 2944 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2945 2946 // The following is a workaround to aid development on non-numbered userdebug 2947 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2948 // the system partition is newer. 2949 // 2950 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2951 // that starts with "eng." to signify that this is an engineering build and not 2952 // destined for release. 2953 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2954 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2955 2956 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2957 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2958 // in general and should not be used for production changes. In this specific case, 2959 // we know that they will work. 2960 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2961 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2962 FileUtils.deleteContents(cacheBaseDir); 2963 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2964 } 2965 } 2966 2967 return cacheDir; 2968 } 2969 2970 @Override 2971 public boolean isFirstBoot() { 2972 return mFirstBoot; 2973 } 2974 2975 @Override 2976 public boolean isOnlyCoreApps() { 2977 return mOnlyCore; 2978 } 2979 2980 @Override 2981 public boolean isUpgrade() { 2982 return mIsUpgrade; 2983 } 2984 2985 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2986 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2987 2988 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2989 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2990 UserHandle.USER_SYSTEM); 2991 if (matches.size() == 1) { 2992 return matches.get(0).getComponentInfo().packageName; 2993 } else if (matches.size() == 0) { 2994 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2995 return null; 2996 } 2997 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2998 } 2999 3000 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3001 synchronized (mPackages) { 3002 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3003 if (libraryEntry == null) { 3004 throw new IllegalStateException("Missing required shared library:" + name); 3005 } 3006 return libraryEntry.apk; 3007 } 3008 } 3009 3010 private @NonNull String getRequiredInstallerLPr() { 3011 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3012 intent.addCategory(Intent.CATEGORY_DEFAULT); 3013 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3014 3015 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3016 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3017 UserHandle.USER_SYSTEM); 3018 if (matches.size() == 1) { 3019 ResolveInfo resolveInfo = matches.get(0); 3020 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3021 throw new RuntimeException("The installer must be a privileged app"); 3022 } 3023 return matches.get(0).getComponentInfo().packageName; 3024 } else { 3025 throw new RuntimeException("There must be exactly one installer; found " + matches); 3026 } 3027 } 3028 3029 private @NonNull String getRequiredUninstallerLPr() { 3030 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3031 intent.addCategory(Intent.CATEGORY_DEFAULT); 3032 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3033 3034 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3035 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3036 UserHandle.USER_SYSTEM); 3037 if (resolveInfo == null || 3038 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3039 throw new RuntimeException("There must be exactly one uninstaller; found " 3040 + resolveInfo); 3041 } 3042 return resolveInfo.getComponentInfo().packageName; 3043 } 3044 3045 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3046 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3047 3048 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3049 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3050 UserHandle.USER_SYSTEM); 3051 ResolveInfo best = null; 3052 final int N = matches.size(); 3053 for (int i = 0; i < N; i++) { 3054 final ResolveInfo cur = matches.get(i); 3055 final String packageName = cur.getComponentInfo().packageName; 3056 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3057 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3058 continue; 3059 } 3060 3061 if (best == null || cur.priority > best.priority) { 3062 best = cur; 3063 } 3064 } 3065 3066 if (best != null) { 3067 return best.getComponentInfo().getComponentName(); 3068 } else { 3069 throw new RuntimeException("There must be at least one intent filter verifier"); 3070 } 3071 } 3072 3073 private @Nullable ComponentName getEphemeralResolverLPr() { 3074 final String[] packageArray = 3075 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3076 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3077 if (DEBUG_EPHEMERAL) { 3078 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3079 } 3080 return null; 3081 } 3082 3083 final int resolveFlags = 3084 MATCH_DIRECT_BOOT_AWARE 3085 | MATCH_DIRECT_BOOT_UNAWARE 3086 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3087 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3088 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3089 resolveFlags, UserHandle.USER_SYSTEM); 3090 3091 final int N = resolvers.size(); 3092 if (N == 0) { 3093 if (DEBUG_EPHEMERAL) { 3094 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3095 } 3096 return null; 3097 } 3098 3099 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3100 for (int i = 0; i < N; i++) { 3101 final ResolveInfo info = resolvers.get(i); 3102 3103 if (info.serviceInfo == null) { 3104 continue; 3105 } 3106 3107 final String packageName = info.serviceInfo.packageName; 3108 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3109 if (DEBUG_EPHEMERAL) { 3110 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3111 + " pkg: " + packageName + ", info:" + info); 3112 } 3113 continue; 3114 } 3115 3116 if (DEBUG_EPHEMERAL) { 3117 Slog.v(TAG, "Ephemeral resolver found;" 3118 + " pkg: " + packageName + ", info:" + info); 3119 } 3120 return new ComponentName(packageName, info.serviceInfo.name); 3121 } 3122 if (DEBUG_EPHEMERAL) { 3123 Slog.v(TAG, "Ephemeral resolver NOT found"); 3124 } 3125 return null; 3126 } 3127 3128 private @Nullable ComponentName getEphemeralInstallerLPr() { 3129 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3130 intent.addCategory(Intent.CATEGORY_DEFAULT); 3131 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3132 3133 final int resolveFlags = 3134 MATCH_DIRECT_BOOT_AWARE 3135 | MATCH_DIRECT_BOOT_UNAWARE 3136 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3137 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3138 resolveFlags, UserHandle.USER_SYSTEM); 3139 Iterator<ResolveInfo> iter = matches.iterator(); 3140 while (iter.hasNext()) { 3141 final ResolveInfo rInfo = iter.next(); 3142 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3143 if (ps != null) { 3144 final PermissionsState permissionsState = ps.getPermissionsState(); 3145 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3146 continue; 3147 } 3148 } 3149 iter.remove(); 3150 } 3151 if (matches.size() == 0) { 3152 return null; 3153 } else if (matches.size() == 1) { 3154 return matches.get(0).getComponentInfo().getComponentName(); 3155 } else { 3156 throw new RuntimeException( 3157 "There must be at most one ephemeral installer; found " + matches); 3158 } 3159 } 3160 3161 private void primeDomainVerificationsLPw(int userId) { 3162 if (DEBUG_DOMAIN_VERIFICATION) { 3163 Slog.d(TAG, "Priming domain verifications in user " + userId); 3164 } 3165 3166 SystemConfig systemConfig = SystemConfig.getInstance(); 3167 ArraySet<String> packages = systemConfig.getLinkedApps(); 3168 3169 for (String packageName : packages) { 3170 PackageParser.Package pkg = mPackages.get(packageName); 3171 if (pkg != null) { 3172 if (!pkg.isSystemApp()) { 3173 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3174 continue; 3175 } 3176 3177 ArraySet<String> domains = null; 3178 for (PackageParser.Activity a : pkg.activities) { 3179 for (ActivityIntentInfo filter : a.intents) { 3180 if (hasValidDomains(filter)) { 3181 if (domains == null) { 3182 domains = new ArraySet<String>(); 3183 } 3184 domains.addAll(filter.getHostsList()); 3185 } 3186 } 3187 } 3188 3189 if (domains != null && domains.size() > 0) { 3190 if (DEBUG_DOMAIN_VERIFICATION) { 3191 Slog.v(TAG, " + " + packageName); 3192 } 3193 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3194 // state w.r.t. the formal app-linkage "no verification attempted" state; 3195 // and then 'always' in the per-user state actually used for intent resolution. 3196 final IntentFilterVerificationInfo ivi; 3197 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3198 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3199 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3200 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3201 } else { 3202 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3203 + "' does not handle web links"); 3204 } 3205 } else { 3206 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3207 } 3208 } 3209 3210 scheduleWritePackageRestrictionsLocked(userId); 3211 scheduleWriteSettingsLocked(); 3212 } 3213 3214 private void applyFactoryDefaultBrowserLPw(int userId) { 3215 // The default browser app's package name is stored in a string resource, 3216 // with a product-specific overlay used for vendor customization. 3217 String browserPkg = mContext.getResources().getString( 3218 com.android.internal.R.string.default_browser); 3219 if (!TextUtils.isEmpty(browserPkg)) { 3220 // non-empty string => required to be a known package 3221 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3222 if (ps == null) { 3223 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3224 browserPkg = null; 3225 } else { 3226 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3227 } 3228 } 3229 3230 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3231 // default. If there's more than one, just leave everything alone. 3232 if (browserPkg == null) { 3233 calculateDefaultBrowserLPw(userId); 3234 } 3235 } 3236 3237 private void calculateDefaultBrowserLPw(int userId) { 3238 List<String> allBrowsers = resolveAllBrowserApps(userId); 3239 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3240 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3241 } 3242 3243 private List<String> resolveAllBrowserApps(int userId) { 3244 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3245 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3246 PackageManager.MATCH_ALL, userId); 3247 3248 final int count = list.size(); 3249 List<String> result = new ArrayList<String>(count); 3250 for (int i=0; i<count; i++) { 3251 ResolveInfo info = list.get(i); 3252 if (info.activityInfo == null 3253 || !info.handleAllWebDataURI 3254 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3255 || result.contains(info.activityInfo.packageName)) { 3256 continue; 3257 } 3258 result.add(info.activityInfo.packageName); 3259 } 3260 3261 return result; 3262 } 3263 3264 private boolean packageIsBrowser(String packageName, int userId) { 3265 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3266 PackageManager.MATCH_ALL, userId); 3267 final int N = list.size(); 3268 for (int i = 0; i < N; i++) { 3269 ResolveInfo info = list.get(i); 3270 if (packageName.equals(info.activityInfo.packageName)) { 3271 return true; 3272 } 3273 } 3274 return false; 3275 } 3276 3277 private void checkDefaultBrowser() { 3278 final int myUserId = UserHandle.myUserId(); 3279 final String packageName = getDefaultBrowserPackageName(myUserId); 3280 if (packageName != null) { 3281 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3282 if (info == null) { 3283 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3284 synchronized (mPackages) { 3285 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3286 } 3287 } 3288 } 3289 } 3290 3291 @Override 3292 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3293 throws RemoteException { 3294 try { 3295 return super.onTransact(code, data, reply, flags); 3296 } catch (RuntimeException e) { 3297 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3298 Slog.wtf(TAG, "Package Manager Crash", e); 3299 } 3300 throw e; 3301 } 3302 } 3303 3304 static int[] appendInts(int[] cur, int[] add) { 3305 if (add == null) return cur; 3306 if (cur == null) return add; 3307 final int N = add.length; 3308 for (int i=0; i<N; i++) { 3309 cur = appendInt(cur, add[i]); 3310 } 3311 return cur; 3312 } 3313 3314 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3315 if (!sUserManager.exists(userId)) return null; 3316 if (ps == null) { 3317 return null; 3318 } 3319 final PackageParser.Package p = ps.pkg; 3320 if (p == null) { 3321 return null; 3322 } 3323 // Filter out ephemeral app metadata: 3324 // * The system/shell/root can see metadata for any app 3325 // * An installed app can see metadata for 1) other installed apps 3326 // and 2) ephemeral apps that have explicitly interacted with it 3327 // * Ephemeral apps can only see their own metadata 3328 // * Holding a signature permission allows seeing instant apps 3329 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3330 if (callingAppId != Process.SYSTEM_UID 3331 && callingAppId != Process.SHELL_UID 3332 && callingAppId != Process.ROOT_UID 3333 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3334 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3335 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3336 if (instantAppPackageName != null) { 3337 // ephemeral apps can only get information on themselves 3338 if (!instantAppPackageName.equals(p.packageName)) { 3339 return null; 3340 } 3341 } else { 3342 if (ps.getInstantApp(userId)) { 3343 // only get access to the ephemeral app if we've been granted access 3344 if (!mInstantAppRegistry.isInstantAccessGranted( 3345 userId, callingAppId, ps.appId)) { 3346 return null; 3347 } 3348 } 3349 } 3350 } 3351 3352 final PermissionsState permissionsState = ps.getPermissionsState(); 3353 3354 // Compute GIDs only if requested 3355 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3356 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3357 // Compute granted permissions only if package has requested permissions 3358 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3359 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3360 final PackageUserState state = ps.readUserState(userId); 3361 3362 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3363 && ps.isSystem()) { 3364 flags |= MATCH_ANY_USER; 3365 } 3366 3367 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3368 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3369 3370 if (packageInfo == null) { 3371 return null; 3372 } 3373 3374 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3375 resolveExternalPackageNameLPr(p); 3376 3377 return packageInfo; 3378 } 3379 3380 @Override 3381 public void checkPackageStartable(String packageName, int userId) { 3382 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3383 3384 synchronized (mPackages) { 3385 final PackageSetting ps = mSettings.mPackages.get(packageName); 3386 if (ps == null) { 3387 throw new SecurityException("Package " + packageName + " was not found!"); 3388 } 3389 3390 if (!ps.getInstalled(userId)) { 3391 throw new SecurityException( 3392 "Package " + packageName + " was not installed for user " + userId + "!"); 3393 } 3394 3395 if (mSafeMode && !ps.isSystem()) { 3396 throw new SecurityException("Package " + packageName + " not a system app!"); 3397 } 3398 3399 if (mFrozenPackages.contains(packageName)) { 3400 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3401 } 3402 3403 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3404 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3405 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3406 } 3407 } 3408 } 3409 3410 @Override 3411 public boolean isPackageAvailable(String packageName, int userId) { 3412 if (!sUserManager.exists(userId)) return false; 3413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3414 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3415 synchronized (mPackages) { 3416 PackageParser.Package p = mPackages.get(packageName); 3417 if (p != null) { 3418 final PackageSetting ps = (PackageSetting) p.mExtras; 3419 if (ps != null) { 3420 final PackageUserState state = ps.readUserState(userId); 3421 if (state != null) { 3422 return PackageParser.isAvailable(state); 3423 } 3424 } 3425 } 3426 } 3427 return false; 3428 } 3429 3430 @Override 3431 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3432 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3433 flags, userId); 3434 } 3435 3436 @Override 3437 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3438 int flags, int userId) { 3439 return getPackageInfoInternal(versionedPackage.getPackageName(), 3440 // TODO: We will change version code to long, so in the new API it is long 3441 (int) versionedPackage.getVersionCode(), flags, userId); 3442 } 3443 3444 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3445 int flags, int userId) { 3446 if (!sUserManager.exists(userId)) return null; 3447 flags = updateFlagsForPackage(flags, userId, packageName); 3448 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3449 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3450 3451 // reader 3452 synchronized (mPackages) { 3453 // Normalize package name to handle renamed packages and static libs 3454 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3455 3456 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3457 if (matchFactoryOnly) { 3458 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3459 if (ps != null) { 3460 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3461 return null; 3462 } 3463 return generatePackageInfo(ps, flags, userId); 3464 } 3465 } 3466 3467 PackageParser.Package p = mPackages.get(packageName); 3468 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3469 return null; 3470 } 3471 if (DEBUG_PACKAGE_INFO) 3472 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3473 if (p != null) { 3474 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3475 Binder.getCallingUid(), userId)) { 3476 return null; 3477 } 3478 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3479 } 3480 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3481 final PackageSetting ps = mSettings.mPackages.get(packageName); 3482 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3483 return null; 3484 } 3485 return generatePackageInfo(ps, flags, userId); 3486 } 3487 } 3488 return null; 3489 } 3490 3491 3492 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3493 // System/shell/root get to see all static libs 3494 final int appId = UserHandle.getAppId(uid); 3495 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3496 || appId == Process.ROOT_UID) { 3497 return false; 3498 } 3499 3500 // No package means no static lib as it is always on internal storage 3501 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3502 return false; 3503 } 3504 3505 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3506 ps.pkg.staticSharedLibVersion); 3507 if (libEntry == null) { 3508 return false; 3509 } 3510 3511 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3512 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3513 if (uidPackageNames == null) { 3514 return true; 3515 } 3516 3517 for (String uidPackageName : uidPackageNames) { 3518 if (ps.name.equals(uidPackageName)) { 3519 return false; 3520 } 3521 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3522 if (uidPs != null) { 3523 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3524 libEntry.info.getName()); 3525 if (index < 0) { 3526 continue; 3527 } 3528 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3529 return false; 3530 } 3531 } 3532 } 3533 return true; 3534 } 3535 3536 @Override 3537 public String[] currentToCanonicalPackageNames(String[] names) { 3538 String[] out = new String[names.length]; 3539 // reader 3540 synchronized (mPackages) { 3541 for (int i=names.length-1; i>=0; i--) { 3542 PackageSetting ps = mSettings.mPackages.get(names[i]); 3543 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3544 } 3545 } 3546 return out; 3547 } 3548 3549 @Override 3550 public String[] canonicalToCurrentPackageNames(String[] names) { 3551 String[] out = new String[names.length]; 3552 // reader 3553 synchronized (mPackages) { 3554 for (int i=names.length-1; i>=0; i--) { 3555 String cur = mSettings.getRenamedPackageLPr(names[i]); 3556 out[i] = cur != null ? cur : names[i]; 3557 } 3558 } 3559 return out; 3560 } 3561 3562 @Override 3563 public int getPackageUid(String packageName, int flags, int userId) { 3564 if (!sUserManager.exists(userId)) return -1; 3565 flags = updateFlagsForPackage(flags, userId, packageName); 3566 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3567 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3568 3569 // reader 3570 synchronized (mPackages) { 3571 final PackageParser.Package p = mPackages.get(packageName); 3572 if (p != null && p.isMatch(flags)) { 3573 return UserHandle.getUid(userId, p.applicationInfo.uid); 3574 } 3575 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3576 final PackageSetting ps = mSettings.mPackages.get(packageName); 3577 if (ps != null && ps.isMatch(flags)) { 3578 return UserHandle.getUid(userId, ps.appId); 3579 } 3580 } 3581 } 3582 3583 return -1; 3584 } 3585 3586 @Override 3587 public int[] getPackageGids(String packageName, int flags, int userId) { 3588 if (!sUserManager.exists(userId)) return null; 3589 flags = updateFlagsForPackage(flags, userId, packageName); 3590 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3591 false /* requireFullPermission */, false /* checkShell */, 3592 "getPackageGids"); 3593 3594 // reader 3595 synchronized (mPackages) { 3596 final PackageParser.Package p = mPackages.get(packageName); 3597 if (p != null && p.isMatch(flags)) { 3598 PackageSetting ps = (PackageSetting) p.mExtras; 3599 // TODO: Shouldn't this be checking for package installed state for userId and 3600 // return null? 3601 return ps.getPermissionsState().computeGids(userId); 3602 } 3603 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3604 final PackageSetting ps = mSettings.mPackages.get(packageName); 3605 if (ps != null && ps.isMatch(flags)) { 3606 return ps.getPermissionsState().computeGids(userId); 3607 } 3608 } 3609 } 3610 3611 return null; 3612 } 3613 3614 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3615 if (bp.perm != null) { 3616 return PackageParser.generatePermissionInfo(bp.perm, flags); 3617 } 3618 PermissionInfo pi = new PermissionInfo(); 3619 pi.name = bp.name; 3620 pi.packageName = bp.sourcePackage; 3621 pi.nonLocalizedLabel = bp.name; 3622 pi.protectionLevel = bp.protectionLevel; 3623 return pi; 3624 } 3625 3626 @Override 3627 public PermissionInfo getPermissionInfo(String name, int flags) { 3628 // reader 3629 synchronized (mPackages) { 3630 final BasePermission p = mSettings.mPermissions.get(name); 3631 if (p != null) { 3632 return generatePermissionInfo(p, flags); 3633 } 3634 return null; 3635 } 3636 } 3637 3638 @Override 3639 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3640 int flags) { 3641 // reader 3642 synchronized (mPackages) { 3643 if (group != null && !mPermissionGroups.containsKey(group)) { 3644 // This is thrown as NameNotFoundException 3645 return null; 3646 } 3647 3648 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3649 for (BasePermission p : mSettings.mPermissions.values()) { 3650 if (group == null) { 3651 if (p.perm == null || p.perm.info.group == null) { 3652 out.add(generatePermissionInfo(p, flags)); 3653 } 3654 } else { 3655 if (p.perm != null && group.equals(p.perm.info.group)) { 3656 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3657 } 3658 } 3659 } 3660 return new ParceledListSlice<>(out); 3661 } 3662 } 3663 3664 @Override 3665 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3666 // reader 3667 synchronized (mPackages) { 3668 return PackageParser.generatePermissionGroupInfo( 3669 mPermissionGroups.get(name), flags); 3670 } 3671 } 3672 3673 @Override 3674 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3675 // reader 3676 synchronized (mPackages) { 3677 final int N = mPermissionGroups.size(); 3678 ArrayList<PermissionGroupInfo> out 3679 = new ArrayList<PermissionGroupInfo>(N); 3680 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3681 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3682 } 3683 return new ParceledListSlice<>(out); 3684 } 3685 } 3686 3687 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3688 int uid, int userId) { 3689 if (!sUserManager.exists(userId)) return null; 3690 PackageSetting ps = mSettings.mPackages.get(packageName); 3691 if (ps != null) { 3692 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3693 return null; 3694 } 3695 if (ps.pkg == null) { 3696 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3697 if (pInfo != null) { 3698 return pInfo.applicationInfo; 3699 } 3700 return null; 3701 } 3702 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3703 ps.readUserState(userId), userId); 3704 if (ai != null) { 3705 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3706 } 3707 return ai; 3708 } 3709 return null; 3710 } 3711 3712 @Override 3713 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3714 if (!sUserManager.exists(userId)) return null; 3715 flags = updateFlagsForApplication(flags, userId, packageName); 3716 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3717 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3718 3719 // writer 3720 synchronized (mPackages) { 3721 // Normalize package name to handle renamed packages and static libs 3722 packageName = resolveInternalPackageNameLPr(packageName, 3723 PackageManager.VERSION_CODE_HIGHEST); 3724 3725 PackageParser.Package p = mPackages.get(packageName); 3726 if (DEBUG_PACKAGE_INFO) Log.v( 3727 TAG, "getApplicationInfo " + packageName 3728 + ": " + p); 3729 if (p != null) { 3730 PackageSetting ps = mSettings.mPackages.get(packageName); 3731 if (ps == null) return null; 3732 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3733 return null; 3734 } 3735 // Note: isEnabledLP() does not apply here - always return info 3736 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3737 p, flags, ps.readUserState(userId), userId); 3738 if (ai != null) { 3739 ai.packageName = resolveExternalPackageNameLPr(p); 3740 } 3741 return ai; 3742 } 3743 if ("android".equals(packageName)||"system".equals(packageName)) { 3744 return mAndroidApplication; 3745 } 3746 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3747 // Already generates the external package name 3748 return generateApplicationInfoFromSettingsLPw(packageName, 3749 Binder.getCallingUid(), flags, userId); 3750 } 3751 } 3752 return null; 3753 } 3754 3755 private String normalizePackageNameLPr(String packageName) { 3756 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3757 return normalizedPackageName != null ? normalizedPackageName : packageName; 3758 } 3759 3760 @Override 3761 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3762 final IPackageDataObserver observer) { 3763 mContext.enforceCallingOrSelfPermission( 3764 android.Manifest.permission.CLEAR_APP_CACHE, null); 3765 // Queue up an async operation since clearing cache may take a little while. 3766 mHandler.post(new Runnable() { 3767 public void run() { 3768 mHandler.removeCallbacks(this); 3769 boolean success = true; 3770 synchronized (mInstallLock) { 3771 try { 3772 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3773 } catch (InstallerException e) { 3774 Slog.w(TAG, "Couldn't clear application caches: " + e); 3775 success = false; 3776 } 3777 } 3778 if (observer != null) { 3779 try { 3780 observer.onRemoveCompleted(null, success); 3781 } catch (RemoteException e) { 3782 Slog.w(TAG, "RemoveException when invoking call back"); 3783 } 3784 } 3785 } 3786 }); 3787 } 3788 3789 @Override 3790 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3791 final IntentSender pi) { 3792 mContext.enforceCallingOrSelfPermission( 3793 android.Manifest.permission.CLEAR_APP_CACHE, null); 3794 // Queue up an async operation since clearing cache may take a little while. 3795 mHandler.post(new Runnable() { 3796 public void run() { 3797 mHandler.removeCallbacks(this); 3798 boolean success = true; 3799 synchronized (mInstallLock) { 3800 try { 3801 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3802 } catch (InstallerException e) { 3803 Slog.w(TAG, "Couldn't clear application caches: " + e); 3804 success = false; 3805 } 3806 } 3807 if(pi != null) { 3808 try { 3809 // Callback via pending intent 3810 int code = success ? 1 : 0; 3811 pi.sendIntent(null, code, null, 3812 null, null); 3813 } catch (SendIntentException e1) { 3814 Slog.i(TAG, "Failed to send pending intent"); 3815 } 3816 } 3817 } 3818 }); 3819 } 3820 3821 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3822 synchronized (mInstallLock) { 3823 try { 3824 mInstaller.freeCache(volumeUuid, freeStorageSize, 0); 3825 } catch (InstallerException e) { 3826 throw new IOException("Failed to free enough space", e); 3827 } 3828 } 3829 } 3830 3831 /** 3832 * Update given flags based on encryption status of current user. 3833 */ 3834 private int updateFlags(int flags, int userId) { 3835 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3836 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3837 // Caller expressed an explicit opinion about what encryption 3838 // aware/unaware components they want to see, so fall through and 3839 // give them what they want 3840 } else { 3841 // Caller expressed no opinion, so match based on user state 3842 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3843 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3844 } else { 3845 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3846 } 3847 } 3848 return flags; 3849 } 3850 3851 private UserManagerInternal getUserManagerInternal() { 3852 if (mUserManagerInternal == null) { 3853 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3854 } 3855 return mUserManagerInternal; 3856 } 3857 3858 /** 3859 * Update given flags when being used to request {@link PackageInfo}. 3860 */ 3861 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3862 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3863 boolean triaged = true; 3864 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3865 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3866 // Caller is asking for component details, so they'd better be 3867 // asking for specific encryption matching behavior, or be triaged 3868 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3869 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3870 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3871 triaged = false; 3872 } 3873 } 3874 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3875 | PackageManager.MATCH_SYSTEM_ONLY 3876 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3877 triaged = false; 3878 } 3879 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3880 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3881 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3882 + Debug.getCallers(5)); 3883 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3884 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3885 // If the caller wants all packages and has a restricted profile associated with it, 3886 // then match all users. This is to make sure that launchers that need to access work 3887 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3888 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3889 flags |= PackageManager.MATCH_ANY_USER; 3890 } 3891 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3892 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3893 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3894 } 3895 return updateFlags(flags, userId); 3896 } 3897 3898 /** 3899 * Update given flags when being used to request {@link ApplicationInfo}. 3900 */ 3901 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3902 return updateFlagsForPackage(flags, userId, cookie); 3903 } 3904 3905 /** 3906 * Update given flags when being used to request {@link ComponentInfo}. 3907 */ 3908 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3909 if (cookie instanceof Intent) { 3910 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3911 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3912 } 3913 } 3914 3915 boolean triaged = true; 3916 // Caller is asking for component details, so they'd better be 3917 // asking for specific encryption matching behavior, or be triaged 3918 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3919 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3920 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3921 triaged = false; 3922 } 3923 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3924 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3925 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3926 } 3927 3928 return updateFlags(flags, userId); 3929 } 3930 3931 /** 3932 * Update given intent when being used to request {@link ResolveInfo}. 3933 */ 3934 private Intent updateIntentForResolve(Intent intent) { 3935 if (intent.getSelector() != null) { 3936 intent = intent.getSelector(); 3937 } 3938 if (DEBUG_PREFERRED) { 3939 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 3940 } 3941 return intent; 3942 } 3943 3944 /** 3945 * Update given flags when being used to request {@link ResolveInfo}. 3946 */ 3947 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3948 // Safe mode means we shouldn't match any third-party components 3949 if (mSafeMode) { 3950 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3951 } 3952 final int callingUid = Binder.getCallingUid(); 3953 if (getInstantAppPackageName(callingUid) != null) { 3954 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 3955 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 3956 flags |= PackageManager.MATCH_INSTANT; 3957 } else { 3958 // Otherwise, prevent leaking ephemeral components 3959 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 3960 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3961 // Unless called from the system process 3962 flags &= ~PackageManager.MATCH_INSTANT; 3963 } 3964 } 3965 return updateFlagsForComponent(flags, userId, cookie); 3966 } 3967 3968 @Override 3969 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3970 if (!sUserManager.exists(userId)) return null; 3971 flags = updateFlagsForComponent(flags, userId, component); 3972 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3973 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3974 synchronized (mPackages) { 3975 PackageParser.Activity a = mActivities.mActivities.get(component); 3976 3977 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3978 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3979 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3980 if (ps == null) return null; 3981 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3982 userId); 3983 } 3984 if (mResolveComponentName.equals(component)) { 3985 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3986 new PackageUserState(), userId); 3987 } 3988 } 3989 return null; 3990 } 3991 3992 @Override 3993 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3994 String resolvedType) { 3995 synchronized (mPackages) { 3996 if (component.equals(mResolveComponentName)) { 3997 // The resolver supports EVERYTHING! 3998 return true; 3999 } 4000 PackageParser.Activity a = mActivities.mActivities.get(component); 4001 if (a == null) { 4002 return false; 4003 } 4004 for (int i=0; i<a.intents.size(); i++) { 4005 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4006 intent.getData(), intent.getCategories(), TAG) >= 0) { 4007 return true; 4008 } 4009 } 4010 return false; 4011 } 4012 } 4013 4014 @Override 4015 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4016 if (!sUserManager.exists(userId)) return null; 4017 flags = updateFlagsForComponent(flags, userId, component); 4018 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4019 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4020 synchronized (mPackages) { 4021 PackageParser.Activity a = mReceivers.mActivities.get(component); 4022 if (DEBUG_PACKAGE_INFO) Log.v( 4023 TAG, "getReceiverInfo " + component + ": " + a); 4024 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4025 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4026 if (ps == null) return null; 4027 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4028 userId); 4029 } 4030 } 4031 return null; 4032 } 4033 4034 @Override 4035 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4036 if (!sUserManager.exists(userId)) return null; 4037 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4038 4039 flags = updateFlagsForPackage(flags, userId, null); 4040 4041 final boolean canSeeStaticLibraries = 4042 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4043 == PERMISSION_GRANTED 4044 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4045 == PERMISSION_GRANTED 4046 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4047 == PERMISSION_GRANTED 4048 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4049 == PERMISSION_GRANTED; 4050 4051 synchronized (mPackages) { 4052 List<SharedLibraryInfo> result = null; 4053 4054 final int libCount = mSharedLibraries.size(); 4055 for (int i = 0; i < libCount; i++) { 4056 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4057 if (versionedLib == null) { 4058 continue; 4059 } 4060 4061 final int versionCount = versionedLib.size(); 4062 for (int j = 0; j < versionCount; j++) { 4063 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4064 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4065 break; 4066 } 4067 final long identity = Binder.clearCallingIdentity(); 4068 try { 4069 // TODO: We will change version code to long, so in the new API it is long 4070 PackageInfo packageInfo = getPackageInfoVersioned( 4071 libInfo.getDeclaringPackage(), flags, userId); 4072 if (packageInfo == null) { 4073 continue; 4074 } 4075 } finally { 4076 Binder.restoreCallingIdentity(identity); 4077 } 4078 4079 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4080 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4081 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4082 4083 if (result == null) { 4084 result = new ArrayList<>(); 4085 } 4086 result.add(resLibInfo); 4087 } 4088 } 4089 4090 return result != null ? new ParceledListSlice<>(result) : null; 4091 } 4092 } 4093 4094 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4095 SharedLibraryInfo libInfo, int flags, int userId) { 4096 List<VersionedPackage> versionedPackages = null; 4097 final int packageCount = mSettings.mPackages.size(); 4098 for (int i = 0; i < packageCount; i++) { 4099 PackageSetting ps = mSettings.mPackages.valueAt(i); 4100 4101 if (ps == null) { 4102 continue; 4103 } 4104 4105 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4106 continue; 4107 } 4108 4109 final String libName = libInfo.getName(); 4110 if (libInfo.isStatic()) { 4111 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4112 if (libIdx < 0) { 4113 continue; 4114 } 4115 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4116 continue; 4117 } 4118 if (versionedPackages == null) { 4119 versionedPackages = new ArrayList<>(); 4120 } 4121 // If the dependent is a static shared lib, use the public package name 4122 String dependentPackageName = ps.name; 4123 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4124 dependentPackageName = ps.pkg.manifestPackageName; 4125 } 4126 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4127 } else if (ps.pkg != null) { 4128 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4129 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4130 if (versionedPackages == null) { 4131 versionedPackages = new ArrayList<>(); 4132 } 4133 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4134 } 4135 } 4136 } 4137 4138 return versionedPackages; 4139 } 4140 4141 @Override 4142 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4143 if (!sUserManager.exists(userId)) return null; 4144 flags = updateFlagsForComponent(flags, userId, component); 4145 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4146 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4147 synchronized (mPackages) { 4148 PackageParser.Service s = mServices.mServices.get(component); 4149 if (DEBUG_PACKAGE_INFO) Log.v( 4150 TAG, "getServiceInfo " + component + ": " + s); 4151 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4152 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4153 if (ps == null) return null; 4154 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4155 userId); 4156 } 4157 } 4158 return null; 4159 } 4160 4161 @Override 4162 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4163 if (!sUserManager.exists(userId)) return null; 4164 flags = updateFlagsForComponent(flags, userId, component); 4165 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4166 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4167 synchronized (mPackages) { 4168 PackageParser.Provider p = mProviders.mProviders.get(component); 4169 if (DEBUG_PACKAGE_INFO) Log.v( 4170 TAG, "getProviderInfo " + component + ": " + p); 4171 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4172 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4173 if (ps == null) return null; 4174 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4175 userId); 4176 } 4177 } 4178 return null; 4179 } 4180 4181 @Override 4182 public String[] getSystemSharedLibraryNames() { 4183 synchronized (mPackages) { 4184 Set<String> libs = null; 4185 final int libCount = mSharedLibraries.size(); 4186 for (int i = 0; i < libCount; i++) { 4187 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4188 if (versionedLib == null) { 4189 continue; 4190 } 4191 final int versionCount = versionedLib.size(); 4192 for (int j = 0; j < versionCount; j++) { 4193 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4194 if (!libEntry.info.isStatic()) { 4195 if (libs == null) { 4196 libs = new ArraySet<>(); 4197 } 4198 libs.add(libEntry.info.getName()); 4199 break; 4200 } 4201 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4202 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4203 UserHandle.getUserId(Binder.getCallingUid()))) { 4204 if (libs == null) { 4205 libs = new ArraySet<>(); 4206 } 4207 libs.add(libEntry.info.getName()); 4208 break; 4209 } 4210 } 4211 } 4212 4213 if (libs != null) { 4214 String[] libsArray = new String[libs.size()]; 4215 libs.toArray(libsArray); 4216 return libsArray; 4217 } 4218 4219 return null; 4220 } 4221 } 4222 4223 @Override 4224 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4225 synchronized (mPackages) { 4226 return mServicesSystemSharedLibraryPackageName; 4227 } 4228 } 4229 4230 @Override 4231 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4232 synchronized (mPackages) { 4233 return mSharedSystemSharedLibraryPackageName; 4234 } 4235 } 4236 4237 private void updateSequenceNumberLP(String packageName, int[] userList) { 4238 for (int i = userList.length - 1; i >= 0; --i) { 4239 final int userId = userList[i]; 4240 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4241 if (changedPackages == null) { 4242 changedPackages = new SparseArray<>(); 4243 mChangedPackages.put(userId, changedPackages); 4244 } 4245 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4246 if (sequenceNumbers == null) { 4247 sequenceNumbers = new HashMap<>(); 4248 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4249 } 4250 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4251 if (sequenceNumber != null) { 4252 changedPackages.remove(sequenceNumber); 4253 } 4254 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4255 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4256 } 4257 mChangedPackagesSequenceNumber++; 4258 } 4259 4260 @Override 4261 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4262 synchronized (mPackages) { 4263 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4264 return null; 4265 } 4266 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4267 if (changedPackages == null) { 4268 return null; 4269 } 4270 final List<String> packageNames = 4271 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4272 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4273 final String packageName = changedPackages.get(i); 4274 if (packageName != null) { 4275 packageNames.add(packageName); 4276 } 4277 } 4278 return packageNames.isEmpty() 4279 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4280 } 4281 } 4282 4283 @Override 4284 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4285 ArrayList<FeatureInfo> res; 4286 synchronized (mAvailableFeatures) { 4287 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4288 res.addAll(mAvailableFeatures.values()); 4289 } 4290 final FeatureInfo fi = new FeatureInfo(); 4291 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4292 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4293 res.add(fi); 4294 4295 return new ParceledListSlice<>(res); 4296 } 4297 4298 @Override 4299 public boolean hasSystemFeature(String name, int version) { 4300 synchronized (mAvailableFeatures) { 4301 final FeatureInfo feat = mAvailableFeatures.get(name); 4302 if (feat == null) { 4303 return false; 4304 } else { 4305 return feat.version >= version; 4306 } 4307 } 4308 } 4309 4310 @Override 4311 public int checkPermission(String permName, String pkgName, int userId) { 4312 if (!sUserManager.exists(userId)) { 4313 return PackageManager.PERMISSION_DENIED; 4314 } 4315 4316 synchronized (mPackages) { 4317 final PackageParser.Package p = mPackages.get(pkgName); 4318 if (p != null && p.mExtras != null) { 4319 final PackageSetting ps = (PackageSetting) p.mExtras; 4320 final PermissionsState permissionsState = ps.getPermissionsState(); 4321 if (permissionsState.hasPermission(permName, userId)) { 4322 return PackageManager.PERMISSION_GRANTED; 4323 } 4324 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4325 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4326 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4327 return PackageManager.PERMISSION_GRANTED; 4328 } 4329 } 4330 } 4331 4332 return PackageManager.PERMISSION_DENIED; 4333 } 4334 4335 @Override 4336 public int checkUidPermission(String permName, int uid) { 4337 final int userId = UserHandle.getUserId(uid); 4338 4339 if (!sUserManager.exists(userId)) { 4340 return PackageManager.PERMISSION_DENIED; 4341 } 4342 4343 synchronized (mPackages) { 4344 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4345 if (obj != null) { 4346 final SettingBase ps = (SettingBase) obj; 4347 final PermissionsState permissionsState = ps.getPermissionsState(); 4348 if (permissionsState.hasPermission(permName, userId)) { 4349 return PackageManager.PERMISSION_GRANTED; 4350 } 4351 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4352 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4353 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4354 return PackageManager.PERMISSION_GRANTED; 4355 } 4356 } else { 4357 ArraySet<String> perms = mSystemPermissions.get(uid); 4358 if (perms != null) { 4359 if (perms.contains(permName)) { 4360 return PackageManager.PERMISSION_GRANTED; 4361 } 4362 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4363 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4364 return PackageManager.PERMISSION_GRANTED; 4365 } 4366 } 4367 } 4368 } 4369 4370 return PackageManager.PERMISSION_DENIED; 4371 } 4372 4373 @Override 4374 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4375 if (UserHandle.getCallingUserId() != userId) { 4376 mContext.enforceCallingPermission( 4377 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4378 "isPermissionRevokedByPolicy for user " + userId); 4379 } 4380 4381 if (checkPermission(permission, packageName, userId) 4382 == PackageManager.PERMISSION_GRANTED) { 4383 return false; 4384 } 4385 4386 final long identity = Binder.clearCallingIdentity(); 4387 try { 4388 final int flags = getPermissionFlags(permission, packageName, userId); 4389 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4390 } finally { 4391 Binder.restoreCallingIdentity(identity); 4392 } 4393 } 4394 4395 @Override 4396 public String getPermissionControllerPackageName() { 4397 synchronized (mPackages) { 4398 return mRequiredInstallerPackage; 4399 } 4400 } 4401 4402 /** 4403 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4404 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4405 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4406 * @param message the message to log on security exception 4407 */ 4408 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4409 boolean checkShell, String message) { 4410 if (userId < 0) { 4411 throw new IllegalArgumentException("Invalid userId " + userId); 4412 } 4413 if (checkShell) { 4414 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4415 } 4416 if (userId == UserHandle.getUserId(callingUid)) return; 4417 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4418 if (requireFullPermission) { 4419 mContext.enforceCallingOrSelfPermission( 4420 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4421 } else { 4422 try { 4423 mContext.enforceCallingOrSelfPermission( 4424 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4425 } catch (SecurityException se) { 4426 mContext.enforceCallingOrSelfPermission( 4427 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4428 } 4429 } 4430 } 4431 } 4432 4433 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4434 if (callingUid == Process.SHELL_UID) { 4435 if (userHandle >= 0 4436 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4437 throw new SecurityException("Shell does not have permission to access user " 4438 + userHandle); 4439 } else if (userHandle < 0) { 4440 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4441 + Debug.getCallers(3)); 4442 } 4443 } 4444 } 4445 4446 private BasePermission findPermissionTreeLP(String permName) { 4447 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4448 if (permName.startsWith(bp.name) && 4449 permName.length() > bp.name.length() && 4450 permName.charAt(bp.name.length()) == '.') { 4451 return bp; 4452 } 4453 } 4454 return null; 4455 } 4456 4457 private BasePermission checkPermissionTreeLP(String permName) { 4458 if (permName != null) { 4459 BasePermission bp = findPermissionTreeLP(permName); 4460 if (bp != null) { 4461 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4462 return bp; 4463 } 4464 throw new SecurityException("Calling uid " 4465 + Binder.getCallingUid() 4466 + " is not allowed to add to permission tree " 4467 + bp.name + " owned by uid " + bp.uid); 4468 } 4469 } 4470 throw new SecurityException("No permission tree found for " + permName); 4471 } 4472 4473 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4474 if (s1 == null) { 4475 return s2 == null; 4476 } 4477 if (s2 == null) { 4478 return false; 4479 } 4480 if (s1.getClass() != s2.getClass()) { 4481 return false; 4482 } 4483 return s1.equals(s2); 4484 } 4485 4486 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4487 if (pi1.icon != pi2.icon) return false; 4488 if (pi1.logo != pi2.logo) return false; 4489 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4490 if (!compareStrings(pi1.name, pi2.name)) return false; 4491 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4492 // We'll take care of setting this one. 4493 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4494 // These are not currently stored in settings. 4495 //if (!compareStrings(pi1.group, pi2.group)) return false; 4496 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4497 //if (pi1.labelRes != pi2.labelRes) return false; 4498 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4499 return true; 4500 } 4501 4502 int permissionInfoFootprint(PermissionInfo info) { 4503 int size = info.name.length(); 4504 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4505 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4506 return size; 4507 } 4508 4509 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4510 int size = 0; 4511 for (BasePermission perm : mSettings.mPermissions.values()) { 4512 if (perm.uid == tree.uid) { 4513 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4514 } 4515 } 4516 return size; 4517 } 4518 4519 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4520 // We calculate the max size of permissions defined by this uid and throw 4521 // if that plus the size of 'info' would exceed our stated maximum. 4522 if (tree.uid != Process.SYSTEM_UID) { 4523 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4524 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4525 throw new SecurityException("Permission tree size cap exceeded"); 4526 } 4527 } 4528 } 4529 4530 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4531 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4532 throw new SecurityException("Label must be specified in permission"); 4533 } 4534 BasePermission tree = checkPermissionTreeLP(info.name); 4535 BasePermission bp = mSettings.mPermissions.get(info.name); 4536 boolean added = bp == null; 4537 boolean changed = true; 4538 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4539 if (added) { 4540 enforcePermissionCapLocked(info, tree); 4541 bp = new BasePermission(info.name, tree.sourcePackage, 4542 BasePermission.TYPE_DYNAMIC); 4543 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4544 throw new SecurityException( 4545 "Not allowed to modify non-dynamic permission " 4546 + info.name); 4547 } else { 4548 if (bp.protectionLevel == fixedLevel 4549 && bp.perm.owner.equals(tree.perm.owner) 4550 && bp.uid == tree.uid 4551 && comparePermissionInfos(bp.perm.info, info)) { 4552 changed = false; 4553 } 4554 } 4555 bp.protectionLevel = fixedLevel; 4556 info = new PermissionInfo(info); 4557 info.protectionLevel = fixedLevel; 4558 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4559 bp.perm.info.packageName = tree.perm.info.packageName; 4560 bp.uid = tree.uid; 4561 if (added) { 4562 mSettings.mPermissions.put(info.name, bp); 4563 } 4564 if (changed) { 4565 if (!async) { 4566 mSettings.writeLPr(); 4567 } else { 4568 scheduleWriteSettingsLocked(); 4569 } 4570 } 4571 return added; 4572 } 4573 4574 @Override 4575 public boolean addPermission(PermissionInfo info) { 4576 synchronized (mPackages) { 4577 return addPermissionLocked(info, false); 4578 } 4579 } 4580 4581 @Override 4582 public boolean addPermissionAsync(PermissionInfo info) { 4583 synchronized (mPackages) { 4584 return addPermissionLocked(info, true); 4585 } 4586 } 4587 4588 @Override 4589 public void removePermission(String name) { 4590 synchronized (mPackages) { 4591 checkPermissionTreeLP(name); 4592 BasePermission bp = mSettings.mPermissions.get(name); 4593 if (bp != null) { 4594 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4595 throw new SecurityException( 4596 "Not allowed to modify non-dynamic permission " 4597 + name); 4598 } 4599 mSettings.mPermissions.remove(name); 4600 mSettings.writeLPr(); 4601 } 4602 } 4603 } 4604 4605 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4606 BasePermission bp) { 4607 int index = pkg.requestedPermissions.indexOf(bp.name); 4608 if (index == -1) { 4609 throw new SecurityException("Package " + pkg.packageName 4610 + " has not requested permission " + bp.name); 4611 } 4612 if (!bp.isRuntime() && !bp.isDevelopment()) { 4613 throw new SecurityException("Permission " + bp.name 4614 + " is not a changeable permission type"); 4615 } 4616 } 4617 4618 @Override 4619 public void grantRuntimePermission(String packageName, String name, final int userId) { 4620 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4621 } 4622 4623 private void grantRuntimePermission(String packageName, String name, final int userId, 4624 boolean overridePolicy) { 4625 if (!sUserManager.exists(userId)) { 4626 Log.e(TAG, "No such user:" + userId); 4627 return; 4628 } 4629 4630 mContext.enforceCallingOrSelfPermission( 4631 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4632 "grantRuntimePermission"); 4633 4634 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4635 true /* requireFullPermission */, true /* checkShell */, 4636 "grantRuntimePermission"); 4637 4638 final int uid; 4639 final SettingBase sb; 4640 4641 synchronized (mPackages) { 4642 final PackageParser.Package pkg = mPackages.get(packageName); 4643 if (pkg == null) { 4644 throw new IllegalArgumentException("Unknown package: " + packageName); 4645 } 4646 4647 final BasePermission bp = mSettings.mPermissions.get(name); 4648 if (bp == null) { 4649 throw new IllegalArgumentException("Unknown permission: " + name); 4650 } 4651 4652 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4653 4654 // If a permission review is required for legacy apps we represent 4655 // their permissions as always granted runtime ones since we need 4656 // to keep the review required permission flag per user while an 4657 // install permission's state is shared across all users. 4658 if (mPermissionReviewRequired 4659 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4660 && bp.isRuntime()) { 4661 return; 4662 } 4663 4664 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4665 sb = (SettingBase) pkg.mExtras; 4666 if (sb == null) { 4667 throw new IllegalArgumentException("Unknown package: " + packageName); 4668 } 4669 4670 final PermissionsState permissionsState = sb.getPermissionsState(); 4671 4672 final int flags = permissionsState.getPermissionFlags(name, userId); 4673 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4674 throw new SecurityException("Cannot grant system fixed permission " 4675 + name + " for package " + packageName); 4676 } 4677 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4678 throw new SecurityException("Cannot grant policy fixed permission " 4679 + name + " for package " + packageName); 4680 } 4681 4682 if (bp.isDevelopment()) { 4683 // Development permissions must be handled specially, since they are not 4684 // normal runtime permissions. For now they apply to all users. 4685 if (permissionsState.grantInstallPermission(bp) != 4686 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4687 scheduleWriteSettingsLocked(); 4688 } 4689 return; 4690 } 4691 4692 final PackageSetting ps = mSettings.mPackages.get(packageName); 4693 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4694 throw new SecurityException("Cannot grant non-ephemeral permission" 4695 + name + " for package " + packageName); 4696 } 4697 4698 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4699 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4700 return; 4701 } 4702 4703 final int result = permissionsState.grantRuntimePermission(bp, userId); 4704 switch (result) { 4705 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4706 return; 4707 } 4708 4709 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4710 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4711 mHandler.post(new Runnable() { 4712 @Override 4713 public void run() { 4714 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4715 } 4716 }); 4717 } 4718 break; 4719 } 4720 4721 if (bp.isRuntime()) { 4722 logPermissionGranted(mContext, name, packageName); 4723 } 4724 4725 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4726 4727 // Not critical if that is lost - app has to request again. 4728 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4729 } 4730 4731 // Only need to do this if user is initialized. Otherwise it's a new user 4732 // and there are no processes running as the user yet and there's no need 4733 // to make an expensive call to remount processes for the changed permissions. 4734 if (READ_EXTERNAL_STORAGE.equals(name) 4735 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4736 final long token = Binder.clearCallingIdentity(); 4737 try { 4738 if (sUserManager.isInitialized(userId)) { 4739 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4740 StorageManagerInternal.class); 4741 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4742 } 4743 } finally { 4744 Binder.restoreCallingIdentity(token); 4745 } 4746 } 4747 } 4748 4749 @Override 4750 public void revokeRuntimePermission(String packageName, String name, int userId) { 4751 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4752 } 4753 4754 private void revokeRuntimePermission(String packageName, String name, int userId, 4755 boolean overridePolicy) { 4756 if (!sUserManager.exists(userId)) { 4757 Log.e(TAG, "No such user:" + userId); 4758 return; 4759 } 4760 4761 mContext.enforceCallingOrSelfPermission( 4762 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4763 "revokeRuntimePermission"); 4764 4765 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4766 true /* requireFullPermission */, true /* checkShell */, 4767 "revokeRuntimePermission"); 4768 4769 final int appId; 4770 4771 synchronized (mPackages) { 4772 final PackageParser.Package pkg = mPackages.get(packageName); 4773 if (pkg == null) { 4774 throw new IllegalArgumentException("Unknown package: " + packageName); 4775 } 4776 4777 final BasePermission bp = mSettings.mPermissions.get(name); 4778 if (bp == null) { 4779 throw new IllegalArgumentException("Unknown permission: " + name); 4780 } 4781 4782 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4783 4784 // If a permission review is required for legacy apps we represent 4785 // their permissions as always granted runtime ones since we need 4786 // to keep the review required permission flag per user while an 4787 // install permission's state is shared across all users. 4788 if (mPermissionReviewRequired 4789 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4790 && bp.isRuntime()) { 4791 return; 4792 } 4793 4794 SettingBase sb = (SettingBase) pkg.mExtras; 4795 if (sb == null) { 4796 throw new IllegalArgumentException("Unknown package: " + packageName); 4797 } 4798 4799 final PermissionsState permissionsState = sb.getPermissionsState(); 4800 4801 final int flags = permissionsState.getPermissionFlags(name, userId); 4802 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4803 throw new SecurityException("Cannot revoke system fixed permission " 4804 + name + " for package " + packageName); 4805 } 4806 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4807 throw new SecurityException("Cannot revoke policy fixed permission " 4808 + name + " for package " + packageName); 4809 } 4810 4811 if (bp.isDevelopment()) { 4812 // Development permissions must be handled specially, since they are not 4813 // normal runtime permissions. For now they apply to all users. 4814 if (permissionsState.revokeInstallPermission(bp) != 4815 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4816 scheduleWriteSettingsLocked(); 4817 } 4818 return; 4819 } 4820 4821 if (permissionsState.revokeRuntimePermission(bp, userId) == 4822 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4823 return; 4824 } 4825 4826 if (bp.isRuntime()) { 4827 logPermissionRevoked(mContext, name, packageName); 4828 } 4829 4830 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4831 4832 // Critical, after this call app should never have the permission. 4833 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4834 4835 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4836 } 4837 4838 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4839 } 4840 4841 /** 4842 * Get the first event id for the permission. 4843 * 4844 * <p>There are four events for each permission: <ul> 4845 * <li>Request permission: first id + 0</li> 4846 * <li>Grant permission: first id + 1</li> 4847 * <li>Request for permission denied: first id + 2</li> 4848 * <li>Revoke permission: first id + 3</li> 4849 * </ul></p> 4850 * 4851 * @param name name of the permission 4852 * 4853 * @return The first event id for the permission 4854 */ 4855 private static int getBaseEventId(@NonNull String name) { 4856 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4857 4858 if (eventIdIndex == -1) { 4859 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4860 || "user".equals(Build.TYPE)) { 4861 Log.i(TAG, "Unknown permission " + name); 4862 4863 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4864 } else { 4865 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4866 // 4867 // Also update 4868 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4869 // - metrics_constants.proto 4870 throw new IllegalStateException("Unknown permission " + name); 4871 } 4872 } 4873 4874 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4875 } 4876 4877 /** 4878 * Log that a permission was revoked. 4879 * 4880 * @param context Context of the caller 4881 * @param name name of the permission 4882 * @param packageName package permission if for 4883 */ 4884 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4885 @NonNull String packageName) { 4886 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4887 } 4888 4889 /** 4890 * Log that a permission request was granted. 4891 * 4892 * @param context Context of the caller 4893 * @param name name of the permission 4894 * @param packageName package permission if for 4895 */ 4896 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4897 @NonNull String packageName) { 4898 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4899 } 4900 4901 @Override 4902 public void resetRuntimePermissions() { 4903 mContext.enforceCallingOrSelfPermission( 4904 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4905 "revokeRuntimePermission"); 4906 4907 int callingUid = Binder.getCallingUid(); 4908 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4909 mContext.enforceCallingOrSelfPermission( 4910 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4911 "resetRuntimePermissions"); 4912 } 4913 4914 synchronized (mPackages) { 4915 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4916 for (int userId : UserManagerService.getInstance().getUserIds()) { 4917 final int packageCount = mPackages.size(); 4918 for (int i = 0; i < packageCount; i++) { 4919 PackageParser.Package pkg = mPackages.valueAt(i); 4920 if (!(pkg.mExtras instanceof PackageSetting)) { 4921 continue; 4922 } 4923 PackageSetting ps = (PackageSetting) pkg.mExtras; 4924 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4925 } 4926 } 4927 } 4928 } 4929 4930 @Override 4931 public int getPermissionFlags(String name, String packageName, int userId) { 4932 if (!sUserManager.exists(userId)) { 4933 return 0; 4934 } 4935 4936 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4937 4938 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4939 true /* requireFullPermission */, false /* checkShell */, 4940 "getPermissionFlags"); 4941 4942 synchronized (mPackages) { 4943 final PackageParser.Package pkg = mPackages.get(packageName); 4944 if (pkg == null) { 4945 return 0; 4946 } 4947 4948 final BasePermission bp = mSettings.mPermissions.get(name); 4949 if (bp == null) { 4950 return 0; 4951 } 4952 4953 SettingBase sb = (SettingBase) pkg.mExtras; 4954 if (sb == null) { 4955 return 0; 4956 } 4957 4958 PermissionsState permissionsState = sb.getPermissionsState(); 4959 return permissionsState.getPermissionFlags(name, userId); 4960 } 4961 } 4962 4963 @Override 4964 public void updatePermissionFlags(String name, String packageName, int flagMask, 4965 int flagValues, int userId) { 4966 if (!sUserManager.exists(userId)) { 4967 return; 4968 } 4969 4970 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4971 4972 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4973 true /* requireFullPermission */, true /* checkShell */, 4974 "updatePermissionFlags"); 4975 4976 // Only the system can change these flags and nothing else. 4977 if (getCallingUid() != Process.SYSTEM_UID) { 4978 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4979 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4980 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4981 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4982 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4983 } 4984 4985 synchronized (mPackages) { 4986 final PackageParser.Package pkg = mPackages.get(packageName); 4987 if (pkg == null) { 4988 throw new IllegalArgumentException("Unknown package: " + packageName); 4989 } 4990 4991 final BasePermission bp = mSettings.mPermissions.get(name); 4992 if (bp == null) { 4993 throw new IllegalArgumentException("Unknown permission: " + name); 4994 } 4995 4996 SettingBase sb = (SettingBase) pkg.mExtras; 4997 if (sb == null) { 4998 throw new IllegalArgumentException("Unknown package: " + packageName); 4999 } 5000 5001 PermissionsState permissionsState = sb.getPermissionsState(); 5002 5003 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5004 5005 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5006 // Install and runtime permissions are stored in different places, 5007 // so figure out what permission changed and persist the change. 5008 if (permissionsState.getInstallPermissionState(name) != null) { 5009 scheduleWriteSettingsLocked(); 5010 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5011 || hadState) { 5012 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5013 } 5014 } 5015 } 5016 } 5017 5018 /** 5019 * Update the permission flags for all packages and runtime permissions of a user in order 5020 * to allow device or profile owner to remove POLICY_FIXED. 5021 */ 5022 @Override 5023 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5024 if (!sUserManager.exists(userId)) { 5025 return; 5026 } 5027 5028 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5029 5030 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5031 true /* requireFullPermission */, true /* checkShell */, 5032 "updatePermissionFlagsForAllApps"); 5033 5034 // Only the system can change system fixed flags. 5035 if (getCallingUid() != Process.SYSTEM_UID) { 5036 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5037 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5038 } 5039 5040 synchronized (mPackages) { 5041 boolean changed = false; 5042 final int packageCount = mPackages.size(); 5043 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5044 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5045 SettingBase sb = (SettingBase) pkg.mExtras; 5046 if (sb == null) { 5047 continue; 5048 } 5049 PermissionsState permissionsState = sb.getPermissionsState(); 5050 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5051 userId, flagMask, flagValues); 5052 } 5053 if (changed) { 5054 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5055 } 5056 } 5057 } 5058 5059 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5060 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5061 != PackageManager.PERMISSION_GRANTED 5062 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5063 != PackageManager.PERMISSION_GRANTED) { 5064 throw new SecurityException(message + " requires " 5065 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5066 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5067 } 5068 } 5069 5070 @Override 5071 public boolean shouldShowRequestPermissionRationale(String permissionName, 5072 String packageName, int userId) { 5073 if (UserHandle.getCallingUserId() != userId) { 5074 mContext.enforceCallingPermission( 5075 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5076 "canShowRequestPermissionRationale for user " + userId); 5077 } 5078 5079 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5080 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5081 return false; 5082 } 5083 5084 if (checkPermission(permissionName, packageName, userId) 5085 == PackageManager.PERMISSION_GRANTED) { 5086 return false; 5087 } 5088 5089 final int flags; 5090 5091 final long identity = Binder.clearCallingIdentity(); 5092 try { 5093 flags = getPermissionFlags(permissionName, 5094 packageName, userId); 5095 } finally { 5096 Binder.restoreCallingIdentity(identity); 5097 } 5098 5099 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5100 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5101 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5102 5103 if ((flags & fixedFlags) != 0) { 5104 return false; 5105 } 5106 5107 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5108 } 5109 5110 @Override 5111 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5112 mContext.enforceCallingOrSelfPermission( 5113 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5114 "addOnPermissionsChangeListener"); 5115 5116 synchronized (mPackages) { 5117 mOnPermissionChangeListeners.addListenerLocked(listener); 5118 } 5119 } 5120 5121 @Override 5122 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5123 synchronized (mPackages) { 5124 mOnPermissionChangeListeners.removeListenerLocked(listener); 5125 } 5126 } 5127 5128 @Override 5129 public boolean isProtectedBroadcast(String actionName) { 5130 synchronized (mPackages) { 5131 if (mProtectedBroadcasts.contains(actionName)) { 5132 return true; 5133 } else if (actionName != null) { 5134 // TODO: remove these terrible hacks 5135 if (actionName.startsWith("android.net.netmon.lingerExpired") 5136 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5137 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5138 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5139 return true; 5140 } 5141 } 5142 } 5143 return false; 5144 } 5145 5146 @Override 5147 public int checkSignatures(String pkg1, String pkg2) { 5148 synchronized (mPackages) { 5149 final PackageParser.Package p1 = mPackages.get(pkg1); 5150 final PackageParser.Package p2 = mPackages.get(pkg2); 5151 if (p1 == null || p1.mExtras == null 5152 || p2 == null || p2.mExtras == null) { 5153 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5154 } 5155 return compareSignatures(p1.mSignatures, p2.mSignatures); 5156 } 5157 } 5158 5159 @Override 5160 public int checkUidSignatures(int uid1, int uid2) { 5161 // Map to base uids. 5162 uid1 = UserHandle.getAppId(uid1); 5163 uid2 = UserHandle.getAppId(uid2); 5164 // reader 5165 synchronized (mPackages) { 5166 Signature[] s1; 5167 Signature[] s2; 5168 Object obj = mSettings.getUserIdLPr(uid1); 5169 if (obj != null) { 5170 if (obj instanceof SharedUserSetting) { 5171 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5172 } else if (obj instanceof PackageSetting) { 5173 s1 = ((PackageSetting)obj).signatures.mSignatures; 5174 } else { 5175 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5176 } 5177 } else { 5178 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5179 } 5180 obj = mSettings.getUserIdLPr(uid2); 5181 if (obj != null) { 5182 if (obj instanceof SharedUserSetting) { 5183 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5184 } else if (obj instanceof PackageSetting) { 5185 s2 = ((PackageSetting)obj).signatures.mSignatures; 5186 } else { 5187 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5188 } 5189 } else { 5190 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5191 } 5192 return compareSignatures(s1, s2); 5193 } 5194 } 5195 5196 /** 5197 * This method should typically only be used when granting or revoking 5198 * permissions, since the app may immediately restart after this call. 5199 * <p> 5200 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5201 * guard your work against the app being relaunched. 5202 */ 5203 private void killUid(int appId, int userId, String reason) { 5204 final long identity = Binder.clearCallingIdentity(); 5205 try { 5206 IActivityManager am = ActivityManager.getService(); 5207 if (am != null) { 5208 try { 5209 am.killUid(appId, userId, reason); 5210 } catch (RemoteException e) { 5211 /* ignore - same process */ 5212 } 5213 } 5214 } finally { 5215 Binder.restoreCallingIdentity(identity); 5216 } 5217 } 5218 5219 /** 5220 * Compares two sets of signatures. Returns: 5221 * <br /> 5222 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5223 * <br /> 5224 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5225 * <br /> 5226 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5227 * <br /> 5228 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5229 * <br /> 5230 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5231 */ 5232 static int compareSignatures(Signature[] s1, Signature[] s2) { 5233 if (s1 == null) { 5234 return s2 == null 5235 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5236 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5237 } 5238 5239 if (s2 == null) { 5240 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5241 } 5242 5243 if (s1.length != s2.length) { 5244 return PackageManager.SIGNATURE_NO_MATCH; 5245 } 5246 5247 // Since both signature sets are of size 1, we can compare without HashSets. 5248 if (s1.length == 1) { 5249 return s1[0].equals(s2[0]) ? 5250 PackageManager.SIGNATURE_MATCH : 5251 PackageManager.SIGNATURE_NO_MATCH; 5252 } 5253 5254 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5255 for (Signature sig : s1) { 5256 set1.add(sig); 5257 } 5258 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5259 for (Signature sig : s2) { 5260 set2.add(sig); 5261 } 5262 // Make sure s2 contains all signatures in s1. 5263 if (set1.equals(set2)) { 5264 return PackageManager.SIGNATURE_MATCH; 5265 } 5266 return PackageManager.SIGNATURE_NO_MATCH; 5267 } 5268 5269 /** 5270 * If the database version for this type of package (internal storage or 5271 * external storage) is less than the version where package signatures 5272 * were updated, return true. 5273 */ 5274 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5275 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5276 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5277 } 5278 5279 /** 5280 * Used for backward compatibility to make sure any packages with 5281 * certificate chains get upgraded to the new style. {@code existingSigs} 5282 * will be in the old format (since they were stored on disk from before the 5283 * system upgrade) and {@code scannedSigs} will be in the newer format. 5284 */ 5285 private int compareSignaturesCompat(PackageSignatures existingSigs, 5286 PackageParser.Package scannedPkg) { 5287 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5288 return PackageManager.SIGNATURE_NO_MATCH; 5289 } 5290 5291 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5292 for (Signature sig : existingSigs.mSignatures) { 5293 existingSet.add(sig); 5294 } 5295 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5296 for (Signature sig : scannedPkg.mSignatures) { 5297 try { 5298 Signature[] chainSignatures = sig.getChainSignatures(); 5299 for (Signature chainSig : chainSignatures) { 5300 scannedCompatSet.add(chainSig); 5301 } 5302 } catch (CertificateEncodingException e) { 5303 scannedCompatSet.add(sig); 5304 } 5305 } 5306 /* 5307 * Make sure the expanded scanned set contains all signatures in the 5308 * existing one. 5309 */ 5310 if (scannedCompatSet.equals(existingSet)) { 5311 // Migrate the old signatures to the new scheme. 5312 existingSigs.assignSignatures(scannedPkg.mSignatures); 5313 // The new KeySets will be re-added later in the scanning process. 5314 synchronized (mPackages) { 5315 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5316 } 5317 return PackageManager.SIGNATURE_MATCH; 5318 } 5319 return PackageManager.SIGNATURE_NO_MATCH; 5320 } 5321 5322 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5323 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5324 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5325 } 5326 5327 private int compareSignaturesRecover(PackageSignatures existingSigs, 5328 PackageParser.Package scannedPkg) { 5329 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5330 return PackageManager.SIGNATURE_NO_MATCH; 5331 } 5332 5333 String msg = null; 5334 try { 5335 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5336 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5337 + scannedPkg.packageName); 5338 return PackageManager.SIGNATURE_MATCH; 5339 } 5340 } catch (CertificateException e) { 5341 msg = e.getMessage(); 5342 } 5343 5344 logCriticalInfo(Log.INFO, 5345 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5346 return PackageManager.SIGNATURE_NO_MATCH; 5347 } 5348 5349 @Override 5350 public List<String> getAllPackages() { 5351 synchronized (mPackages) { 5352 return new ArrayList<String>(mPackages.keySet()); 5353 } 5354 } 5355 5356 @Override 5357 public String[] getPackagesForUid(int uid) { 5358 final int userId = UserHandle.getUserId(uid); 5359 uid = UserHandle.getAppId(uid); 5360 // reader 5361 synchronized (mPackages) { 5362 Object obj = mSettings.getUserIdLPr(uid); 5363 if (obj instanceof SharedUserSetting) { 5364 final SharedUserSetting sus = (SharedUserSetting) obj; 5365 final int N = sus.packages.size(); 5366 String[] res = new String[N]; 5367 final Iterator<PackageSetting> it = sus.packages.iterator(); 5368 int i = 0; 5369 while (it.hasNext()) { 5370 PackageSetting ps = it.next(); 5371 if (ps.getInstalled(userId)) { 5372 res[i++] = ps.name; 5373 } else { 5374 res = ArrayUtils.removeElement(String.class, res, res[i]); 5375 } 5376 } 5377 return res; 5378 } else if (obj instanceof PackageSetting) { 5379 final PackageSetting ps = (PackageSetting) obj; 5380 if (ps.getInstalled(userId)) { 5381 return new String[]{ps.name}; 5382 } 5383 } 5384 } 5385 return null; 5386 } 5387 5388 @Override 5389 public String getNameForUid(int uid) { 5390 // reader 5391 synchronized (mPackages) { 5392 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5393 if (obj instanceof SharedUserSetting) { 5394 final SharedUserSetting sus = (SharedUserSetting) obj; 5395 return sus.name + ":" + sus.userId; 5396 } else if (obj instanceof PackageSetting) { 5397 final PackageSetting ps = (PackageSetting) obj; 5398 return ps.name; 5399 } 5400 } 5401 return null; 5402 } 5403 5404 @Override 5405 public int getUidForSharedUser(String sharedUserName) { 5406 if(sharedUserName == null) { 5407 return -1; 5408 } 5409 // reader 5410 synchronized (mPackages) { 5411 SharedUserSetting suid; 5412 try { 5413 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5414 if (suid != null) { 5415 return suid.userId; 5416 } 5417 } catch (PackageManagerException ignore) { 5418 // can't happen, but, still need to catch it 5419 } 5420 return -1; 5421 } 5422 } 5423 5424 @Override 5425 public int getFlagsForUid(int uid) { 5426 synchronized (mPackages) { 5427 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5428 if (obj instanceof SharedUserSetting) { 5429 final SharedUserSetting sus = (SharedUserSetting) obj; 5430 return sus.pkgFlags; 5431 } else if (obj instanceof PackageSetting) { 5432 final PackageSetting ps = (PackageSetting) obj; 5433 return ps.pkgFlags; 5434 } 5435 } 5436 return 0; 5437 } 5438 5439 @Override 5440 public int getPrivateFlagsForUid(int uid) { 5441 synchronized (mPackages) { 5442 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5443 if (obj instanceof SharedUserSetting) { 5444 final SharedUserSetting sus = (SharedUserSetting) obj; 5445 return sus.pkgPrivateFlags; 5446 } else if (obj instanceof PackageSetting) { 5447 final PackageSetting ps = (PackageSetting) obj; 5448 return ps.pkgPrivateFlags; 5449 } 5450 } 5451 return 0; 5452 } 5453 5454 @Override 5455 public boolean isUidPrivileged(int uid) { 5456 uid = UserHandle.getAppId(uid); 5457 // reader 5458 synchronized (mPackages) { 5459 Object obj = mSettings.getUserIdLPr(uid); 5460 if (obj instanceof SharedUserSetting) { 5461 final SharedUserSetting sus = (SharedUserSetting) obj; 5462 final Iterator<PackageSetting> it = sus.packages.iterator(); 5463 while (it.hasNext()) { 5464 if (it.next().isPrivileged()) { 5465 return true; 5466 } 5467 } 5468 } else if (obj instanceof PackageSetting) { 5469 final PackageSetting ps = (PackageSetting) obj; 5470 return ps.isPrivileged(); 5471 } 5472 } 5473 return false; 5474 } 5475 5476 @Override 5477 public String[] getAppOpPermissionPackages(String permissionName) { 5478 synchronized (mPackages) { 5479 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5480 if (pkgs == null) { 5481 return null; 5482 } 5483 return pkgs.toArray(new String[pkgs.size()]); 5484 } 5485 } 5486 5487 @Override 5488 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5489 int flags, int userId) { 5490 try { 5491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5492 5493 if (!sUserManager.exists(userId)) return null; 5494 flags = updateFlagsForResolve(flags, userId, intent); 5495 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5496 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5497 5498 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5499 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5500 flags, userId); 5501 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5502 5503 final ResolveInfo bestChoice = 5504 chooseBestActivity(intent, resolvedType, flags, query, userId); 5505 return bestChoice; 5506 } finally { 5507 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5508 } 5509 } 5510 5511 @Override 5512 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5513 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5514 throw new SecurityException( 5515 "findPersistentPreferredActivity can only be run by the system"); 5516 } 5517 if (!sUserManager.exists(userId)) { 5518 return null; 5519 } 5520 intent = updateIntentForResolve(intent); 5521 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5522 final int flags = updateFlagsForResolve(0, userId, intent); 5523 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5524 userId); 5525 synchronized (mPackages) { 5526 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5527 userId); 5528 } 5529 } 5530 5531 @Override 5532 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5533 IntentFilter filter, int match, ComponentName activity) { 5534 final int userId = UserHandle.getCallingUserId(); 5535 if (DEBUG_PREFERRED) { 5536 Log.v(TAG, "setLastChosenActivity intent=" + intent 5537 + " resolvedType=" + resolvedType 5538 + " flags=" + flags 5539 + " filter=" + filter 5540 + " match=" + match 5541 + " activity=" + activity); 5542 filter.dump(new PrintStreamPrinter(System.out), " "); 5543 } 5544 intent.setComponent(null); 5545 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5546 userId); 5547 // Find any earlier preferred or last chosen entries and nuke them 5548 findPreferredActivity(intent, resolvedType, 5549 flags, query, 0, false, true, false, userId); 5550 // Add the new activity as the last chosen for this filter 5551 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5552 "Setting last chosen"); 5553 } 5554 5555 @Override 5556 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5557 final int userId = UserHandle.getCallingUserId(); 5558 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5559 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5560 userId); 5561 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5562 false, false, false, userId); 5563 } 5564 5565 private boolean isEphemeralDisabled() { 5566 // ephemeral apps have been disabled across the board 5567 if (DISABLE_EPHEMERAL_APPS) { 5568 return true; 5569 } 5570 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5571 if (!mSystemReady) { 5572 return true; 5573 } 5574 // we can't get a content resolver until the system is ready; these checks must happen last 5575 final ContentResolver resolver = mContext.getContentResolver(); 5576 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5577 return true; 5578 } 5579 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5580 } 5581 5582 private boolean isEphemeralAllowed( 5583 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5584 boolean skipPackageCheck) { 5585 // Short circuit and return early if possible. 5586 if (isEphemeralDisabled()) { 5587 return false; 5588 } 5589 final int callingUser = UserHandle.getCallingUserId(); 5590 if (callingUser != UserHandle.USER_SYSTEM) { 5591 return false; 5592 } 5593 if (mEphemeralResolverConnection == null) { 5594 return false; 5595 } 5596 if (mEphemeralInstallerComponent == null) { 5597 return false; 5598 } 5599 if (intent.getComponent() != null) { 5600 return false; 5601 } 5602 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5603 return false; 5604 } 5605 if (!skipPackageCheck && intent.getPackage() != null) { 5606 return false; 5607 } 5608 final boolean isWebUri = hasWebURI(intent); 5609 if (!isWebUri || intent.getData().getHost() == null) { 5610 return false; 5611 } 5612 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5613 synchronized (mPackages) { 5614 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5615 for (int n = 0; n < count; n++) { 5616 ResolveInfo info = resolvedActivities.get(n); 5617 String packageName = info.activityInfo.packageName; 5618 PackageSetting ps = mSettings.mPackages.get(packageName); 5619 if (ps != null) { 5620 // Try to get the status from User settings first 5621 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5622 int status = (int) (packedStatus >> 32); 5623 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5624 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5625 if (DEBUG_EPHEMERAL) { 5626 Slog.v(TAG, "DENY ephemeral apps;" 5627 + " pkg: " + packageName + ", status: " + status); 5628 } 5629 return false; 5630 } 5631 } 5632 } 5633 } 5634 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5635 return true; 5636 } 5637 5638 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5639 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5640 int userId) { 5641 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5642 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5643 callingPackage, userId)); 5644 mHandler.sendMessage(msg); 5645 } 5646 5647 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5648 int flags, List<ResolveInfo> query, int userId) { 5649 if (query != null) { 5650 final int N = query.size(); 5651 if (N == 1) { 5652 return query.get(0); 5653 } else if (N > 1) { 5654 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5655 // If there is more than one activity with the same priority, 5656 // then let the user decide between them. 5657 ResolveInfo r0 = query.get(0); 5658 ResolveInfo r1 = query.get(1); 5659 if (DEBUG_INTENT_MATCHING || debug) { 5660 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5661 + r1.activityInfo.name + "=" + r1.priority); 5662 } 5663 // If the first activity has a higher priority, or a different 5664 // default, then it is always desirable to pick it. 5665 if (r0.priority != r1.priority 5666 || r0.preferredOrder != r1.preferredOrder 5667 || r0.isDefault != r1.isDefault) { 5668 return query.get(0); 5669 } 5670 // If we have saved a preference for a preferred activity for 5671 // this Intent, use that. 5672 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5673 flags, query, r0.priority, true, false, debug, userId); 5674 if (ri != null) { 5675 return ri; 5676 } 5677 ri = new ResolveInfo(mResolveInfo); 5678 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5679 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5680 // If all of the options come from the same package, show the application's 5681 // label and icon instead of the generic resolver's. 5682 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5683 // and then throw away the ResolveInfo itself, meaning that the caller loses 5684 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5685 // a fallback for this case; we only set the target package's resources on 5686 // the ResolveInfo, not the ActivityInfo. 5687 final String intentPackage = intent.getPackage(); 5688 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5689 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5690 ri.resolvePackageName = intentPackage; 5691 if (userNeedsBadging(userId)) { 5692 ri.noResourceId = true; 5693 } else { 5694 ri.icon = appi.icon; 5695 } 5696 ri.iconResourceId = appi.icon; 5697 ri.labelRes = appi.labelRes; 5698 } 5699 ri.activityInfo.applicationInfo = new ApplicationInfo( 5700 ri.activityInfo.applicationInfo); 5701 if (userId != 0) { 5702 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5703 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5704 } 5705 // Make sure that the resolver is displayable in car mode 5706 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5707 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5708 return ri; 5709 } 5710 } 5711 return null; 5712 } 5713 5714 /** 5715 * Return true if the given list is not empty and all of its contents have 5716 * an activityInfo with the given package name. 5717 */ 5718 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5719 if (ArrayUtils.isEmpty(list)) { 5720 return false; 5721 } 5722 for (int i = 0, N = list.size(); i < N; i++) { 5723 final ResolveInfo ri = list.get(i); 5724 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5725 if (ai == null || !packageName.equals(ai.packageName)) { 5726 return false; 5727 } 5728 } 5729 return true; 5730 } 5731 5732 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5733 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5734 final int N = query.size(); 5735 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5736 .get(userId); 5737 // Get the list of persistent preferred activities that handle the intent 5738 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5739 List<PersistentPreferredActivity> pprefs = ppir != null 5740 ? ppir.queryIntent(intent, resolvedType, 5741 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5742 userId) 5743 : null; 5744 if (pprefs != null && pprefs.size() > 0) { 5745 final int M = pprefs.size(); 5746 for (int i=0; i<M; i++) { 5747 final PersistentPreferredActivity ppa = pprefs.get(i); 5748 if (DEBUG_PREFERRED || debug) { 5749 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5750 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5751 + "\n component=" + ppa.mComponent); 5752 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5753 } 5754 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5755 flags | MATCH_DISABLED_COMPONENTS, userId); 5756 if (DEBUG_PREFERRED || debug) { 5757 Slog.v(TAG, "Found persistent preferred activity:"); 5758 if (ai != null) { 5759 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5760 } else { 5761 Slog.v(TAG, " null"); 5762 } 5763 } 5764 if (ai == null) { 5765 // This previously registered persistent preferred activity 5766 // component is no longer known. Ignore it and do NOT remove it. 5767 continue; 5768 } 5769 for (int j=0; j<N; j++) { 5770 final ResolveInfo ri = query.get(j); 5771 if (!ri.activityInfo.applicationInfo.packageName 5772 .equals(ai.applicationInfo.packageName)) { 5773 continue; 5774 } 5775 if (!ri.activityInfo.name.equals(ai.name)) { 5776 continue; 5777 } 5778 // Found a persistent preference that can handle the intent. 5779 if (DEBUG_PREFERRED || debug) { 5780 Slog.v(TAG, "Returning persistent preferred activity: " + 5781 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5782 } 5783 return ri; 5784 } 5785 } 5786 } 5787 return null; 5788 } 5789 5790 // TODO: handle preferred activities missing while user has amnesia 5791 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5792 List<ResolveInfo> query, int priority, boolean always, 5793 boolean removeMatches, boolean debug, int userId) { 5794 if (!sUserManager.exists(userId)) return null; 5795 flags = updateFlagsForResolve(flags, userId, intent); 5796 intent = updateIntentForResolve(intent); 5797 // writer 5798 synchronized (mPackages) { 5799 // Try to find a matching persistent preferred activity. 5800 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5801 debug, userId); 5802 5803 // If a persistent preferred activity matched, use it. 5804 if (pri != null) { 5805 return pri; 5806 } 5807 5808 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5809 // Get the list of preferred activities that handle the intent 5810 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5811 List<PreferredActivity> prefs = pir != null 5812 ? pir.queryIntent(intent, resolvedType, 5813 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5814 userId) 5815 : null; 5816 if (prefs != null && prefs.size() > 0) { 5817 boolean changed = false; 5818 try { 5819 // First figure out how good the original match set is. 5820 // We will only allow preferred activities that came 5821 // from the same match quality. 5822 int match = 0; 5823 5824 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5825 5826 final int N = query.size(); 5827 for (int j=0; j<N; j++) { 5828 final ResolveInfo ri = query.get(j); 5829 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5830 + ": 0x" + Integer.toHexString(match)); 5831 if (ri.match > match) { 5832 match = ri.match; 5833 } 5834 } 5835 5836 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5837 + Integer.toHexString(match)); 5838 5839 match &= IntentFilter.MATCH_CATEGORY_MASK; 5840 final int M = prefs.size(); 5841 for (int i=0; i<M; i++) { 5842 final PreferredActivity pa = prefs.get(i); 5843 if (DEBUG_PREFERRED || debug) { 5844 Slog.v(TAG, "Checking PreferredActivity ds=" 5845 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5846 + "\n component=" + pa.mPref.mComponent); 5847 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5848 } 5849 if (pa.mPref.mMatch != match) { 5850 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5851 + Integer.toHexString(pa.mPref.mMatch)); 5852 continue; 5853 } 5854 // If it's not an "always" type preferred activity and that's what we're 5855 // looking for, skip it. 5856 if (always && !pa.mPref.mAlways) { 5857 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5858 continue; 5859 } 5860 final ActivityInfo ai = getActivityInfo( 5861 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5862 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5863 userId); 5864 if (DEBUG_PREFERRED || debug) { 5865 Slog.v(TAG, "Found preferred activity:"); 5866 if (ai != null) { 5867 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5868 } else { 5869 Slog.v(TAG, " null"); 5870 } 5871 } 5872 if (ai == null) { 5873 // This previously registered preferred activity 5874 // component is no longer known. Most likely an update 5875 // to the app was installed and in the new version this 5876 // component no longer exists. Clean it up by removing 5877 // it from the preferred activities list, and skip it. 5878 Slog.w(TAG, "Removing dangling preferred activity: " 5879 + pa.mPref.mComponent); 5880 pir.removeFilter(pa); 5881 changed = true; 5882 continue; 5883 } 5884 for (int j=0; j<N; j++) { 5885 final ResolveInfo ri = query.get(j); 5886 if (!ri.activityInfo.applicationInfo.packageName 5887 .equals(ai.applicationInfo.packageName)) { 5888 continue; 5889 } 5890 if (!ri.activityInfo.name.equals(ai.name)) { 5891 continue; 5892 } 5893 5894 if (removeMatches) { 5895 pir.removeFilter(pa); 5896 changed = true; 5897 if (DEBUG_PREFERRED) { 5898 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5899 } 5900 break; 5901 } 5902 5903 // Okay we found a previously set preferred or last chosen app. 5904 // If the result set is different from when this 5905 // was created, we need to clear it and re-ask the 5906 // user their preference, if we're looking for an "always" type entry. 5907 if (always && !pa.mPref.sameSet(query)) { 5908 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5909 + intent + " type " + resolvedType); 5910 if (DEBUG_PREFERRED) { 5911 Slog.v(TAG, "Removing preferred activity since set changed " 5912 + pa.mPref.mComponent); 5913 } 5914 pir.removeFilter(pa); 5915 // Re-add the filter as a "last chosen" entry (!always) 5916 PreferredActivity lastChosen = new PreferredActivity( 5917 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5918 pir.addFilter(lastChosen); 5919 changed = true; 5920 return null; 5921 } 5922 5923 // Yay! Either the set matched or we're looking for the last chosen 5924 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5925 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5926 return ri; 5927 } 5928 } 5929 } finally { 5930 if (changed) { 5931 if (DEBUG_PREFERRED) { 5932 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5933 } 5934 scheduleWritePackageRestrictionsLocked(userId); 5935 } 5936 } 5937 } 5938 } 5939 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5940 return null; 5941 } 5942 5943 /* 5944 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5945 */ 5946 @Override 5947 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5948 int targetUserId) { 5949 mContext.enforceCallingOrSelfPermission( 5950 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5951 List<CrossProfileIntentFilter> matches = 5952 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5953 if (matches != null) { 5954 int size = matches.size(); 5955 for (int i = 0; i < size; i++) { 5956 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5957 } 5958 } 5959 if (hasWebURI(intent)) { 5960 // cross-profile app linking works only towards the parent. 5961 final UserInfo parent = getProfileParent(sourceUserId); 5962 synchronized(mPackages) { 5963 int flags = updateFlagsForResolve(0, parent.id, intent); 5964 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5965 intent, resolvedType, flags, sourceUserId, parent.id); 5966 return xpDomainInfo != null; 5967 } 5968 } 5969 return false; 5970 } 5971 5972 private UserInfo getProfileParent(int userId) { 5973 final long identity = Binder.clearCallingIdentity(); 5974 try { 5975 return sUserManager.getProfileParent(userId); 5976 } finally { 5977 Binder.restoreCallingIdentity(identity); 5978 } 5979 } 5980 5981 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5982 String resolvedType, int userId) { 5983 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5984 if (resolver != null) { 5985 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 5986 } 5987 return null; 5988 } 5989 5990 @Override 5991 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5992 String resolvedType, int flags, int userId) { 5993 try { 5994 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5995 5996 return new ParceledListSlice<>( 5997 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5998 } finally { 5999 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6000 } 6001 } 6002 6003 /** 6004 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6005 * instant, returns {@code null}. 6006 */ 6007 private String getInstantAppPackageName(int callingUid) { 6008 final int appId = UserHandle.getAppId(callingUid); 6009 synchronized (mPackages) { 6010 final Object obj = mSettings.getUserIdLPr(appId); 6011 if (obj instanceof PackageSetting) { 6012 final PackageSetting ps = (PackageSetting) obj; 6013 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6014 return isInstantApp ? ps.pkg.packageName : null; 6015 } 6016 } 6017 return null; 6018 } 6019 6020 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6021 String resolvedType, int flags, int userId) { 6022 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6023 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6024 flags = updateFlagsForResolve(flags, userId, intent); 6025 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6026 false /* requireFullPermission */, false /* checkShell */, 6027 "query intent activities"); 6028 ComponentName comp = intent.getComponent(); 6029 if (comp == null) { 6030 if (intent.getSelector() != null) { 6031 intent = intent.getSelector(); 6032 comp = intent.getComponent(); 6033 } 6034 } 6035 6036 if (comp != null) { 6037 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6038 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6039 if (ai != null) { 6040 // When specifying an explicit component, we prevent the activity from being 6041 // used when either 1) the calling package is normal and the activity is within 6042 // an ephemeral application or 2) the calling package is ephemeral and the 6043 // activity is not visible to ephemeral applications. 6044 final boolean matchInstantApp = 6045 (flags & PackageManager.MATCH_INSTANT) != 0; 6046 final boolean matchVisibleToInstantAppOnly = 6047 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6048 final boolean isCallerInstantApp = 6049 instantAppPkgName != null; 6050 final boolean isTargetSameInstantApp = 6051 comp.getPackageName().equals(instantAppPkgName); 6052 final boolean isTargetInstantApp = 6053 (ai.applicationInfo.privateFlags 6054 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6055 final boolean isTargetHiddenFromInstantApp = 6056 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6057 final boolean blockResolution = 6058 !isTargetSameInstantApp 6059 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6060 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6061 && isTargetHiddenFromInstantApp)); 6062 if (!blockResolution) { 6063 final ResolveInfo ri = new ResolveInfo(); 6064 ri.activityInfo = ai; 6065 list.add(ri); 6066 } 6067 } 6068 return list; 6069 } 6070 6071 // reader 6072 boolean sortResult = false; 6073 boolean addEphemeral = false; 6074 List<ResolveInfo> result; 6075 final String pkgName = intent.getPackage(); 6076 synchronized (mPackages) { 6077 if (pkgName == null) { 6078 List<CrossProfileIntentFilter> matchingFilters = 6079 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6080 // Check for results that need to skip the current profile. 6081 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6082 resolvedType, flags, userId); 6083 if (xpResolveInfo != null) { 6084 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6085 xpResult.add(xpResolveInfo); 6086 return filterForEphemeral( 6087 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6088 } 6089 6090 // Check for results in the current profile. 6091 result = filterIfNotSystemUser(mActivities.queryIntent( 6092 intent, resolvedType, flags, userId), userId); 6093 addEphemeral = 6094 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6095 6096 // Check for cross profile results. 6097 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6098 xpResolveInfo = queryCrossProfileIntents( 6099 matchingFilters, intent, resolvedType, flags, userId, 6100 hasNonNegativePriorityResult); 6101 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6102 boolean isVisibleToUser = filterIfNotSystemUser( 6103 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6104 if (isVisibleToUser) { 6105 result.add(xpResolveInfo); 6106 sortResult = true; 6107 } 6108 } 6109 if (hasWebURI(intent)) { 6110 CrossProfileDomainInfo xpDomainInfo = null; 6111 final UserInfo parent = getProfileParent(userId); 6112 if (parent != null) { 6113 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6114 flags, userId, parent.id); 6115 } 6116 if (xpDomainInfo != null) { 6117 if (xpResolveInfo != null) { 6118 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6119 // in the result. 6120 result.remove(xpResolveInfo); 6121 } 6122 if (result.size() == 0 && !addEphemeral) { 6123 // No result in current profile, but found candidate in parent user. 6124 // And we are not going to add emphemeral app, so we can return the 6125 // result straight away. 6126 result.add(xpDomainInfo.resolveInfo); 6127 return filterForEphemeral(result, instantAppPkgName); 6128 } 6129 } else if (result.size() <= 1 && !addEphemeral) { 6130 // No result in parent user and <= 1 result in current profile, and we 6131 // are not going to add emphemeral app, so we can return the result without 6132 // further processing. 6133 return filterForEphemeral(result, instantAppPkgName); 6134 } 6135 // We have more than one candidate (combining results from current and parent 6136 // profile), so we need filtering and sorting. 6137 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6138 intent, flags, result, xpDomainInfo, userId); 6139 sortResult = true; 6140 } 6141 } else { 6142 final PackageParser.Package pkg = mPackages.get(pkgName); 6143 if (pkg != null) { 6144 result = filterForEphemeral(filterIfNotSystemUser( 6145 mActivities.queryIntentForPackage( 6146 intent, resolvedType, flags, pkg.activities, userId), 6147 userId), instantAppPkgName); 6148 } else { 6149 // the caller wants to resolve for a particular package; however, there 6150 // were no installed results, so, try to find an ephemeral result 6151 addEphemeral = isEphemeralAllowed( 6152 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6153 result = new ArrayList<ResolveInfo>(); 6154 } 6155 } 6156 } 6157 if (addEphemeral) { 6158 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6159 final EphemeralRequest requestObject = new EphemeralRequest( 6160 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6161 null /*launchIntent*/, null /*callingPackage*/, userId); 6162 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 6163 mContext, mEphemeralResolverConnection, requestObject); 6164 if (intentInfo != null) { 6165 if (DEBUG_EPHEMERAL) { 6166 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6167 } 6168 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 6169 ephemeralInstaller.ephemeralResponse = intentInfo; 6170 // make sure this resolver is the default 6171 ephemeralInstaller.isDefault = true; 6172 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6173 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6174 // add a non-generic filter 6175 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6176 ephemeralInstaller.filter.addDataPath( 6177 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6178 result.add(ephemeralInstaller); 6179 } 6180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6181 } 6182 if (sortResult) { 6183 Collections.sort(result, mResolvePrioritySorter); 6184 } 6185 return filterForEphemeral(result, instantAppPkgName); 6186 } 6187 6188 private static class CrossProfileDomainInfo { 6189 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6190 ResolveInfo resolveInfo; 6191 /* Best domain verification status of the activities found in the other profile */ 6192 int bestDomainVerificationStatus; 6193 } 6194 6195 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6196 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6197 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6198 sourceUserId)) { 6199 return null; 6200 } 6201 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6202 resolvedType, flags, parentUserId); 6203 6204 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6205 return null; 6206 } 6207 CrossProfileDomainInfo result = null; 6208 int size = resultTargetUser.size(); 6209 for (int i = 0; i < size; i++) { 6210 ResolveInfo riTargetUser = resultTargetUser.get(i); 6211 // Intent filter verification is only for filters that specify a host. So don't return 6212 // those that handle all web uris. 6213 if (riTargetUser.handleAllWebDataURI) { 6214 continue; 6215 } 6216 String packageName = riTargetUser.activityInfo.packageName; 6217 PackageSetting ps = mSettings.mPackages.get(packageName); 6218 if (ps == null) { 6219 continue; 6220 } 6221 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6222 int status = (int)(verificationState >> 32); 6223 if (result == null) { 6224 result = new CrossProfileDomainInfo(); 6225 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6226 sourceUserId, parentUserId); 6227 result.bestDomainVerificationStatus = status; 6228 } else { 6229 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6230 result.bestDomainVerificationStatus); 6231 } 6232 } 6233 // Don't consider matches with status NEVER across profiles. 6234 if (result != null && result.bestDomainVerificationStatus 6235 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6236 return null; 6237 } 6238 return result; 6239 } 6240 6241 /** 6242 * Verification statuses are ordered from the worse to the best, except for 6243 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6244 */ 6245 private int bestDomainVerificationStatus(int status1, int status2) { 6246 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6247 return status2; 6248 } 6249 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6250 return status1; 6251 } 6252 return (int) MathUtils.max(status1, status2); 6253 } 6254 6255 private boolean isUserEnabled(int userId) { 6256 long callingId = Binder.clearCallingIdentity(); 6257 try { 6258 UserInfo userInfo = sUserManager.getUserInfo(userId); 6259 return userInfo != null && userInfo.isEnabled(); 6260 } finally { 6261 Binder.restoreCallingIdentity(callingId); 6262 } 6263 } 6264 6265 /** 6266 * Filter out activities with systemUserOnly flag set, when current user is not System. 6267 * 6268 * @return filtered list 6269 */ 6270 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6271 if (userId == UserHandle.USER_SYSTEM) { 6272 return resolveInfos; 6273 } 6274 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6275 ResolveInfo info = resolveInfos.get(i); 6276 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6277 resolveInfos.remove(i); 6278 } 6279 } 6280 return resolveInfos; 6281 } 6282 6283 /** 6284 * Filters out ephemeral activities. 6285 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6286 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6287 * 6288 * @param resolveInfos The pre-filtered list of resolved activities 6289 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6290 * is performed. 6291 * @return A filtered list of resolved activities. 6292 */ 6293 private List<ResolveInfo> filterForEphemeral(List<ResolveInfo> resolveInfos, 6294 String ephemeralPkgName) { 6295 if (ephemeralPkgName == null) { 6296 return resolveInfos; 6297 } 6298 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6299 ResolveInfo info = resolveInfos.get(i); 6300 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6301 // allow activities that are defined in the provided package 6302 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6303 continue; 6304 } 6305 // allow activities that have been explicitly exposed to ephemeral apps 6306 if (!isEphemeralApp 6307 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6308 continue; 6309 } 6310 resolveInfos.remove(i); 6311 } 6312 return resolveInfos; 6313 } 6314 6315 /** 6316 * @param resolveInfos list of resolve infos in descending priority order 6317 * @return if the list contains a resolve info with non-negative priority 6318 */ 6319 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6320 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6321 } 6322 6323 private static boolean hasWebURI(Intent intent) { 6324 if (intent.getData() == null) { 6325 return false; 6326 } 6327 final String scheme = intent.getScheme(); 6328 if (TextUtils.isEmpty(scheme)) { 6329 return false; 6330 } 6331 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6332 } 6333 6334 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6335 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6336 int userId) { 6337 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6338 6339 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6340 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6341 candidates.size()); 6342 } 6343 6344 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6345 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6346 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6347 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6348 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6349 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6350 6351 synchronized (mPackages) { 6352 final int count = candidates.size(); 6353 // First, try to use linked apps. Partition the candidates into four lists: 6354 // one for the final results, one for the "do not use ever", one for "undefined status" 6355 // and finally one for "browser app type". 6356 for (int n=0; n<count; n++) { 6357 ResolveInfo info = candidates.get(n); 6358 String packageName = info.activityInfo.packageName; 6359 PackageSetting ps = mSettings.mPackages.get(packageName); 6360 if (ps != null) { 6361 // Add to the special match all list (Browser use case) 6362 if (info.handleAllWebDataURI) { 6363 matchAllList.add(info); 6364 continue; 6365 } 6366 // Try to get the status from User settings first 6367 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6368 int status = (int)(packedStatus >> 32); 6369 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6370 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6371 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6372 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6373 + " : linkgen=" + linkGeneration); 6374 } 6375 // Use link-enabled generation as preferredOrder, i.e. 6376 // prefer newly-enabled over earlier-enabled. 6377 info.preferredOrder = linkGeneration; 6378 alwaysList.add(info); 6379 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6380 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6381 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6382 } 6383 neverList.add(info); 6384 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6385 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6386 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6387 } 6388 alwaysAskList.add(info); 6389 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6390 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6391 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6392 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6393 } 6394 undefinedList.add(info); 6395 } 6396 } 6397 } 6398 6399 // We'll want to include browser possibilities in a few cases 6400 boolean includeBrowser = false; 6401 6402 // First try to add the "always" resolution(s) for the current user, if any 6403 if (alwaysList.size() > 0) { 6404 result.addAll(alwaysList); 6405 } else { 6406 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6407 result.addAll(undefinedList); 6408 // Maybe add one for the other profile. 6409 if (xpDomainInfo != null && ( 6410 xpDomainInfo.bestDomainVerificationStatus 6411 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6412 result.add(xpDomainInfo.resolveInfo); 6413 } 6414 includeBrowser = true; 6415 } 6416 6417 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6418 // If there were 'always' entries their preferred order has been set, so we also 6419 // back that off to make the alternatives equivalent 6420 if (alwaysAskList.size() > 0) { 6421 for (ResolveInfo i : result) { 6422 i.preferredOrder = 0; 6423 } 6424 result.addAll(alwaysAskList); 6425 includeBrowser = true; 6426 } 6427 6428 if (includeBrowser) { 6429 // Also add browsers (all of them or only the default one) 6430 if (DEBUG_DOMAIN_VERIFICATION) { 6431 Slog.v(TAG, " ...including browsers in candidate set"); 6432 } 6433 if ((matchFlags & MATCH_ALL) != 0) { 6434 result.addAll(matchAllList); 6435 } else { 6436 // Browser/generic handling case. If there's a default browser, go straight 6437 // to that (but only if there is no other higher-priority match). 6438 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6439 int maxMatchPrio = 0; 6440 ResolveInfo defaultBrowserMatch = null; 6441 final int numCandidates = matchAllList.size(); 6442 for (int n = 0; n < numCandidates; n++) { 6443 ResolveInfo info = matchAllList.get(n); 6444 // track the highest overall match priority... 6445 if (info.priority > maxMatchPrio) { 6446 maxMatchPrio = info.priority; 6447 } 6448 // ...and the highest-priority default browser match 6449 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6450 if (defaultBrowserMatch == null 6451 || (defaultBrowserMatch.priority < info.priority)) { 6452 if (debug) { 6453 Slog.v(TAG, "Considering default browser match " + info); 6454 } 6455 defaultBrowserMatch = info; 6456 } 6457 } 6458 } 6459 if (defaultBrowserMatch != null 6460 && defaultBrowserMatch.priority >= maxMatchPrio 6461 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6462 { 6463 if (debug) { 6464 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6465 } 6466 result.add(defaultBrowserMatch); 6467 } else { 6468 result.addAll(matchAllList); 6469 } 6470 } 6471 6472 // If there is nothing selected, add all candidates and remove the ones that the user 6473 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6474 if (result.size() == 0) { 6475 result.addAll(candidates); 6476 result.removeAll(neverList); 6477 } 6478 } 6479 } 6480 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6481 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6482 result.size()); 6483 for (ResolveInfo info : result) { 6484 Slog.v(TAG, " + " + info.activityInfo); 6485 } 6486 } 6487 return result; 6488 } 6489 6490 // Returns a packed value as a long: 6491 // 6492 // high 'int'-sized word: link status: undefined/ask/never/always. 6493 // low 'int'-sized word: relative priority among 'always' results. 6494 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6495 long result = ps.getDomainVerificationStatusForUser(userId); 6496 // if none available, get the master status 6497 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6498 if (ps.getIntentFilterVerificationInfo() != null) { 6499 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6500 } 6501 } 6502 return result; 6503 } 6504 6505 private ResolveInfo querySkipCurrentProfileIntents( 6506 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6507 int flags, int sourceUserId) { 6508 if (matchingFilters != null) { 6509 int size = matchingFilters.size(); 6510 for (int i = 0; i < size; i ++) { 6511 CrossProfileIntentFilter filter = matchingFilters.get(i); 6512 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6513 // Checking if there are activities in the target user that can handle the 6514 // intent. 6515 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6516 resolvedType, flags, sourceUserId); 6517 if (resolveInfo != null) { 6518 return resolveInfo; 6519 } 6520 } 6521 } 6522 } 6523 return null; 6524 } 6525 6526 // Return matching ResolveInfo in target user if any. 6527 private ResolveInfo queryCrossProfileIntents( 6528 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6529 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6530 if (matchingFilters != null) { 6531 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6532 // match the same intent. For performance reasons, it is better not to 6533 // run queryIntent twice for the same userId 6534 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6535 int size = matchingFilters.size(); 6536 for (int i = 0; i < size; i++) { 6537 CrossProfileIntentFilter filter = matchingFilters.get(i); 6538 int targetUserId = filter.getTargetUserId(); 6539 boolean skipCurrentProfile = 6540 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6541 boolean skipCurrentProfileIfNoMatchFound = 6542 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6543 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6544 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6545 // Checking if there are activities in the target user that can handle the 6546 // intent. 6547 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6548 resolvedType, flags, sourceUserId); 6549 if (resolveInfo != null) return resolveInfo; 6550 alreadyTriedUserIds.put(targetUserId, true); 6551 } 6552 } 6553 } 6554 return null; 6555 } 6556 6557 /** 6558 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6559 * will forward the intent to the filter's target user. 6560 * Otherwise, returns null. 6561 */ 6562 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6563 String resolvedType, int flags, int sourceUserId) { 6564 int targetUserId = filter.getTargetUserId(); 6565 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6566 resolvedType, flags, targetUserId); 6567 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6568 // If all the matches in the target profile are suspended, return null. 6569 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6570 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6571 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6572 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6573 targetUserId); 6574 } 6575 } 6576 } 6577 return null; 6578 } 6579 6580 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6581 int sourceUserId, int targetUserId) { 6582 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6583 long ident = Binder.clearCallingIdentity(); 6584 boolean targetIsProfile; 6585 try { 6586 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6587 } finally { 6588 Binder.restoreCallingIdentity(ident); 6589 } 6590 String className; 6591 if (targetIsProfile) { 6592 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6593 } else { 6594 className = FORWARD_INTENT_TO_PARENT; 6595 } 6596 ComponentName forwardingActivityComponentName = new ComponentName( 6597 mAndroidApplication.packageName, className); 6598 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6599 sourceUserId); 6600 if (!targetIsProfile) { 6601 forwardingActivityInfo.showUserIcon = targetUserId; 6602 forwardingResolveInfo.noResourceId = true; 6603 } 6604 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6605 forwardingResolveInfo.priority = 0; 6606 forwardingResolveInfo.preferredOrder = 0; 6607 forwardingResolveInfo.match = 0; 6608 forwardingResolveInfo.isDefault = true; 6609 forwardingResolveInfo.filter = filter; 6610 forwardingResolveInfo.targetUserId = targetUserId; 6611 return forwardingResolveInfo; 6612 } 6613 6614 @Override 6615 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6616 Intent[] specifics, String[] specificTypes, Intent intent, 6617 String resolvedType, int flags, int userId) { 6618 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6619 specificTypes, intent, resolvedType, flags, userId)); 6620 } 6621 6622 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6623 Intent[] specifics, String[] specificTypes, Intent intent, 6624 String resolvedType, int flags, int userId) { 6625 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6626 flags = updateFlagsForResolve(flags, userId, intent); 6627 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6628 false /* requireFullPermission */, false /* checkShell */, 6629 "query intent activity options"); 6630 final String resultsAction = intent.getAction(); 6631 6632 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6633 | PackageManager.GET_RESOLVED_FILTER, userId); 6634 6635 if (DEBUG_INTENT_MATCHING) { 6636 Log.v(TAG, "Query " + intent + ": " + results); 6637 } 6638 6639 int specificsPos = 0; 6640 int N; 6641 6642 // todo: note that the algorithm used here is O(N^2). This 6643 // isn't a problem in our current environment, but if we start running 6644 // into situations where we have more than 5 or 10 matches then this 6645 // should probably be changed to something smarter... 6646 6647 // First we go through and resolve each of the specific items 6648 // that were supplied, taking care of removing any corresponding 6649 // duplicate items in the generic resolve list. 6650 if (specifics != null) { 6651 for (int i=0; i<specifics.length; i++) { 6652 final Intent sintent = specifics[i]; 6653 if (sintent == null) { 6654 continue; 6655 } 6656 6657 if (DEBUG_INTENT_MATCHING) { 6658 Log.v(TAG, "Specific #" + i + ": " + sintent); 6659 } 6660 6661 String action = sintent.getAction(); 6662 if (resultsAction != null && resultsAction.equals(action)) { 6663 // If this action was explicitly requested, then don't 6664 // remove things that have it. 6665 action = null; 6666 } 6667 6668 ResolveInfo ri = null; 6669 ActivityInfo ai = null; 6670 6671 ComponentName comp = sintent.getComponent(); 6672 if (comp == null) { 6673 ri = resolveIntent( 6674 sintent, 6675 specificTypes != null ? specificTypes[i] : null, 6676 flags, userId); 6677 if (ri == null) { 6678 continue; 6679 } 6680 if (ri == mResolveInfo) { 6681 // ACK! Must do something better with this. 6682 } 6683 ai = ri.activityInfo; 6684 comp = new ComponentName(ai.applicationInfo.packageName, 6685 ai.name); 6686 } else { 6687 ai = getActivityInfo(comp, flags, userId); 6688 if (ai == null) { 6689 continue; 6690 } 6691 } 6692 6693 // Look for any generic query activities that are duplicates 6694 // of this specific one, and remove them from the results. 6695 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6696 N = results.size(); 6697 int j; 6698 for (j=specificsPos; j<N; j++) { 6699 ResolveInfo sri = results.get(j); 6700 if ((sri.activityInfo.name.equals(comp.getClassName()) 6701 && sri.activityInfo.applicationInfo.packageName.equals( 6702 comp.getPackageName())) 6703 || (action != null && sri.filter.matchAction(action))) { 6704 results.remove(j); 6705 if (DEBUG_INTENT_MATCHING) Log.v( 6706 TAG, "Removing duplicate item from " + j 6707 + " due to specific " + specificsPos); 6708 if (ri == null) { 6709 ri = sri; 6710 } 6711 j--; 6712 N--; 6713 } 6714 } 6715 6716 // Add this specific item to its proper place. 6717 if (ri == null) { 6718 ri = new ResolveInfo(); 6719 ri.activityInfo = ai; 6720 } 6721 results.add(specificsPos, ri); 6722 ri.specificIndex = i; 6723 specificsPos++; 6724 } 6725 } 6726 6727 // Now we go through the remaining generic results and remove any 6728 // duplicate actions that are found here. 6729 N = results.size(); 6730 for (int i=specificsPos; i<N-1; i++) { 6731 final ResolveInfo rii = results.get(i); 6732 if (rii.filter == null) { 6733 continue; 6734 } 6735 6736 // Iterate over all of the actions of this result's intent 6737 // filter... typically this should be just one. 6738 final Iterator<String> it = rii.filter.actionsIterator(); 6739 if (it == null) { 6740 continue; 6741 } 6742 while (it.hasNext()) { 6743 final String action = it.next(); 6744 if (resultsAction != null && resultsAction.equals(action)) { 6745 // If this action was explicitly requested, then don't 6746 // remove things that have it. 6747 continue; 6748 } 6749 for (int j=i+1; j<N; j++) { 6750 final ResolveInfo rij = results.get(j); 6751 if (rij.filter != null && rij.filter.hasAction(action)) { 6752 results.remove(j); 6753 if (DEBUG_INTENT_MATCHING) Log.v( 6754 TAG, "Removing duplicate item from " + j 6755 + " due to action " + action + " at " + i); 6756 j--; 6757 N--; 6758 } 6759 } 6760 } 6761 6762 // If the caller didn't request filter information, drop it now 6763 // so we don't have to marshall/unmarshall it. 6764 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6765 rii.filter = null; 6766 } 6767 } 6768 6769 // Filter out the caller activity if so requested. 6770 if (caller != null) { 6771 N = results.size(); 6772 for (int i=0; i<N; i++) { 6773 ActivityInfo ainfo = results.get(i).activityInfo; 6774 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6775 && caller.getClassName().equals(ainfo.name)) { 6776 results.remove(i); 6777 break; 6778 } 6779 } 6780 } 6781 6782 // If the caller didn't request filter information, 6783 // drop them now so we don't have to 6784 // marshall/unmarshall it. 6785 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6786 N = results.size(); 6787 for (int i=0; i<N; i++) { 6788 results.get(i).filter = null; 6789 } 6790 } 6791 6792 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6793 return results; 6794 } 6795 6796 @Override 6797 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6798 String resolvedType, int flags, int userId) { 6799 return new ParceledListSlice<>( 6800 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6801 } 6802 6803 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6804 String resolvedType, int flags, int userId) { 6805 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6806 flags = updateFlagsForResolve(flags, userId, intent); 6807 ComponentName comp = intent.getComponent(); 6808 if (comp == null) { 6809 if (intent.getSelector() != null) { 6810 intent = intent.getSelector(); 6811 comp = intent.getComponent(); 6812 } 6813 } 6814 if (comp != null) { 6815 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6816 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6817 if (ai != null) { 6818 ResolveInfo ri = new ResolveInfo(); 6819 ri.activityInfo = ai; 6820 list.add(ri); 6821 } 6822 return list; 6823 } 6824 6825 // reader 6826 synchronized (mPackages) { 6827 String pkgName = intent.getPackage(); 6828 if (pkgName == null) { 6829 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6830 } 6831 final PackageParser.Package pkg = mPackages.get(pkgName); 6832 if (pkg != null) { 6833 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6834 userId); 6835 } 6836 return Collections.emptyList(); 6837 } 6838 } 6839 6840 @Override 6841 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6842 if (!sUserManager.exists(userId)) return null; 6843 flags = updateFlagsForResolve(flags, userId, intent); 6844 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6845 if (query != null) { 6846 if (query.size() >= 1) { 6847 // If there is more than one service with the same priority, 6848 // just arbitrarily pick the first one. 6849 return query.get(0); 6850 } 6851 } 6852 return null; 6853 } 6854 6855 @Override 6856 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6857 String resolvedType, int flags, int userId) { 6858 return new ParceledListSlice<>( 6859 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6860 } 6861 6862 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6863 String resolvedType, int flags, int userId) { 6864 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6865 flags = updateFlagsForResolve(flags, userId, intent); 6866 ComponentName comp = intent.getComponent(); 6867 if (comp == null) { 6868 if (intent.getSelector() != null) { 6869 intent = intent.getSelector(); 6870 comp = intent.getComponent(); 6871 } 6872 } 6873 if (comp != null) { 6874 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6875 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6876 if (si != null) { 6877 final ResolveInfo ri = new ResolveInfo(); 6878 ri.serviceInfo = si; 6879 list.add(ri); 6880 } 6881 return list; 6882 } 6883 6884 // reader 6885 synchronized (mPackages) { 6886 String pkgName = intent.getPackage(); 6887 if (pkgName == null) { 6888 return mServices.queryIntent(intent, resolvedType, flags, userId); 6889 } 6890 final PackageParser.Package pkg = mPackages.get(pkgName); 6891 if (pkg != null) { 6892 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6893 userId); 6894 } 6895 return Collections.emptyList(); 6896 } 6897 } 6898 6899 @Override 6900 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6901 String resolvedType, int flags, int userId) { 6902 return new ParceledListSlice<>( 6903 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6904 } 6905 6906 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6907 Intent intent, String resolvedType, int flags, int userId) { 6908 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6909 flags = updateFlagsForResolve(flags, userId, intent); 6910 ComponentName comp = intent.getComponent(); 6911 if (comp == null) { 6912 if (intent.getSelector() != null) { 6913 intent = intent.getSelector(); 6914 comp = intent.getComponent(); 6915 } 6916 } 6917 if (comp != null) { 6918 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6919 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6920 if (pi != null) { 6921 final ResolveInfo ri = new ResolveInfo(); 6922 ri.providerInfo = pi; 6923 list.add(ri); 6924 } 6925 return list; 6926 } 6927 6928 // reader 6929 synchronized (mPackages) { 6930 String pkgName = intent.getPackage(); 6931 if (pkgName == null) { 6932 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6933 } 6934 final PackageParser.Package pkg = mPackages.get(pkgName); 6935 if (pkg != null) { 6936 return mProviders.queryIntentForPackage( 6937 intent, resolvedType, flags, pkg.providers, userId); 6938 } 6939 return Collections.emptyList(); 6940 } 6941 } 6942 6943 @Override 6944 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6945 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6946 flags = updateFlagsForPackage(flags, userId, null); 6947 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6948 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6949 true /* requireFullPermission */, false /* checkShell */, 6950 "get installed packages"); 6951 6952 // writer 6953 synchronized (mPackages) { 6954 ArrayList<PackageInfo> list; 6955 if (listUninstalled) { 6956 list = new ArrayList<>(mSettings.mPackages.size()); 6957 for (PackageSetting ps : mSettings.mPackages.values()) { 6958 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 6959 continue; 6960 } 6961 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 6962 if (pi != null) { 6963 list.add(pi); 6964 } 6965 } 6966 } else { 6967 list = new ArrayList<>(mPackages.size()); 6968 for (PackageParser.Package p : mPackages.values()) { 6969 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 6970 Binder.getCallingUid(), userId)) { 6971 continue; 6972 } 6973 final PackageInfo pi = generatePackageInfo((PackageSetting) 6974 p.mExtras, flags, userId); 6975 if (pi != null) { 6976 list.add(pi); 6977 } 6978 } 6979 } 6980 6981 return new ParceledListSlice<>(list); 6982 } 6983 } 6984 6985 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6986 String[] permissions, boolean[] tmp, int flags, int userId) { 6987 int numMatch = 0; 6988 final PermissionsState permissionsState = ps.getPermissionsState(); 6989 for (int i=0; i<permissions.length; i++) { 6990 final String permission = permissions[i]; 6991 if (permissionsState.hasPermission(permission, userId)) { 6992 tmp[i] = true; 6993 numMatch++; 6994 } else { 6995 tmp[i] = false; 6996 } 6997 } 6998 if (numMatch == 0) { 6999 return; 7000 } 7001 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7002 7003 // The above might return null in cases of uninstalled apps or install-state 7004 // skew across users/profiles. 7005 if (pi != null) { 7006 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7007 if (numMatch == permissions.length) { 7008 pi.requestedPermissions = permissions; 7009 } else { 7010 pi.requestedPermissions = new String[numMatch]; 7011 numMatch = 0; 7012 for (int i=0; i<permissions.length; i++) { 7013 if (tmp[i]) { 7014 pi.requestedPermissions[numMatch] = permissions[i]; 7015 numMatch++; 7016 } 7017 } 7018 } 7019 } 7020 list.add(pi); 7021 } 7022 } 7023 7024 @Override 7025 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7026 String[] permissions, int flags, int userId) { 7027 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7028 flags = updateFlagsForPackage(flags, userId, permissions); 7029 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7030 true /* requireFullPermission */, false /* checkShell */, 7031 "get packages holding permissions"); 7032 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7033 7034 // writer 7035 synchronized (mPackages) { 7036 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7037 boolean[] tmpBools = new boolean[permissions.length]; 7038 if (listUninstalled) { 7039 for (PackageSetting ps : mSettings.mPackages.values()) { 7040 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7041 userId); 7042 } 7043 } else { 7044 for (PackageParser.Package pkg : mPackages.values()) { 7045 PackageSetting ps = (PackageSetting)pkg.mExtras; 7046 if (ps != null) { 7047 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7048 userId); 7049 } 7050 } 7051 } 7052 7053 return new ParceledListSlice<PackageInfo>(list); 7054 } 7055 } 7056 7057 @Override 7058 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7059 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7060 flags = updateFlagsForApplication(flags, userId, null); 7061 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7062 7063 // writer 7064 synchronized (mPackages) { 7065 ArrayList<ApplicationInfo> list; 7066 if (listUninstalled) { 7067 list = new ArrayList<>(mSettings.mPackages.size()); 7068 for (PackageSetting ps : mSettings.mPackages.values()) { 7069 ApplicationInfo ai; 7070 int effectiveFlags = flags; 7071 if (ps.isSystem()) { 7072 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7073 } 7074 if (ps.pkg != null) { 7075 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7076 continue; 7077 } 7078 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7079 ps.readUserState(userId), userId); 7080 if (ai != null) { 7081 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7082 } 7083 } else { 7084 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7085 // and already converts to externally visible package name 7086 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7087 Binder.getCallingUid(), effectiveFlags, userId); 7088 } 7089 if (ai != null) { 7090 list.add(ai); 7091 } 7092 } 7093 } else { 7094 list = new ArrayList<>(mPackages.size()); 7095 for (PackageParser.Package p : mPackages.values()) { 7096 if (p.mExtras != null) { 7097 PackageSetting ps = (PackageSetting) p.mExtras; 7098 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7099 continue; 7100 } 7101 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7102 ps.readUserState(userId), userId); 7103 if (ai != null) { 7104 ai.packageName = resolveExternalPackageNameLPr(p); 7105 list.add(ai); 7106 } 7107 } 7108 } 7109 } 7110 7111 return new ParceledListSlice<>(list); 7112 } 7113 } 7114 7115 @Override 7116 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7117 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7118 return null; 7119 } 7120 7121 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7122 "getEphemeralApplications"); 7123 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7124 true /* requireFullPermission */, false /* checkShell */, 7125 "getEphemeralApplications"); 7126 synchronized (mPackages) { 7127 List<InstantAppInfo> instantApps = mInstantAppRegistry 7128 .getInstantAppsLPr(userId); 7129 if (instantApps != null) { 7130 return new ParceledListSlice<>(instantApps); 7131 } 7132 } 7133 return null; 7134 } 7135 7136 @Override 7137 public boolean isInstantApp(String packageName, int userId) { 7138 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7139 true /* requireFullPermission */, false /* checkShell */, 7140 "isInstantApp"); 7141 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7142 return false; 7143 } 7144 7145 if (!isCallerSameApp(packageName)) { 7146 return false; 7147 } 7148 synchronized (mPackages) { 7149 final PackageSetting ps = mSettings.mPackages.get(packageName); 7150 if (ps != null) { 7151 return ps.getInstantApp(userId); 7152 } 7153 } 7154 return false; 7155 } 7156 7157 @Override 7158 public byte[] getInstantAppCookie(String packageName, int userId) { 7159 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7160 return null; 7161 } 7162 7163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7164 true /* requireFullPermission */, false /* checkShell */, 7165 "getInstantAppCookie"); 7166 if (!isCallerSameApp(packageName)) { 7167 return null; 7168 } 7169 synchronized (mPackages) { 7170 return mInstantAppRegistry.getInstantAppCookieLPw( 7171 packageName, userId); 7172 } 7173 } 7174 7175 @Override 7176 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7177 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7178 return true; 7179 } 7180 7181 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7182 true /* requireFullPermission */, true /* checkShell */, 7183 "setInstantAppCookie"); 7184 if (!isCallerSameApp(packageName)) { 7185 return false; 7186 } 7187 synchronized (mPackages) { 7188 return mInstantAppRegistry.setInstantAppCookieLPw( 7189 packageName, cookie, userId); 7190 } 7191 } 7192 7193 @Override 7194 public Bitmap getInstantAppIcon(String packageName, int userId) { 7195 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7196 return null; 7197 } 7198 7199 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7200 "getInstantAppIcon"); 7201 7202 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7203 true /* requireFullPermission */, false /* checkShell */, 7204 "getInstantAppIcon"); 7205 7206 synchronized (mPackages) { 7207 return mInstantAppRegistry.getInstantAppIconLPw( 7208 packageName, userId); 7209 } 7210 } 7211 7212 private boolean isCallerSameApp(String packageName) { 7213 PackageParser.Package pkg = mPackages.get(packageName); 7214 return pkg != null 7215 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7216 } 7217 7218 @Override 7219 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7220 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7221 } 7222 7223 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7224 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7225 7226 // reader 7227 synchronized (mPackages) { 7228 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7229 final int userId = UserHandle.getCallingUserId(); 7230 while (i.hasNext()) { 7231 final PackageParser.Package p = i.next(); 7232 if (p.applicationInfo == null) continue; 7233 7234 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7235 && !p.applicationInfo.isDirectBootAware(); 7236 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7237 && p.applicationInfo.isDirectBootAware(); 7238 7239 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7240 && (!mSafeMode || isSystemApp(p)) 7241 && (matchesUnaware || matchesAware)) { 7242 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7243 if (ps != null) { 7244 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7245 ps.readUserState(userId), userId); 7246 if (ai != null) { 7247 finalList.add(ai); 7248 } 7249 } 7250 } 7251 } 7252 } 7253 7254 return finalList; 7255 } 7256 7257 @Override 7258 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7259 if (!sUserManager.exists(userId)) return null; 7260 flags = updateFlagsForComponent(flags, userId, name); 7261 // reader 7262 synchronized (mPackages) { 7263 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7264 PackageSetting ps = provider != null 7265 ? mSettings.mPackages.get(provider.owner.packageName) 7266 : null; 7267 return ps != null 7268 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7269 ? PackageParser.generateProviderInfo(provider, flags, 7270 ps.readUserState(userId), userId) 7271 : null; 7272 } 7273 } 7274 7275 /** 7276 * @deprecated 7277 */ 7278 @Deprecated 7279 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7280 // reader 7281 synchronized (mPackages) { 7282 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7283 .entrySet().iterator(); 7284 final int userId = UserHandle.getCallingUserId(); 7285 while (i.hasNext()) { 7286 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7287 PackageParser.Provider p = entry.getValue(); 7288 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7289 7290 if (ps != null && p.syncable 7291 && (!mSafeMode || (p.info.applicationInfo.flags 7292 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7293 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7294 ps.readUserState(userId), userId); 7295 if (info != null) { 7296 outNames.add(entry.getKey()); 7297 outInfo.add(info); 7298 } 7299 } 7300 } 7301 } 7302 } 7303 7304 @Override 7305 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7306 int uid, int flags) { 7307 final int userId = processName != null ? UserHandle.getUserId(uid) 7308 : UserHandle.getCallingUserId(); 7309 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7310 flags = updateFlagsForComponent(flags, userId, processName); 7311 7312 ArrayList<ProviderInfo> finalList = null; 7313 // reader 7314 synchronized (mPackages) { 7315 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7316 while (i.hasNext()) { 7317 final PackageParser.Provider p = i.next(); 7318 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7319 if (ps != null && p.info.authority != null 7320 && (processName == null 7321 || (p.info.processName.equals(processName) 7322 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7323 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7324 if (finalList == null) { 7325 finalList = new ArrayList<ProviderInfo>(3); 7326 } 7327 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7328 ps.readUserState(userId), userId); 7329 if (info != null) { 7330 finalList.add(info); 7331 } 7332 } 7333 } 7334 } 7335 7336 if (finalList != null) { 7337 Collections.sort(finalList, mProviderInitOrderSorter); 7338 return new ParceledListSlice<ProviderInfo>(finalList); 7339 } 7340 7341 return ParceledListSlice.emptyList(); 7342 } 7343 7344 @Override 7345 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7346 // reader 7347 synchronized (mPackages) { 7348 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7349 return PackageParser.generateInstrumentationInfo(i, flags); 7350 } 7351 } 7352 7353 @Override 7354 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7355 String targetPackage, int flags) { 7356 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7357 } 7358 7359 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7360 int flags) { 7361 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7362 7363 // reader 7364 synchronized (mPackages) { 7365 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7366 while (i.hasNext()) { 7367 final PackageParser.Instrumentation p = i.next(); 7368 if (targetPackage == null 7369 || targetPackage.equals(p.info.targetPackage)) { 7370 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7371 flags); 7372 if (ii != null) { 7373 finalList.add(ii); 7374 } 7375 } 7376 } 7377 } 7378 7379 return finalList; 7380 } 7381 7382 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7383 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7384 if (overlays == null) { 7385 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7386 return; 7387 } 7388 for (PackageParser.Package opkg : overlays.values()) { 7389 // Not much to do if idmap fails: we already logged the error 7390 // and we certainly don't want to abort installation of pkg simply 7391 // because an overlay didn't fit properly. For these reasons, 7392 // ignore the return value of createIdmapForPackagePairLI. 7393 createIdmapForPackagePairLI(pkg, opkg); 7394 } 7395 } 7396 7397 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7398 PackageParser.Package opkg) { 7399 if (!opkg.mTrustedOverlay) { 7400 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7401 opkg.baseCodePath + ": overlay not trusted"); 7402 return false; 7403 } 7404 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7405 if (overlaySet == null) { 7406 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7407 opkg.baseCodePath + " but target package has no known overlays"); 7408 return false; 7409 } 7410 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7411 // TODO: generate idmap for split APKs 7412 try { 7413 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7414 } catch (InstallerException e) { 7415 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7416 + opkg.baseCodePath); 7417 return false; 7418 } 7419 PackageParser.Package[] overlayArray = 7420 overlaySet.values().toArray(new PackageParser.Package[0]); 7421 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7422 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7423 return p1.mOverlayPriority - p2.mOverlayPriority; 7424 } 7425 }; 7426 Arrays.sort(overlayArray, cmp); 7427 7428 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7429 int i = 0; 7430 for (PackageParser.Package p : overlayArray) { 7431 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7432 } 7433 return true; 7434 } 7435 7436 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7437 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7438 try { 7439 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7440 } finally { 7441 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7442 } 7443 } 7444 7445 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7446 final File[] files = dir.listFiles(); 7447 if (ArrayUtils.isEmpty(files)) { 7448 Log.d(TAG, "No files in app dir " + dir); 7449 return; 7450 } 7451 7452 if (DEBUG_PACKAGE_SCANNING) { 7453 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7454 + " flags=0x" + Integer.toHexString(parseFlags)); 7455 } 7456 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7457 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7458 7459 // Submit files for parsing in parallel 7460 int fileCount = 0; 7461 for (File file : files) { 7462 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7463 && !PackageInstallerService.isStageName(file.getName()); 7464 if (!isPackage) { 7465 // Ignore entries which are not packages 7466 continue; 7467 } 7468 parallelPackageParser.submit(file, parseFlags); 7469 fileCount++; 7470 } 7471 7472 // Process results one by one 7473 for (; fileCount > 0; fileCount--) { 7474 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7475 Throwable throwable = parseResult.throwable; 7476 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7477 7478 if (throwable == null) { 7479 // Static shared libraries have synthetic package names 7480 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7481 renameStaticSharedLibraryPackage(parseResult.pkg); 7482 } 7483 try { 7484 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7485 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7486 currentTime, null); 7487 } 7488 } catch (PackageManagerException e) { 7489 errorCode = e.error; 7490 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7491 } 7492 } else if (throwable instanceof PackageParser.PackageParserException) { 7493 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7494 throwable; 7495 errorCode = e.error; 7496 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7497 } else { 7498 throw new IllegalStateException("Unexpected exception occurred while parsing " 7499 + parseResult.scanFile, throwable); 7500 } 7501 7502 // Delete invalid userdata apps 7503 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7504 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7505 logCriticalInfo(Log.WARN, 7506 "Deleting invalid package at " + parseResult.scanFile); 7507 removeCodePathLI(parseResult.scanFile); 7508 } 7509 } 7510 parallelPackageParser.close(); 7511 } 7512 7513 private static File getSettingsProblemFile() { 7514 File dataDir = Environment.getDataDirectory(); 7515 File systemDir = new File(dataDir, "system"); 7516 File fname = new File(systemDir, "uiderrors.txt"); 7517 return fname; 7518 } 7519 7520 static void reportSettingsProblem(int priority, String msg) { 7521 logCriticalInfo(priority, msg); 7522 } 7523 7524 static void logCriticalInfo(int priority, String msg) { 7525 Slog.println(priority, TAG, msg); 7526 EventLogTags.writePmCriticalInfo(msg); 7527 try { 7528 File fname = getSettingsProblemFile(); 7529 FileOutputStream out = new FileOutputStream(fname, true); 7530 PrintWriter pw = new FastPrintWriter(out); 7531 SimpleDateFormat formatter = new SimpleDateFormat(); 7532 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7533 pw.println(dateString + ": " + msg); 7534 pw.close(); 7535 FileUtils.setPermissions( 7536 fname.toString(), 7537 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7538 -1, -1); 7539 } catch (java.io.IOException e) { 7540 } 7541 } 7542 7543 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7544 if (srcFile.isDirectory()) { 7545 final File baseFile = new File(pkg.baseCodePath); 7546 long maxModifiedTime = baseFile.lastModified(); 7547 if (pkg.splitCodePaths != null) { 7548 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7549 final File splitFile = new File(pkg.splitCodePaths[i]); 7550 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7551 } 7552 } 7553 return maxModifiedTime; 7554 } 7555 return srcFile.lastModified(); 7556 } 7557 7558 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7559 final int policyFlags) throws PackageManagerException { 7560 // When upgrading from pre-N MR1, verify the package time stamp using the package 7561 // directory and not the APK file. 7562 final long lastModifiedTime = mIsPreNMR1Upgrade 7563 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7564 if (ps != null 7565 && ps.codePath.equals(srcFile) 7566 && ps.timeStamp == lastModifiedTime 7567 && !isCompatSignatureUpdateNeeded(pkg) 7568 && !isRecoverSignatureUpdateNeeded(pkg)) { 7569 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7570 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7571 ArraySet<PublicKey> signingKs; 7572 synchronized (mPackages) { 7573 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7574 } 7575 if (ps.signatures.mSignatures != null 7576 && ps.signatures.mSignatures.length != 0 7577 && signingKs != null) { 7578 // Optimization: reuse the existing cached certificates 7579 // if the package appears to be unchanged. 7580 pkg.mSignatures = ps.signatures.mSignatures; 7581 pkg.mSigningKeys = signingKs; 7582 return; 7583 } 7584 7585 Slog.w(TAG, "PackageSetting for " + ps.name 7586 + " is missing signatures. Collecting certs again to recover them."); 7587 } else { 7588 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7589 } 7590 7591 try { 7592 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7593 PackageParser.collectCertificates(pkg, policyFlags); 7594 } catch (PackageParserException e) { 7595 throw PackageManagerException.from(e); 7596 } finally { 7597 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7598 } 7599 } 7600 7601 /** 7602 * Traces a package scan. 7603 * @see #scanPackageLI(File, int, int, long, UserHandle) 7604 */ 7605 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7606 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7607 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7608 try { 7609 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7610 } finally { 7611 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7612 } 7613 } 7614 7615 /** 7616 * Scans a package and returns the newly parsed package. 7617 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7618 */ 7619 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7620 long currentTime, UserHandle user) throws PackageManagerException { 7621 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7622 PackageParser pp = new PackageParser(); 7623 pp.setSeparateProcesses(mSeparateProcesses); 7624 pp.setOnlyCoreApps(mOnlyCore); 7625 pp.setDisplayMetrics(mMetrics); 7626 7627 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7628 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7629 } 7630 7631 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7632 final PackageParser.Package pkg; 7633 try { 7634 pkg = pp.parsePackage(scanFile, parseFlags); 7635 } catch (PackageParserException e) { 7636 throw PackageManagerException.from(e); 7637 } finally { 7638 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7639 } 7640 7641 // Static shared libraries have synthetic package names 7642 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7643 renameStaticSharedLibraryPackage(pkg); 7644 } 7645 7646 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7647 } 7648 7649 /** 7650 * Scans a package and returns the newly parsed package. 7651 * @throws PackageManagerException on a parse error. 7652 */ 7653 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7654 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7655 throws PackageManagerException { 7656 // If the package has children and this is the first dive in the function 7657 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7658 // packages (parent and children) would be successfully scanned before the 7659 // actual scan since scanning mutates internal state and we want to atomically 7660 // install the package and its children. 7661 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7662 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7663 scanFlags |= SCAN_CHECK_ONLY; 7664 } 7665 } else { 7666 scanFlags &= ~SCAN_CHECK_ONLY; 7667 } 7668 7669 // Scan the parent 7670 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7671 scanFlags, currentTime, user); 7672 7673 // Scan the children 7674 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7675 for (int i = 0; i < childCount; i++) { 7676 PackageParser.Package childPackage = pkg.childPackages.get(i); 7677 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7678 currentTime, user); 7679 } 7680 7681 7682 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7683 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7684 } 7685 7686 return scannedPkg; 7687 } 7688 7689 /** 7690 * Scans a package and returns the newly parsed package. 7691 * @throws PackageManagerException on a parse error. 7692 */ 7693 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7694 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7695 throws PackageManagerException { 7696 PackageSetting ps = null; 7697 PackageSetting updatedPkg; 7698 // reader 7699 synchronized (mPackages) { 7700 // Look to see if we already know about this package. 7701 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7702 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7703 // This package has been renamed to its original name. Let's 7704 // use that. 7705 ps = mSettings.getPackageLPr(oldName); 7706 } 7707 // If there was no original package, see one for the real package name. 7708 if (ps == null) { 7709 ps = mSettings.getPackageLPr(pkg.packageName); 7710 } 7711 // Check to see if this package could be hiding/updating a system 7712 // package. Must look for it either under the original or real 7713 // package name depending on our state. 7714 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7715 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7716 7717 // If this is a package we don't know about on the system partition, we 7718 // may need to remove disabled child packages on the system partition 7719 // or may need to not add child packages if the parent apk is updated 7720 // on the data partition and no longer defines this child package. 7721 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7722 // If this is a parent package for an updated system app and this system 7723 // app got an OTA update which no longer defines some of the child packages 7724 // we have to prune them from the disabled system packages. 7725 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7726 if (disabledPs != null) { 7727 final int scannedChildCount = (pkg.childPackages != null) 7728 ? pkg.childPackages.size() : 0; 7729 final int disabledChildCount = disabledPs.childPackageNames != null 7730 ? disabledPs.childPackageNames.size() : 0; 7731 for (int i = 0; i < disabledChildCount; i++) { 7732 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7733 boolean disabledPackageAvailable = false; 7734 for (int j = 0; j < scannedChildCount; j++) { 7735 PackageParser.Package childPkg = pkg.childPackages.get(j); 7736 if (childPkg.packageName.equals(disabledChildPackageName)) { 7737 disabledPackageAvailable = true; 7738 break; 7739 } 7740 } 7741 if (!disabledPackageAvailable) { 7742 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7743 } 7744 } 7745 } 7746 } 7747 } 7748 7749 boolean updatedPkgBetter = false; 7750 // First check if this is a system package that may involve an update 7751 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7752 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7753 // it needs to drop FLAG_PRIVILEGED. 7754 if (locationIsPrivileged(scanFile)) { 7755 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7756 } else { 7757 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7758 } 7759 7760 if (ps != null && !ps.codePath.equals(scanFile)) { 7761 // The path has changed from what was last scanned... check the 7762 // version of the new path against what we have stored to determine 7763 // what to do. 7764 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7765 if (pkg.mVersionCode <= ps.versionCode) { 7766 // The system package has been updated and the code path does not match 7767 // Ignore entry. Skip it. 7768 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7769 + " ignored: updated version " + ps.versionCode 7770 + " better than this " + pkg.mVersionCode); 7771 if (!updatedPkg.codePath.equals(scanFile)) { 7772 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7773 + ps.name + " changing from " + updatedPkg.codePathString 7774 + " to " + scanFile); 7775 updatedPkg.codePath = scanFile; 7776 updatedPkg.codePathString = scanFile.toString(); 7777 updatedPkg.resourcePath = scanFile; 7778 updatedPkg.resourcePathString = scanFile.toString(); 7779 } 7780 updatedPkg.pkg = pkg; 7781 updatedPkg.versionCode = pkg.mVersionCode; 7782 7783 // Update the disabled system child packages to point to the package too. 7784 final int childCount = updatedPkg.childPackageNames != null 7785 ? updatedPkg.childPackageNames.size() : 0; 7786 for (int i = 0; i < childCount; i++) { 7787 String childPackageName = updatedPkg.childPackageNames.get(i); 7788 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7789 childPackageName); 7790 if (updatedChildPkg != null) { 7791 updatedChildPkg.pkg = pkg; 7792 updatedChildPkg.versionCode = pkg.mVersionCode; 7793 } 7794 } 7795 7796 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7797 + scanFile + " ignored: updated version " + ps.versionCode 7798 + " better than this " + pkg.mVersionCode); 7799 } else { 7800 // The current app on the system partition is better than 7801 // what we have updated to on the data partition; switch 7802 // back to the system partition version. 7803 // At this point, its safely assumed that package installation for 7804 // apps in system partition will go through. If not there won't be a working 7805 // version of the app 7806 // writer 7807 synchronized (mPackages) { 7808 // Just remove the loaded entries from package lists. 7809 mPackages.remove(ps.name); 7810 } 7811 7812 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7813 + " reverting from " + ps.codePathString 7814 + ": new version " + pkg.mVersionCode 7815 + " better than installed " + ps.versionCode); 7816 7817 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7818 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7819 synchronized (mInstallLock) { 7820 args.cleanUpResourcesLI(); 7821 } 7822 synchronized (mPackages) { 7823 mSettings.enableSystemPackageLPw(ps.name); 7824 } 7825 updatedPkgBetter = true; 7826 } 7827 } 7828 } 7829 7830 if (updatedPkg != null) { 7831 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7832 // initially 7833 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7834 7835 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7836 // flag set initially 7837 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7838 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7839 } 7840 } 7841 7842 // Verify certificates against what was last scanned 7843 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7844 7845 /* 7846 * A new system app appeared, but we already had a non-system one of the 7847 * same name installed earlier. 7848 */ 7849 boolean shouldHideSystemApp = false; 7850 if (updatedPkg == null && ps != null 7851 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7852 /* 7853 * Check to make sure the signatures match first. If they don't, 7854 * wipe the installed application and its data. 7855 */ 7856 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7857 != PackageManager.SIGNATURE_MATCH) { 7858 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7859 + " signatures don't match existing userdata copy; removing"); 7860 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7861 "scanPackageInternalLI")) { 7862 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7863 } 7864 ps = null; 7865 } else { 7866 /* 7867 * If the newly-added system app is an older version than the 7868 * already installed version, hide it. It will be scanned later 7869 * and re-added like an update. 7870 */ 7871 if (pkg.mVersionCode <= ps.versionCode) { 7872 shouldHideSystemApp = true; 7873 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7874 + " but new version " + pkg.mVersionCode + " better than installed " 7875 + ps.versionCode + "; hiding system"); 7876 } else { 7877 /* 7878 * The newly found system app is a newer version that the 7879 * one previously installed. Simply remove the 7880 * already-installed application and replace it with our own 7881 * while keeping the application data. 7882 */ 7883 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7884 + " reverting from " + ps.codePathString + ": new version " 7885 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7886 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7887 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7888 synchronized (mInstallLock) { 7889 args.cleanUpResourcesLI(); 7890 } 7891 } 7892 } 7893 } 7894 7895 // The apk is forward locked (not public) if its code and resources 7896 // are kept in different files. (except for app in either system or 7897 // vendor path). 7898 // TODO grab this value from PackageSettings 7899 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7900 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7901 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7902 } 7903 } 7904 7905 // TODO: extend to support forward-locked splits 7906 String resourcePath = null; 7907 String baseResourcePath = null; 7908 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7909 if (ps != null && ps.resourcePathString != null) { 7910 resourcePath = ps.resourcePathString; 7911 baseResourcePath = ps.resourcePathString; 7912 } else { 7913 // Should not happen at all. Just log an error. 7914 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7915 } 7916 } else { 7917 resourcePath = pkg.codePath; 7918 baseResourcePath = pkg.baseCodePath; 7919 } 7920 7921 // Set application objects path explicitly. 7922 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7923 pkg.setApplicationInfoCodePath(pkg.codePath); 7924 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7925 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7926 pkg.setApplicationInfoResourcePath(resourcePath); 7927 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7928 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7929 7930 final int userId = ((user == null) ? 0 : user.getIdentifier()); 7931 if (ps != null && ps.getInstantApp(userId)) { 7932 scanFlags |= SCAN_AS_INSTANT_APP; 7933 } 7934 7935 // Note that we invoke the following method only if we are about to unpack an application 7936 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7937 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7938 7939 /* 7940 * If the system app should be overridden by a previously installed 7941 * data, hide the system app now and let the /data/app scan pick it up 7942 * again. 7943 */ 7944 if (shouldHideSystemApp) { 7945 synchronized (mPackages) { 7946 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7947 } 7948 } 7949 7950 return scannedPkg; 7951 } 7952 7953 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 7954 // Derive the new package synthetic package name 7955 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 7956 + pkg.staticSharedLibVersion); 7957 } 7958 7959 private static String fixProcessName(String defProcessName, 7960 String processName) { 7961 if (processName == null) { 7962 return defProcessName; 7963 } 7964 return processName; 7965 } 7966 7967 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7968 throws PackageManagerException { 7969 if (pkgSetting.signatures.mSignatures != null) { 7970 // Already existing package. Make sure signatures match 7971 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7972 == PackageManager.SIGNATURE_MATCH; 7973 if (!match) { 7974 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7975 == PackageManager.SIGNATURE_MATCH; 7976 } 7977 if (!match) { 7978 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7979 == PackageManager.SIGNATURE_MATCH; 7980 } 7981 if (!match) { 7982 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7983 + pkg.packageName + " signatures do not match the " 7984 + "previously installed version; ignoring!"); 7985 } 7986 } 7987 7988 // Check for shared user signatures 7989 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7990 // Already existing package. Make sure signatures match 7991 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7992 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7993 if (!match) { 7994 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7995 == PackageManager.SIGNATURE_MATCH; 7996 } 7997 if (!match) { 7998 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7999 == PackageManager.SIGNATURE_MATCH; 8000 } 8001 if (!match) { 8002 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8003 "Package " + pkg.packageName 8004 + " has no signatures that match those in shared user " 8005 + pkgSetting.sharedUser.name + "; ignoring!"); 8006 } 8007 } 8008 } 8009 8010 /** 8011 * Enforces that only the system UID or root's UID can call a method exposed 8012 * via Binder. 8013 * 8014 * @param message used as message if SecurityException is thrown 8015 * @throws SecurityException if the caller is not system or root 8016 */ 8017 private static final void enforceSystemOrRoot(String message) { 8018 final int uid = Binder.getCallingUid(); 8019 if (uid != Process.SYSTEM_UID && uid != 0) { 8020 throw new SecurityException(message); 8021 } 8022 } 8023 8024 @Override 8025 public void performFstrimIfNeeded() { 8026 enforceSystemOrRoot("Only the system can request fstrim"); 8027 8028 // Before everything else, see whether we need to fstrim. 8029 try { 8030 IStorageManager sm = PackageHelper.getStorageManager(); 8031 if (sm != null) { 8032 boolean doTrim = false; 8033 final long interval = android.provider.Settings.Global.getLong( 8034 mContext.getContentResolver(), 8035 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8036 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8037 if (interval > 0) { 8038 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8039 if (timeSinceLast > interval) { 8040 doTrim = true; 8041 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8042 + "; running immediately"); 8043 } 8044 } 8045 if (doTrim) { 8046 final boolean dexOptDialogShown; 8047 synchronized (mPackages) { 8048 dexOptDialogShown = mDexOptDialogShown; 8049 } 8050 if (!isFirstBoot() && dexOptDialogShown) { 8051 try { 8052 ActivityManager.getService().showBootMessage( 8053 mContext.getResources().getString( 8054 R.string.android_upgrading_fstrim), true); 8055 } catch (RemoteException e) { 8056 } 8057 } 8058 sm.runMaintenance(); 8059 } 8060 } else { 8061 Slog.e(TAG, "storageManager service unavailable!"); 8062 } 8063 } catch (RemoteException e) { 8064 // Can't happen; StorageManagerService is local 8065 } 8066 } 8067 8068 @Override 8069 public void updatePackagesIfNeeded() { 8070 enforceSystemOrRoot("Only the system can request package update"); 8071 8072 // We need to re-extract after an OTA. 8073 boolean causeUpgrade = isUpgrade(); 8074 8075 // First boot or factory reset. 8076 // Note: we also handle devices that are upgrading to N right now as if it is their 8077 // first boot, as they do not have profile data. 8078 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8079 8080 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8081 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8082 8083 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8084 return; 8085 } 8086 8087 List<PackageParser.Package> pkgs; 8088 synchronized (mPackages) { 8089 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8090 } 8091 8092 final long startTime = System.nanoTime(); 8093 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8094 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8095 8096 final int elapsedTimeSeconds = 8097 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8098 8099 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8100 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8101 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8102 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8103 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8104 } 8105 8106 /** 8107 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8108 * containing statistics about the invocation. The array consists of three elements, 8109 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8110 * and {@code numberOfPackagesFailed}. 8111 */ 8112 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8113 String compilerFilter) { 8114 8115 int numberOfPackagesVisited = 0; 8116 int numberOfPackagesOptimized = 0; 8117 int numberOfPackagesSkipped = 0; 8118 int numberOfPackagesFailed = 0; 8119 final int numberOfPackagesToDexopt = pkgs.size(); 8120 8121 for (PackageParser.Package pkg : pkgs) { 8122 numberOfPackagesVisited++; 8123 8124 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8125 if (DEBUG_DEXOPT) { 8126 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8127 } 8128 numberOfPackagesSkipped++; 8129 continue; 8130 } 8131 8132 if (DEBUG_DEXOPT) { 8133 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8134 numberOfPackagesToDexopt + ": " + pkg.packageName); 8135 } 8136 8137 if (showDialog) { 8138 try { 8139 ActivityManager.getService().showBootMessage( 8140 mContext.getResources().getString(R.string.android_upgrading_apk, 8141 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8142 } catch (RemoteException e) { 8143 } 8144 synchronized (mPackages) { 8145 mDexOptDialogShown = true; 8146 } 8147 } 8148 8149 // If the OTA updates a system app which was previously preopted to a non-preopted state 8150 // the app might end up being verified at runtime. That's because by default the apps 8151 // are verify-profile but for preopted apps there's no profile. 8152 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8153 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8154 // filter (by default interpret-only). 8155 // Note that at this stage unused apps are already filtered. 8156 if (isSystemApp(pkg) && 8157 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8158 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8159 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8160 } 8161 8162 // checkProfiles is false to avoid merging profiles during boot which 8163 // might interfere with background compilation (b/28612421). 8164 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8165 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8166 // trade-off worth doing to save boot time work. 8167 int dexOptStatus = performDexOptTraced(pkg.packageName, 8168 false /* checkProfiles */, 8169 compilerFilter, 8170 false /* force */); 8171 switch (dexOptStatus) { 8172 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8173 numberOfPackagesOptimized++; 8174 break; 8175 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8176 numberOfPackagesSkipped++; 8177 break; 8178 case PackageDexOptimizer.DEX_OPT_FAILED: 8179 numberOfPackagesFailed++; 8180 break; 8181 default: 8182 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8183 break; 8184 } 8185 } 8186 8187 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8188 numberOfPackagesFailed }; 8189 } 8190 8191 @Override 8192 public void notifyPackageUse(String packageName, int reason) { 8193 synchronized (mPackages) { 8194 PackageParser.Package p = mPackages.get(packageName); 8195 if (p == null) { 8196 return; 8197 } 8198 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8199 } 8200 } 8201 8202 @Override 8203 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8204 int userId = UserHandle.getCallingUserId(); 8205 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8206 if (ai == null) { 8207 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8208 + loadingPackageName + ", user=" + userId); 8209 return; 8210 } 8211 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8212 } 8213 8214 // TODO: this is not used nor needed. Delete it. 8215 @Override 8216 public boolean performDexOptIfNeeded(String packageName) { 8217 int dexOptStatus = performDexOptTraced(packageName, 8218 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8219 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8220 } 8221 8222 @Override 8223 public boolean performDexOpt(String packageName, 8224 boolean checkProfiles, int compileReason, boolean force) { 8225 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8226 getCompilerFilterForReason(compileReason), force); 8227 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8228 } 8229 8230 @Override 8231 public boolean performDexOptMode(String packageName, 8232 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8233 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8234 targetCompilerFilter, force); 8235 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8236 } 8237 8238 private int performDexOptTraced(String packageName, 8239 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8240 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8241 try { 8242 return performDexOptInternal(packageName, checkProfiles, 8243 targetCompilerFilter, force); 8244 } finally { 8245 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8246 } 8247 } 8248 8249 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8250 // if the package can now be considered up to date for the given filter. 8251 private int performDexOptInternal(String packageName, 8252 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8253 PackageParser.Package p; 8254 synchronized (mPackages) { 8255 p = mPackages.get(packageName); 8256 if (p == null) { 8257 // Package could not be found. Report failure. 8258 return PackageDexOptimizer.DEX_OPT_FAILED; 8259 } 8260 mPackageUsage.maybeWriteAsync(mPackages); 8261 mCompilerStats.maybeWriteAsync(); 8262 } 8263 long callingId = Binder.clearCallingIdentity(); 8264 try { 8265 synchronized (mInstallLock) { 8266 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8267 targetCompilerFilter, force); 8268 } 8269 } finally { 8270 Binder.restoreCallingIdentity(callingId); 8271 } 8272 } 8273 8274 public ArraySet<String> getOptimizablePackages() { 8275 ArraySet<String> pkgs = new ArraySet<String>(); 8276 synchronized (mPackages) { 8277 for (PackageParser.Package p : mPackages.values()) { 8278 if (PackageDexOptimizer.canOptimizePackage(p)) { 8279 pkgs.add(p.packageName); 8280 } 8281 } 8282 } 8283 return pkgs; 8284 } 8285 8286 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8287 boolean checkProfiles, String targetCompilerFilter, 8288 boolean force) { 8289 // Select the dex optimizer based on the force parameter. 8290 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8291 // allocate an object here. 8292 PackageDexOptimizer pdo = force 8293 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8294 : mPackageDexOptimizer; 8295 8296 // Optimize all dependencies first. Note: we ignore the return value and march on 8297 // on errors. 8298 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8299 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8300 if (!deps.isEmpty()) { 8301 for (PackageParser.Package depPackage : deps) { 8302 // TODO: Analyze and investigate if we (should) profile libraries. 8303 // Currently this will do a full compilation of the library by default. 8304 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8305 false /* checkProfiles */, 8306 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8307 getOrCreateCompilerPackageStats(depPackage)); 8308 } 8309 } 8310 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8311 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8312 } 8313 8314 // Performs dexopt on the used secondary dex files belonging to the given package. 8315 // Returns true if all dex files were process successfully (which could mean either dexopt or 8316 // skip). Returns false if any of the files caused errors. 8317 @Override 8318 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8319 boolean force) { 8320 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8321 } 8322 8323 /** 8324 * Reconcile the information we have about the secondary dex files belonging to 8325 * {@code packagName} and the actual dex files. For all dex files that were 8326 * deleted, update the internal records and delete the generated oat files. 8327 */ 8328 @Override 8329 public void reconcileSecondaryDexFiles(String packageName) { 8330 mDexManager.reconcileSecondaryDexFiles(packageName); 8331 } 8332 8333 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8334 // a reference there. 8335 /*package*/ DexManager getDexManager() { 8336 return mDexManager; 8337 } 8338 8339 /** 8340 * Execute the background dexopt job immediately. 8341 */ 8342 @Override 8343 public boolean runBackgroundDexoptJob() { 8344 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8345 } 8346 8347 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8348 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8349 || p.usesStaticLibraries != null) { 8350 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8351 Set<String> collectedNames = new HashSet<>(); 8352 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8353 8354 retValue.remove(p); 8355 8356 return retValue; 8357 } else { 8358 return Collections.emptyList(); 8359 } 8360 } 8361 8362 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8363 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8364 if (!collectedNames.contains(p.packageName)) { 8365 collectedNames.add(p.packageName); 8366 collected.add(p); 8367 8368 if (p.usesLibraries != null) { 8369 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8370 null, collected, collectedNames); 8371 } 8372 if (p.usesOptionalLibraries != null) { 8373 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8374 null, collected, collectedNames); 8375 } 8376 if (p.usesStaticLibraries != null) { 8377 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8378 p.usesStaticLibrariesVersions, collected, collectedNames); 8379 } 8380 } 8381 } 8382 8383 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8384 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8385 final int libNameCount = libs.size(); 8386 for (int i = 0; i < libNameCount; i++) { 8387 String libName = libs.get(i); 8388 int version = (versions != null && versions.length == libNameCount) 8389 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8390 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8391 if (libPkg != null) { 8392 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8393 } 8394 } 8395 } 8396 8397 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8398 synchronized (mPackages) { 8399 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8400 if (libEntry != null) { 8401 return mPackages.get(libEntry.apk); 8402 } 8403 return null; 8404 } 8405 } 8406 8407 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8408 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8409 if (versionedLib == null) { 8410 return null; 8411 } 8412 return versionedLib.get(version); 8413 } 8414 8415 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8416 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8417 pkg.staticSharedLibName); 8418 if (versionedLib == null) { 8419 return null; 8420 } 8421 int previousLibVersion = -1; 8422 final int versionCount = versionedLib.size(); 8423 for (int i = 0; i < versionCount; i++) { 8424 final int libVersion = versionedLib.keyAt(i); 8425 if (libVersion < pkg.staticSharedLibVersion) { 8426 previousLibVersion = Math.max(previousLibVersion, libVersion); 8427 } 8428 } 8429 if (previousLibVersion >= 0) { 8430 return versionedLib.get(previousLibVersion); 8431 } 8432 return null; 8433 } 8434 8435 public void shutdown() { 8436 mPackageUsage.writeNow(mPackages); 8437 mCompilerStats.writeNow(); 8438 } 8439 8440 @Override 8441 public void dumpProfiles(String packageName) { 8442 PackageParser.Package pkg; 8443 synchronized (mPackages) { 8444 pkg = mPackages.get(packageName); 8445 if (pkg == null) { 8446 throw new IllegalArgumentException("Unknown package: " + packageName); 8447 } 8448 } 8449 /* Only the shell, root, or the app user should be able to dump profiles. */ 8450 int callingUid = Binder.getCallingUid(); 8451 if (callingUid != Process.SHELL_UID && 8452 callingUid != Process.ROOT_UID && 8453 callingUid != pkg.applicationInfo.uid) { 8454 throw new SecurityException("dumpProfiles"); 8455 } 8456 8457 synchronized (mInstallLock) { 8458 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8459 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8460 try { 8461 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8462 String codePaths = TextUtils.join(";", allCodePaths); 8463 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8464 } catch (InstallerException e) { 8465 Slog.w(TAG, "Failed to dump profiles", e); 8466 } 8467 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8468 } 8469 } 8470 8471 @Override 8472 public void forceDexOpt(String packageName) { 8473 enforceSystemOrRoot("forceDexOpt"); 8474 8475 PackageParser.Package pkg; 8476 synchronized (mPackages) { 8477 pkg = mPackages.get(packageName); 8478 if (pkg == null) { 8479 throw new IllegalArgumentException("Unknown package: " + packageName); 8480 } 8481 } 8482 8483 synchronized (mInstallLock) { 8484 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8485 8486 // Whoever is calling forceDexOpt wants a fully compiled package. 8487 // Don't use profiles since that may cause compilation to be skipped. 8488 final int res = performDexOptInternalWithDependenciesLI(pkg, 8489 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8490 true /* force */); 8491 8492 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8493 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8494 throw new IllegalStateException("Failed to dexopt: " + res); 8495 } 8496 } 8497 } 8498 8499 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8500 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8501 Slog.w(TAG, "Unable to update from " + oldPkg.name 8502 + " to " + newPkg.packageName 8503 + ": old package not in system partition"); 8504 return false; 8505 } else if (mPackages.get(oldPkg.name) != null) { 8506 Slog.w(TAG, "Unable to update from " + oldPkg.name 8507 + " to " + newPkg.packageName 8508 + ": old package still exists"); 8509 return false; 8510 } 8511 return true; 8512 } 8513 8514 void removeCodePathLI(File codePath) { 8515 if (codePath.isDirectory()) { 8516 try { 8517 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8518 } catch (InstallerException e) { 8519 Slog.w(TAG, "Failed to remove code path", e); 8520 } 8521 } else { 8522 codePath.delete(); 8523 } 8524 } 8525 8526 private int[] resolveUserIds(int userId) { 8527 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8528 } 8529 8530 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8531 if (pkg == null) { 8532 Slog.wtf(TAG, "Package was null!", new Throwable()); 8533 return; 8534 } 8535 clearAppDataLeafLIF(pkg, userId, flags); 8536 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8537 for (int i = 0; i < childCount; i++) { 8538 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8539 } 8540 } 8541 8542 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8543 final PackageSetting ps; 8544 synchronized (mPackages) { 8545 ps = mSettings.mPackages.get(pkg.packageName); 8546 } 8547 for (int realUserId : resolveUserIds(userId)) { 8548 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8549 try { 8550 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8551 ceDataInode); 8552 } catch (InstallerException e) { 8553 Slog.w(TAG, String.valueOf(e)); 8554 } 8555 } 8556 } 8557 8558 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8559 if (pkg == null) { 8560 Slog.wtf(TAG, "Package was null!", new Throwable()); 8561 return; 8562 } 8563 destroyAppDataLeafLIF(pkg, userId, flags); 8564 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8565 for (int i = 0; i < childCount; i++) { 8566 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8567 } 8568 } 8569 8570 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8571 final PackageSetting ps; 8572 synchronized (mPackages) { 8573 ps = mSettings.mPackages.get(pkg.packageName); 8574 } 8575 for (int realUserId : resolveUserIds(userId)) { 8576 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8577 try { 8578 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8579 ceDataInode); 8580 } catch (InstallerException e) { 8581 Slog.w(TAG, String.valueOf(e)); 8582 } 8583 } 8584 } 8585 8586 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8587 if (pkg == null) { 8588 Slog.wtf(TAG, "Package was null!", new Throwable()); 8589 return; 8590 } 8591 destroyAppProfilesLeafLIF(pkg); 8592 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8593 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8594 for (int i = 0; i < childCount; i++) { 8595 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8596 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8597 true /* removeBaseMarker */); 8598 } 8599 } 8600 8601 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8602 boolean removeBaseMarker) { 8603 if (pkg.isForwardLocked()) { 8604 return; 8605 } 8606 8607 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8608 try { 8609 path = PackageManagerServiceUtils.realpath(new File(path)); 8610 } catch (IOException e) { 8611 // TODO: Should we return early here ? 8612 Slog.w(TAG, "Failed to get canonical path", e); 8613 continue; 8614 } 8615 8616 final String useMarker = path.replace('/', '@'); 8617 for (int realUserId : resolveUserIds(userId)) { 8618 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8619 if (removeBaseMarker) { 8620 File foreignUseMark = new File(profileDir, useMarker); 8621 if (foreignUseMark.exists()) { 8622 if (!foreignUseMark.delete()) { 8623 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8624 + pkg.packageName); 8625 } 8626 } 8627 } 8628 8629 File[] markers = profileDir.listFiles(); 8630 if (markers != null) { 8631 final String searchString = "@" + pkg.packageName + "@"; 8632 // We also delete all markers that contain the package name we're 8633 // uninstalling. These are associated with secondary dex-files belonging 8634 // to the package. Reconstructing the path of these dex files is messy 8635 // in general. 8636 for (File marker : markers) { 8637 if (marker.getName().indexOf(searchString) > 0) { 8638 if (!marker.delete()) { 8639 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8640 + pkg.packageName); 8641 } 8642 } 8643 } 8644 } 8645 } 8646 } 8647 } 8648 8649 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8650 try { 8651 mInstaller.destroyAppProfiles(pkg.packageName); 8652 } catch (InstallerException e) { 8653 Slog.w(TAG, String.valueOf(e)); 8654 } 8655 } 8656 8657 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8658 if (pkg == null) { 8659 Slog.wtf(TAG, "Package was null!", new Throwable()); 8660 return; 8661 } 8662 clearAppProfilesLeafLIF(pkg); 8663 // We don't remove the base foreign use marker when clearing profiles because 8664 // we will rename it when the app is updated. Unlike the actual profile contents, 8665 // the foreign use marker is good across installs. 8666 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8667 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8668 for (int i = 0; i < childCount; i++) { 8669 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8670 } 8671 } 8672 8673 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8674 try { 8675 mInstaller.clearAppProfiles(pkg.packageName); 8676 } catch (InstallerException e) { 8677 Slog.w(TAG, String.valueOf(e)); 8678 } 8679 } 8680 8681 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8682 long lastUpdateTime) { 8683 // Set parent install/update time 8684 PackageSetting ps = (PackageSetting) pkg.mExtras; 8685 if (ps != null) { 8686 ps.firstInstallTime = firstInstallTime; 8687 ps.lastUpdateTime = lastUpdateTime; 8688 } 8689 // Set children install/update time 8690 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8691 for (int i = 0; i < childCount; i++) { 8692 PackageParser.Package childPkg = pkg.childPackages.get(i); 8693 ps = (PackageSetting) childPkg.mExtras; 8694 if (ps != null) { 8695 ps.firstInstallTime = firstInstallTime; 8696 ps.lastUpdateTime = lastUpdateTime; 8697 } 8698 } 8699 } 8700 8701 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8702 PackageParser.Package changingLib) { 8703 if (file.path != null) { 8704 usesLibraryFiles.add(file.path); 8705 return; 8706 } 8707 PackageParser.Package p = mPackages.get(file.apk); 8708 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8709 // If we are doing this while in the middle of updating a library apk, 8710 // then we need to make sure to use that new apk for determining the 8711 // dependencies here. (We haven't yet finished committing the new apk 8712 // to the package manager state.) 8713 if (p == null || p.packageName.equals(changingLib.packageName)) { 8714 p = changingLib; 8715 } 8716 } 8717 if (p != null) { 8718 usesLibraryFiles.addAll(p.getAllCodePaths()); 8719 } 8720 } 8721 8722 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8723 PackageParser.Package changingLib) throws PackageManagerException { 8724 if (pkg == null) { 8725 return; 8726 } 8727 ArraySet<String> usesLibraryFiles = null; 8728 if (pkg.usesLibraries != null) { 8729 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8730 null, null, pkg.packageName, changingLib, true, null); 8731 } 8732 if (pkg.usesStaticLibraries != null) { 8733 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8734 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8735 pkg.packageName, changingLib, true, usesLibraryFiles); 8736 } 8737 if (pkg.usesOptionalLibraries != null) { 8738 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8739 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8740 } 8741 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8742 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8743 } else { 8744 pkg.usesLibraryFiles = null; 8745 } 8746 } 8747 8748 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8749 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8750 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8751 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8752 throws PackageManagerException { 8753 final int libCount = requestedLibraries.size(); 8754 for (int i = 0; i < libCount; i++) { 8755 final String libName = requestedLibraries.get(i); 8756 final int libVersion = requiredVersions != null ? requiredVersions[i] 8757 : SharedLibraryInfo.VERSION_UNDEFINED; 8758 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8759 if (libEntry == null) { 8760 if (required) { 8761 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8762 "Package " + packageName + " requires unavailable shared library " 8763 + libName + "; failing!"); 8764 } else { 8765 Slog.w(TAG, "Package " + packageName 8766 + " desires unavailable shared library " 8767 + libName + "; ignoring!"); 8768 } 8769 } else { 8770 if (requiredVersions != null && requiredCertDigests != null) { 8771 if (libEntry.info.getVersion() != requiredVersions[i]) { 8772 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8773 "Package " + packageName + " requires unavailable static shared" 8774 + " library " + libName + " version " 8775 + libEntry.info.getVersion() + "; failing!"); 8776 } 8777 8778 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8779 if (libPkg == null) { 8780 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8781 "Package " + packageName + " requires unavailable static shared" 8782 + " library; failing!"); 8783 } 8784 8785 String expectedCertDigest = requiredCertDigests[i]; 8786 String libCertDigest = PackageUtils.computeCertSha256Digest( 8787 libPkg.mSignatures[0]); 8788 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8789 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8790 "Package " + packageName + " requires differently signed" + 8791 " static shared library; failing!"); 8792 } 8793 } 8794 8795 if (outUsedLibraries == null) { 8796 outUsedLibraries = new ArraySet<>(); 8797 } 8798 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8799 } 8800 } 8801 return outUsedLibraries; 8802 } 8803 8804 private static boolean hasString(List<String> list, List<String> which) { 8805 if (list == null) { 8806 return false; 8807 } 8808 for (int i=list.size()-1; i>=0; i--) { 8809 for (int j=which.size()-1; j>=0; j--) { 8810 if (which.get(j).equals(list.get(i))) { 8811 return true; 8812 } 8813 } 8814 } 8815 return false; 8816 } 8817 8818 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8819 PackageParser.Package changingPkg) { 8820 ArrayList<PackageParser.Package> res = null; 8821 for (PackageParser.Package pkg : mPackages.values()) { 8822 if (changingPkg != null 8823 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8824 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8825 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8826 changingPkg.staticSharedLibName)) { 8827 return null; 8828 } 8829 if (res == null) { 8830 res = new ArrayList<>(); 8831 } 8832 res.add(pkg); 8833 try { 8834 updateSharedLibrariesLPr(pkg, changingPkg); 8835 } catch (PackageManagerException e) { 8836 // If a system app update or an app and a required lib missing we 8837 // delete the package and for updated system apps keep the data as 8838 // it is better for the user to reinstall than to be in an limbo 8839 // state. Also libs disappearing under an app should never happen 8840 // - just in case. 8841 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8842 final int flags = pkg.isUpdatedSystemApp() 8843 ? PackageManager.DELETE_KEEP_DATA : 0; 8844 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8845 flags , null, true, null); 8846 } 8847 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8848 } 8849 } 8850 return res; 8851 } 8852 8853 /** 8854 * Derive the value of the {@code cpuAbiOverride} based on the provided 8855 * value and an optional stored value from the package settings. 8856 */ 8857 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8858 String cpuAbiOverride = null; 8859 8860 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8861 cpuAbiOverride = null; 8862 } else if (abiOverride != null) { 8863 cpuAbiOverride = abiOverride; 8864 } else if (settings != null) { 8865 cpuAbiOverride = settings.cpuAbiOverrideString; 8866 } 8867 8868 return cpuAbiOverride; 8869 } 8870 8871 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8872 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8873 throws PackageManagerException { 8874 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8875 // If the package has children and this is the first dive in the function 8876 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8877 // whether all packages (parent and children) would be successfully scanned 8878 // before the actual scan since scanning mutates internal state and we want 8879 // to atomically install the package and its children. 8880 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8881 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8882 scanFlags |= SCAN_CHECK_ONLY; 8883 } 8884 } else { 8885 scanFlags &= ~SCAN_CHECK_ONLY; 8886 } 8887 8888 final PackageParser.Package scannedPkg; 8889 try { 8890 // Scan the parent 8891 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8892 // Scan the children 8893 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8894 for (int i = 0; i < childCount; i++) { 8895 PackageParser.Package childPkg = pkg.childPackages.get(i); 8896 scanPackageLI(childPkg, policyFlags, 8897 scanFlags, currentTime, user); 8898 } 8899 } finally { 8900 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8901 } 8902 8903 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8904 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8905 } 8906 8907 return scannedPkg; 8908 } 8909 8910 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8911 int scanFlags, long currentTime, @Nullable UserHandle user) 8912 throws PackageManagerException { 8913 boolean success = false; 8914 try { 8915 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8916 currentTime, user); 8917 success = true; 8918 return res; 8919 } finally { 8920 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8921 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8922 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8923 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8924 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8925 } 8926 } 8927 } 8928 8929 /** 8930 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8931 */ 8932 private static boolean apkHasCode(String fileName) { 8933 StrictJarFile jarFile = null; 8934 try { 8935 jarFile = new StrictJarFile(fileName, 8936 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8937 return jarFile.findEntry("classes.dex") != null; 8938 } catch (IOException ignore) { 8939 } finally { 8940 try { 8941 if (jarFile != null) { 8942 jarFile.close(); 8943 } 8944 } catch (IOException ignore) {} 8945 } 8946 return false; 8947 } 8948 8949 /** 8950 * Enforces code policy for the package. This ensures that if an APK has 8951 * declared hasCode="true" in its manifest that the APK actually contains 8952 * code. 8953 * 8954 * @throws PackageManagerException If bytecode could not be found when it should exist 8955 */ 8956 private static void assertCodePolicy(PackageParser.Package pkg) 8957 throws PackageManagerException { 8958 final boolean shouldHaveCode = 8959 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8960 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8961 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8962 "Package " + pkg.baseCodePath + " code is missing"); 8963 } 8964 8965 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8966 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8967 final boolean splitShouldHaveCode = 8968 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8969 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8970 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8971 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8972 } 8973 } 8974 } 8975 } 8976 8977 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8978 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 8979 throws PackageManagerException { 8980 if (DEBUG_PACKAGE_SCANNING) { 8981 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8982 Log.d(TAG, "Scanning package " + pkg.packageName); 8983 } 8984 8985 applyPolicy(pkg, policyFlags); 8986 8987 assertPackageIsValid(pkg, policyFlags, scanFlags); 8988 8989 // Initialize package source and resource directories 8990 final File scanFile = new File(pkg.codePath); 8991 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8992 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8993 8994 SharedUserSetting suid = null; 8995 PackageSetting pkgSetting = null; 8996 8997 // Getting the package setting may have a side-effect, so if we 8998 // are only checking if scan would succeed, stash a copy of the 8999 // old setting to restore at the end. 9000 PackageSetting nonMutatedPs = null; 9001 9002 // We keep references to the derived CPU Abis from settings in oder to reuse 9003 // them in the case where we're not upgrading or booting for the first time. 9004 String primaryCpuAbiFromSettings = null; 9005 String secondaryCpuAbiFromSettings = null; 9006 9007 // writer 9008 synchronized (mPackages) { 9009 if (pkg.mSharedUserId != null) { 9010 // SIDE EFFECTS; may potentially allocate a new shared user 9011 suid = mSettings.getSharedUserLPw( 9012 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9013 if (DEBUG_PACKAGE_SCANNING) { 9014 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9015 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9016 + "): packages=" + suid.packages); 9017 } 9018 } 9019 9020 // Check if we are renaming from an original package name. 9021 PackageSetting origPackage = null; 9022 String realName = null; 9023 if (pkg.mOriginalPackages != null) { 9024 // This package may need to be renamed to a previously 9025 // installed name. Let's check on that... 9026 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9027 if (pkg.mOriginalPackages.contains(renamed)) { 9028 // This package had originally been installed as the 9029 // original name, and we have already taken care of 9030 // transitioning to the new one. Just update the new 9031 // one to continue using the old name. 9032 realName = pkg.mRealPackage; 9033 if (!pkg.packageName.equals(renamed)) { 9034 // Callers into this function may have already taken 9035 // care of renaming the package; only do it here if 9036 // it is not already done. 9037 pkg.setPackageName(renamed); 9038 } 9039 } else { 9040 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9041 if ((origPackage = mSettings.getPackageLPr( 9042 pkg.mOriginalPackages.get(i))) != null) { 9043 // We do have the package already installed under its 9044 // original name... should we use it? 9045 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9046 // New package is not compatible with original. 9047 origPackage = null; 9048 continue; 9049 } else if (origPackage.sharedUser != null) { 9050 // Make sure uid is compatible between packages. 9051 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9052 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9053 + " to " + pkg.packageName + ": old uid " 9054 + origPackage.sharedUser.name 9055 + " differs from " + pkg.mSharedUserId); 9056 origPackage = null; 9057 continue; 9058 } 9059 // TODO: Add case when shared user id is added [b/28144775] 9060 } else { 9061 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9062 + pkg.packageName + " to old name " + origPackage.name); 9063 } 9064 break; 9065 } 9066 } 9067 } 9068 } 9069 9070 if (mTransferedPackages.contains(pkg.packageName)) { 9071 Slog.w(TAG, "Package " + pkg.packageName 9072 + " was transferred to another, but its .apk remains"); 9073 } 9074 9075 // See comments in nonMutatedPs declaration 9076 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9077 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9078 if (foundPs != null) { 9079 nonMutatedPs = new PackageSetting(foundPs); 9080 } 9081 } 9082 9083 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9084 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9085 if (foundPs != null) { 9086 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9087 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9088 } 9089 } 9090 9091 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9092 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9093 PackageManagerService.reportSettingsProblem(Log.WARN, 9094 "Package " + pkg.packageName + " shared user changed from " 9095 + (pkgSetting.sharedUser != null 9096 ? pkgSetting.sharedUser.name : "<nothing>") 9097 + " to " 9098 + (suid != null ? suid.name : "<nothing>") 9099 + "; replacing with new"); 9100 pkgSetting = null; 9101 } 9102 final PackageSetting oldPkgSetting = 9103 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9104 final PackageSetting disabledPkgSetting = 9105 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9106 9107 String[] usesStaticLibraries = null; 9108 if (pkg.usesStaticLibraries != null) { 9109 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9110 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9111 } 9112 9113 if (pkgSetting == null) { 9114 final String parentPackageName = (pkg.parentPackage != null) 9115 ? pkg.parentPackage.packageName : null; 9116 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9117 // REMOVE SharedUserSetting from method; update in a separate call 9118 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9119 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9120 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9121 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9122 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9123 true /*allowInstall*/, instantApp, parentPackageName, 9124 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9125 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9126 // SIDE EFFECTS; updates system state; move elsewhere 9127 if (origPackage != null) { 9128 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9129 } 9130 mSettings.addUserToSettingLPw(pkgSetting); 9131 } else { 9132 // REMOVE SharedUserSetting from method; update in a separate call. 9133 // 9134 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9135 // secondaryCpuAbi are not known at this point so we always update them 9136 // to null here, only to reset them at a later point. 9137 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9138 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9139 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9140 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9141 UserManagerService.getInstance(), usesStaticLibraries, 9142 pkg.usesStaticLibrariesVersions); 9143 } 9144 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9145 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9146 9147 // SIDE EFFECTS; modifies system state; move elsewhere 9148 if (pkgSetting.origPackage != null) { 9149 // If we are first transitioning from an original package, 9150 // fix up the new package's name now. We need to do this after 9151 // looking up the package under its new name, so getPackageLP 9152 // can take care of fiddling things correctly. 9153 pkg.setPackageName(origPackage.name); 9154 9155 // File a report about this. 9156 String msg = "New package " + pkgSetting.realName 9157 + " renamed to replace old package " + pkgSetting.name; 9158 reportSettingsProblem(Log.WARN, msg); 9159 9160 // Make a note of it. 9161 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9162 mTransferedPackages.add(origPackage.name); 9163 } 9164 9165 // No longer need to retain this. 9166 pkgSetting.origPackage = null; 9167 } 9168 9169 // SIDE EFFECTS; modifies system state; move elsewhere 9170 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9171 // Make a note of it. 9172 mTransferedPackages.add(pkg.packageName); 9173 } 9174 9175 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9176 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9177 } 9178 9179 if ((scanFlags & SCAN_BOOTING) == 0 9180 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9181 // Check all shared libraries and map to their actual file path. 9182 // We only do this here for apps not on a system dir, because those 9183 // are the only ones that can fail an install due to this. We 9184 // will take care of the system apps by updating all of their 9185 // library paths after the scan is done. Also during the initial 9186 // scan don't update any libs as we do this wholesale after all 9187 // apps are scanned to avoid dependency based scanning. 9188 updateSharedLibrariesLPr(pkg, null); 9189 } 9190 9191 if (mFoundPolicyFile) { 9192 SELinuxMMAC.assignSeInfoValue(pkg); 9193 } 9194 pkg.applicationInfo.uid = pkgSetting.appId; 9195 pkg.mExtras = pkgSetting; 9196 9197 9198 // Static shared libs have same package with different versions where 9199 // we internally use a synthetic package name to allow multiple versions 9200 // of the same package, therefore we need to compare signatures against 9201 // the package setting for the latest library version. 9202 PackageSetting signatureCheckPs = pkgSetting; 9203 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9204 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9205 if (libraryEntry != null) { 9206 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9207 } 9208 } 9209 9210 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9211 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9212 // We just determined the app is signed correctly, so bring 9213 // over the latest parsed certs. 9214 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9215 } else { 9216 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9217 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9218 "Package " + pkg.packageName + " upgrade keys do not match the " 9219 + "previously installed version"); 9220 } else { 9221 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9222 String msg = "System package " + pkg.packageName 9223 + " signature changed; retaining data."; 9224 reportSettingsProblem(Log.WARN, msg); 9225 } 9226 } 9227 } else { 9228 try { 9229 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9230 verifySignaturesLP(signatureCheckPs, pkg); 9231 // We just determined the app is signed correctly, so bring 9232 // over the latest parsed certs. 9233 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9234 } catch (PackageManagerException e) { 9235 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9236 throw e; 9237 } 9238 // The signature has changed, but this package is in the system 9239 // image... let's recover! 9240 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9241 // However... if this package is part of a shared user, but it 9242 // doesn't match the signature of the shared user, let's fail. 9243 // What this means is that you can't change the signatures 9244 // associated with an overall shared user, which doesn't seem all 9245 // that unreasonable. 9246 if (signatureCheckPs.sharedUser != null) { 9247 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9248 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9249 throw new PackageManagerException( 9250 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9251 "Signature mismatch for shared user: " 9252 + pkgSetting.sharedUser); 9253 } 9254 } 9255 // File a report about this. 9256 String msg = "System package " + pkg.packageName 9257 + " signature changed; retaining data."; 9258 reportSettingsProblem(Log.WARN, msg); 9259 } 9260 } 9261 9262 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9263 // This package wants to adopt ownership of permissions from 9264 // another package. 9265 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9266 final String origName = pkg.mAdoptPermissions.get(i); 9267 final PackageSetting orig = mSettings.getPackageLPr(origName); 9268 if (orig != null) { 9269 if (verifyPackageUpdateLPr(orig, pkg)) { 9270 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9271 + pkg.packageName); 9272 // SIDE EFFECTS; updates permissions system state; move elsewhere 9273 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9274 } 9275 } 9276 } 9277 } 9278 } 9279 9280 pkg.applicationInfo.processName = fixProcessName( 9281 pkg.applicationInfo.packageName, 9282 pkg.applicationInfo.processName); 9283 9284 if (pkg != mPlatformPackage) { 9285 // Get all of our default paths setup 9286 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9287 } 9288 9289 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9290 9291 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9292 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9293 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9294 derivePackageAbi( 9295 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9297 9298 // Some system apps still use directory structure for native libraries 9299 // in which case we might end up not detecting abi solely based on apk 9300 // structure. Try to detect abi based on directory structure. 9301 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9302 pkg.applicationInfo.primaryCpuAbi == null) { 9303 setBundledAppAbisAndRoots(pkg, pkgSetting); 9304 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9305 } 9306 } else { 9307 // This is not a first boot or an upgrade, don't bother deriving the 9308 // ABI during the scan. Instead, trust the value that was stored in the 9309 // package setting. 9310 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9311 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9312 9313 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9314 9315 if (DEBUG_ABI_SELECTION) { 9316 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9317 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9318 pkg.applicationInfo.secondaryCpuAbi); 9319 } 9320 } 9321 } else { 9322 if ((scanFlags & SCAN_MOVE) != 0) { 9323 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9324 // but we already have this packages package info in the PackageSetting. We just 9325 // use that and derive the native library path based on the new codepath. 9326 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9327 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9328 } 9329 9330 // Set native library paths again. For moves, the path will be updated based on the 9331 // ABIs we've determined above. For non-moves, the path will be updated based on the 9332 // ABIs we determined during compilation, but the path will depend on the final 9333 // package path (after the rename away from the stage path). 9334 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9335 } 9336 9337 // This is a special case for the "system" package, where the ABI is 9338 // dictated by the zygote configuration (and init.rc). We should keep track 9339 // of this ABI so that we can deal with "normal" applications that run under 9340 // the same UID correctly. 9341 if (mPlatformPackage == pkg) { 9342 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9343 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9344 } 9345 9346 // If there's a mismatch between the abi-override in the package setting 9347 // and the abiOverride specified for the install. Warn about this because we 9348 // would've already compiled the app without taking the package setting into 9349 // account. 9350 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9351 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9352 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9353 " for package " + pkg.packageName); 9354 } 9355 } 9356 9357 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9358 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9359 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9360 9361 // Copy the derived override back to the parsed package, so that we can 9362 // update the package settings accordingly. 9363 pkg.cpuAbiOverride = cpuAbiOverride; 9364 9365 if (DEBUG_ABI_SELECTION) { 9366 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9367 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9368 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9369 } 9370 9371 // Push the derived path down into PackageSettings so we know what to 9372 // clean up at uninstall time. 9373 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9374 9375 if (DEBUG_ABI_SELECTION) { 9376 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9377 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9378 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9379 } 9380 9381 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9382 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9383 // We don't do this here during boot because we can do it all 9384 // at once after scanning all existing packages. 9385 // 9386 // We also do this *before* we perform dexopt on this package, so that 9387 // we can avoid redundant dexopts, and also to make sure we've got the 9388 // code and package path correct. 9389 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9390 } 9391 9392 if (mFactoryTest && pkg.requestedPermissions.contains( 9393 android.Manifest.permission.FACTORY_TEST)) { 9394 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9395 } 9396 9397 if (isSystemApp(pkg)) { 9398 pkgSetting.isOrphaned = true; 9399 } 9400 9401 // Take care of first install / last update times. 9402 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9403 if (currentTime != 0) { 9404 if (pkgSetting.firstInstallTime == 0) { 9405 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9406 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9407 pkgSetting.lastUpdateTime = currentTime; 9408 } 9409 } else if (pkgSetting.firstInstallTime == 0) { 9410 // We need *something*. Take time time stamp of the file. 9411 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9412 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9413 if (scanFileTime != pkgSetting.timeStamp) { 9414 // A package on the system image has changed; consider this 9415 // to be an update. 9416 pkgSetting.lastUpdateTime = scanFileTime; 9417 } 9418 } 9419 pkgSetting.setTimeStamp(scanFileTime); 9420 9421 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9422 if (nonMutatedPs != null) { 9423 synchronized (mPackages) { 9424 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9425 } 9426 } 9427 } else { 9428 final int userId = user == null ? 0 : user.getIdentifier(); 9429 // Modify state for the given package setting 9430 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9431 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9432 if (pkgSetting.getInstantApp(userId)) { 9433 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9434 } 9435 } 9436 return pkg; 9437 } 9438 9439 /** 9440 * Applies policy to the parsed package based upon the given policy flags. 9441 * Ensures the package is in a good state. 9442 * <p> 9443 * Implementation detail: This method must NOT have any side effect. It would 9444 * ideally be static, but, it requires locks to read system state. 9445 */ 9446 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9447 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9448 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9449 if (pkg.applicationInfo.isDirectBootAware()) { 9450 // we're direct boot aware; set for all components 9451 for (PackageParser.Service s : pkg.services) { 9452 s.info.encryptionAware = s.info.directBootAware = true; 9453 } 9454 for (PackageParser.Provider p : pkg.providers) { 9455 p.info.encryptionAware = p.info.directBootAware = true; 9456 } 9457 for (PackageParser.Activity a : pkg.activities) { 9458 a.info.encryptionAware = a.info.directBootAware = true; 9459 } 9460 for (PackageParser.Activity r : pkg.receivers) { 9461 r.info.encryptionAware = r.info.directBootAware = true; 9462 } 9463 } 9464 } else { 9465 // Only allow system apps to be flagged as core apps. 9466 pkg.coreApp = false; 9467 // clear flags not applicable to regular apps 9468 pkg.applicationInfo.privateFlags &= 9469 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9470 pkg.applicationInfo.privateFlags &= 9471 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9472 } 9473 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9474 9475 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9476 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9477 } 9478 9479 if (!isSystemApp(pkg)) { 9480 // Only system apps can use these features. 9481 pkg.mOriginalPackages = null; 9482 pkg.mRealPackage = null; 9483 pkg.mAdoptPermissions = null; 9484 } 9485 } 9486 9487 /** 9488 * Asserts the parsed package is valid according to the given policy. If the 9489 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9490 * <p> 9491 * Implementation detail: This method must NOT have any side effects. It would 9492 * ideally be static, but, it requires locks to read system state. 9493 * 9494 * @throws PackageManagerException If the package fails any of the validation checks 9495 */ 9496 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9497 throws PackageManagerException { 9498 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9499 assertCodePolicy(pkg); 9500 } 9501 9502 if (pkg.applicationInfo.getCodePath() == null || 9503 pkg.applicationInfo.getResourcePath() == null) { 9504 // Bail out. The resource and code paths haven't been set. 9505 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9506 "Code and resource paths haven't been set correctly"); 9507 } 9508 9509 // Make sure we're not adding any bogus keyset info 9510 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9511 ksms.assertScannedPackageValid(pkg); 9512 9513 synchronized (mPackages) { 9514 // The special "android" package can only be defined once 9515 if (pkg.packageName.equals("android")) { 9516 if (mAndroidApplication != null) { 9517 Slog.w(TAG, "*************************************************"); 9518 Slog.w(TAG, "Core android package being redefined. Skipping."); 9519 Slog.w(TAG, " codePath=" + pkg.codePath); 9520 Slog.w(TAG, "*************************************************"); 9521 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9522 "Core android package being redefined. Skipping."); 9523 } 9524 } 9525 9526 // A package name must be unique; don't allow duplicates 9527 if (mPackages.containsKey(pkg.packageName)) { 9528 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9529 "Application package " + pkg.packageName 9530 + " already installed. Skipping duplicate."); 9531 } 9532 9533 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9534 // Static libs have a synthetic package name containing the version 9535 // but we still want the base name to be unique. 9536 if (mPackages.containsKey(pkg.manifestPackageName)) { 9537 throw new PackageManagerException( 9538 "Duplicate static shared lib provider package"); 9539 } 9540 9541 // Static shared libraries should have at least O target SDK 9542 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9543 throw new PackageManagerException( 9544 "Packages declaring static-shared libs must target O SDK or higher"); 9545 } 9546 9547 // Package declaring static a shared lib cannot be instant apps 9548 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9549 throw new PackageManagerException( 9550 "Packages declaring static-shared libs cannot be instant apps"); 9551 } 9552 9553 // Package declaring static a shared lib cannot be renamed since the package 9554 // name is synthetic and apps can't code around package manager internals. 9555 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9556 throw new PackageManagerException( 9557 "Packages declaring static-shared libs cannot be renamed"); 9558 } 9559 9560 // Package declaring static a shared lib cannot declare child packages 9561 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9562 throw new PackageManagerException( 9563 "Packages declaring static-shared libs cannot have child packages"); 9564 } 9565 9566 // Package declaring static a shared lib cannot declare dynamic libs 9567 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9568 throw new PackageManagerException( 9569 "Packages declaring static-shared libs cannot declare dynamic libs"); 9570 } 9571 9572 // Package declaring static a shared lib cannot declare shared users 9573 if (pkg.mSharedUserId != null) { 9574 throw new PackageManagerException( 9575 "Packages declaring static-shared libs cannot declare shared users"); 9576 } 9577 9578 // Static shared libs cannot declare activities 9579 if (!pkg.activities.isEmpty()) { 9580 throw new PackageManagerException( 9581 "Static shared libs cannot declare activities"); 9582 } 9583 9584 // Static shared libs cannot declare services 9585 if (!pkg.services.isEmpty()) { 9586 throw new PackageManagerException( 9587 "Static shared libs cannot declare services"); 9588 } 9589 9590 // Static shared libs cannot declare providers 9591 if (!pkg.providers.isEmpty()) { 9592 throw new PackageManagerException( 9593 "Static shared libs cannot declare content providers"); 9594 } 9595 9596 // Static shared libs cannot declare receivers 9597 if (!pkg.receivers.isEmpty()) { 9598 throw new PackageManagerException( 9599 "Static shared libs cannot declare broadcast receivers"); 9600 } 9601 9602 // Static shared libs cannot declare permission groups 9603 if (!pkg.permissionGroups.isEmpty()) { 9604 throw new PackageManagerException( 9605 "Static shared libs cannot declare permission groups"); 9606 } 9607 9608 // Static shared libs cannot declare permissions 9609 if (!pkg.permissions.isEmpty()) { 9610 throw new PackageManagerException( 9611 "Static shared libs cannot declare permissions"); 9612 } 9613 9614 // Static shared libs cannot declare protected broadcasts 9615 if (pkg.protectedBroadcasts != null) { 9616 throw new PackageManagerException( 9617 "Static shared libs cannot declare protected broadcasts"); 9618 } 9619 9620 // Static shared libs cannot be overlay targets 9621 if (pkg.mOverlayTarget != null) { 9622 throw new PackageManagerException( 9623 "Static shared libs cannot be overlay targets"); 9624 } 9625 9626 // The version codes must be ordered as lib versions 9627 int minVersionCode = Integer.MIN_VALUE; 9628 int maxVersionCode = Integer.MAX_VALUE; 9629 9630 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9631 pkg.staticSharedLibName); 9632 if (versionedLib != null) { 9633 final int versionCount = versionedLib.size(); 9634 for (int i = 0; i < versionCount; i++) { 9635 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9636 // TODO: We will change version code to long, so in the new API it is long 9637 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9638 .getVersionCode(); 9639 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9640 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9641 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9642 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9643 } else { 9644 minVersionCode = maxVersionCode = libVersionCode; 9645 break; 9646 } 9647 } 9648 } 9649 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9650 throw new PackageManagerException("Static shared" 9651 + " lib version codes must be ordered as lib versions"); 9652 } 9653 } 9654 9655 // Only privileged apps and updated privileged apps can add child packages. 9656 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9657 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9658 throw new PackageManagerException("Only privileged apps can add child " 9659 + "packages. Ignoring package " + pkg.packageName); 9660 } 9661 final int childCount = pkg.childPackages.size(); 9662 for (int i = 0; i < childCount; i++) { 9663 PackageParser.Package childPkg = pkg.childPackages.get(i); 9664 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9665 childPkg.packageName)) { 9666 throw new PackageManagerException("Can't override child of " 9667 + "another disabled app. Ignoring package " + pkg.packageName); 9668 } 9669 } 9670 } 9671 9672 // If we're only installing presumed-existing packages, require that the 9673 // scanned APK is both already known and at the path previously established 9674 // for it. Previously unknown packages we pick up normally, but if we have an 9675 // a priori expectation about this package's install presence, enforce it. 9676 // With a singular exception for new system packages. When an OTA contains 9677 // a new system package, we allow the codepath to change from a system location 9678 // to the user-installed location. If we don't allow this change, any newer, 9679 // user-installed version of the application will be ignored. 9680 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9681 if (mExpectingBetter.containsKey(pkg.packageName)) { 9682 logCriticalInfo(Log.WARN, 9683 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9684 } else { 9685 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9686 if (known != null) { 9687 if (DEBUG_PACKAGE_SCANNING) { 9688 Log.d(TAG, "Examining " + pkg.codePath 9689 + " and requiring known paths " + known.codePathString 9690 + " & " + known.resourcePathString); 9691 } 9692 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9693 || !pkg.applicationInfo.getResourcePath().equals( 9694 known.resourcePathString)) { 9695 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9696 "Application package " + pkg.packageName 9697 + " found at " + pkg.applicationInfo.getCodePath() 9698 + " but expected at " + known.codePathString 9699 + "; ignoring."); 9700 } 9701 } 9702 } 9703 } 9704 9705 // Verify that this new package doesn't have any content providers 9706 // that conflict with existing packages. Only do this if the 9707 // package isn't already installed, since we don't want to break 9708 // things that are installed. 9709 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9710 final int N = pkg.providers.size(); 9711 int i; 9712 for (i=0; i<N; i++) { 9713 PackageParser.Provider p = pkg.providers.get(i); 9714 if (p.info.authority != null) { 9715 String names[] = p.info.authority.split(";"); 9716 for (int j = 0; j < names.length; j++) { 9717 if (mProvidersByAuthority.containsKey(names[j])) { 9718 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9719 final String otherPackageName = 9720 ((other != null && other.getComponentName() != null) ? 9721 other.getComponentName().getPackageName() : "?"); 9722 throw new PackageManagerException( 9723 INSTALL_FAILED_CONFLICTING_PROVIDER, 9724 "Can't install because provider name " + names[j] 9725 + " (in package " + pkg.applicationInfo.packageName 9726 + ") is already used by " + otherPackageName); 9727 } 9728 } 9729 } 9730 } 9731 } 9732 } 9733 } 9734 9735 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9736 int type, String declaringPackageName, int declaringVersionCode) { 9737 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9738 if (versionedLib == null) { 9739 versionedLib = new SparseArray<>(); 9740 mSharedLibraries.put(name, versionedLib); 9741 if (type == SharedLibraryInfo.TYPE_STATIC) { 9742 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9743 } 9744 } else if (versionedLib.indexOfKey(version) >= 0) { 9745 return false; 9746 } 9747 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9748 version, type, declaringPackageName, declaringVersionCode); 9749 versionedLib.put(version, libEntry); 9750 return true; 9751 } 9752 9753 private boolean removeSharedLibraryLPw(String name, int version) { 9754 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9755 if (versionedLib == null) { 9756 return false; 9757 } 9758 final int libIdx = versionedLib.indexOfKey(version); 9759 if (libIdx < 0) { 9760 return false; 9761 } 9762 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9763 versionedLib.remove(version); 9764 if (versionedLib.size() <= 0) { 9765 mSharedLibraries.remove(name); 9766 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9767 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9768 .getPackageName()); 9769 } 9770 } 9771 return true; 9772 } 9773 9774 /** 9775 * Adds a scanned package to the system. When this method is finished, the package will 9776 * be available for query, resolution, etc... 9777 */ 9778 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9779 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9780 final String pkgName = pkg.packageName; 9781 if (mCustomResolverComponentName != null && 9782 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9783 setUpCustomResolverActivity(pkg); 9784 } 9785 9786 if (pkg.packageName.equals("android")) { 9787 synchronized (mPackages) { 9788 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9789 // Set up information for our fall-back user intent resolution activity. 9790 mPlatformPackage = pkg; 9791 pkg.mVersionCode = mSdkVersion; 9792 mAndroidApplication = pkg.applicationInfo; 9793 if (!mResolverReplaced) { 9794 mResolveActivity.applicationInfo = mAndroidApplication; 9795 mResolveActivity.name = ResolverActivity.class.getName(); 9796 mResolveActivity.packageName = mAndroidApplication.packageName; 9797 mResolveActivity.processName = "system:ui"; 9798 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9799 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9800 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9801 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9802 mResolveActivity.exported = true; 9803 mResolveActivity.enabled = true; 9804 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9805 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9806 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9807 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9808 | ActivityInfo.CONFIG_ORIENTATION 9809 | ActivityInfo.CONFIG_KEYBOARD 9810 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9811 mResolveInfo.activityInfo = mResolveActivity; 9812 mResolveInfo.priority = 0; 9813 mResolveInfo.preferredOrder = 0; 9814 mResolveInfo.match = 0; 9815 mResolveComponentName = new ComponentName( 9816 mAndroidApplication.packageName, mResolveActivity.name); 9817 } 9818 } 9819 } 9820 } 9821 9822 ArrayList<PackageParser.Package> clientLibPkgs = null; 9823 // writer 9824 synchronized (mPackages) { 9825 boolean hasStaticSharedLibs = false; 9826 9827 // Any app can add new static shared libraries 9828 if (pkg.staticSharedLibName != null) { 9829 // Static shared libs don't allow renaming as they have synthetic package 9830 // names to allow install of multiple versions, so use name from manifest. 9831 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9832 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9833 pkg.manifestPackageName, pkg.mVersionCode)) { 9834 hasStaticSharedLibs = true; 9835 } else { 9836 Slog.w(TAG, "Package " + pkg.packageName + " library " 9837 + pkg.staticSharedLibName + " already exists; skipping"); 9838 } 9839 // Static shared libs cannot be updated once installed since they 9840 // use synthetic package name which includes the version code, so 9841 // not need to update other packages's shared lib dependencies. 9842 } 9843 9844 if (!hasStaticSharedLibs 9845 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9846 // Only system apps can add new dynamic shared libraries. 9847 if (pkg.libraryNames != null) { 9848 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9849 String name = pkg.libraryNames.get(i); 9850 boolean allowed = false; 9851 if (pkg.isUpdatedSystemApp()) { 9852 // New library entries can only be added through the 9853 // system image. This is important to get rid of a lot 9854 // of nasty edge cases: for example if we allowed a non- 9855 // system update of the app to add a library, then uninstalling 9856 // the update would make the library go away, and assumptions 9857 // we made such as through app install filtering would now 9858 // have allowed apps on the device which aren't compatible 9859 // with it. Better to just have the restriction here, be 9860 // conservative, and create many fewer cases that can negatively 9861 // impact the user experience. 9862 final PackageSetting sysPs = mSettings 9863 .getDisabledSystemPkgLPr(pkg.packageName); 9864 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9865 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9866 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9867 allowed = true; 9868 break; 9869 } 9870 } 9871 } 9872 } else { 9873 allowed = true; 9874 } 9875 if (allowed) { 9876 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9877 SharedLibraryInfo.VERSION_UNDEFINED, 9878 SharedLibraryInfo.TYPE_DYNAMIC, 9879 pkg.packageName, pkg.mVersionCode)) { 9880 Slog.w(TAG, "Package " + pkg.packageName + " library " 9881 + name + " already exists; skipping"); 9882 } 9883 } else { 9884 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9885 + name + " that is not declared on system image; skipping"); 9886 } 9887 } 9888 9889 if ((scanFlags & SCAN_BOOTING) == 0) { 9890 // If we are not booting, we need to update any applications 9891 // that are clients of our shared library. If we are booting, 9892 // this will all be done once the scan is complete. 9893 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9894 } 9895 } 9896 } 9897 } 9898 9899 if ((scanFlags & SCAN_BOOTING) != 0) { 9900 // No apps can run during boot scan, so they don't need to be frozen 9901 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9902 // Caller asked to not kill app, so it's probably not frozen 9903 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9904 // Caller asked us to ignore frozen check for some reason; they 9905 // probably didn't know the package name 9906 } else { 9907 // We're doing major surgery on this package, so it better be frozen 9908 // right now to keep it from launching 9909 checkPackageFrozen(pkgName); 9910 } 9911 9912 // Also need to kill any apps that are dependent on the library. 9913 if (clientLibPkgs != null) { 9914 for (int i=0; i<clientLibPkgs.size(); i++) { 9915 PackageParser.Package clientPkg = clientLibPkgs.get(i); 9916 killApplication(clientPkg.applicationInfo.packageName, 9917 clientPkg.applicationInfo.uid, "update lib"); 9918 } 9919 } 9920 9921 // writer 9922 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 9923 9924 boolean createIdmapFailed = false; 9925 synchronized (mPackages) { 9926 // We don't expect installation to fail beyond this point 9927 9928 if (pkgSetting.pkg != null) { 9929 // Note that |user| might be null during the initial boot scan. If a codePath 9930 // for an app has changed during a boot scan, it's due to an app update that's 9931 // part of the system partition and marker changes must be applied to all users. 9932 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 9933 final int[] userIds = resolveUserIds(userId); 9934 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 9935 } 9936 9937 // Add the new setting to mSettings 9938 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 9939 // Add the new setting to mPackages 9940 mPackages.put(pkg.applicationInfo.packageName, pkg); 9941 // Make sure we don't accidentally delete its data. 9942 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 9943 while (iter.hasNext()) { 9944 PackageCleanItem item = iter.next(); 9945 if (pkgName.equals(item.packageName)) { 9946 iter.remove(); 9947 } 9948 } 9949 9950 // Add the package's KeySets to the global KeySetManagerService 9951 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9952 ksms.addScannedPackageLPw(pkg); 9953 9954 int N = pkg.providers.size(); 9955 StringBuilder r = null; 9956 int i; 9957 for (i=0; i<N; i++) { 9958 PackageParser.Provider p = pkg.providers.get(i); 9959 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 9960 p.info.processName); 9961 mProviders.addProvider(p); 9962 p.syncable = p.info.isSyncable; 9963 if (p.info.authority != null) { 9964 String names[] = p.info.authority.split(";"); 9965 p.info.authority = null; 9966 for (int j = 0; j < names.length; j++) { 9967 if (j == 1 && p.syncable) { 9968 // We only want the first authority for a provider to possibly be 9969 // syncable, so if we already added this provider using a different 9970 // authority clear the syncable flag. We copy the provider before 9971 // changing it because the mProviders object contains a reference 9972 // to a provider that we don't want to change. 9973 // Only do this for the second authority since the resulting provider 9974 // object can be the same for all future authorities for this provider. 9975 p = new PackageParser.Provider(p); 9976 p.syncable = false; 9977 } 9978 if (!mProvidersByAuthority.containsKey(names[j])) { 9979 mProvidersByAuthority.put(names[j], p); 9980 if (p.info.authority == null) { 9981 p.info.authority = names[j]; 9982 } else { 9983 p.info.authority = p.info.authority + ";" + names[j]; 9984 } 9985 if (DEBUG_PACKAGE_SCANNING) { 9986 if (chatty) 9987 Log.d(TAG, "Registered content provider: " + names[j] 9988 + ", className = " + p.info.name + ", isSyncable = " 9989 + p.info.isSyncable); 9990 } 9991 } else { 9992 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9993 Slog.w(TAG, "Skipping provider name " + names[j] + 9994 " (in package " + pkg.applicationInfo.packageName + 9995 "): name already used by " 9996 + ((other != null && other.getComponentName() != null) 9997 ? other.getComponentName().getPackageName() : "?")); 9998 } 9999 } 10000 } 10001 if (chatty) { 10002 if (r == null) { 10003 r = new StringBuilder(256); 10004 } else { 10005 r.append(' '); 10006 } 10007 r.append(p.info.name); 10008 } 10009 } 10010 if (r != null) { 10011 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10012 } 10013 10014 N = pkg.services.size(); 10015 r = null; 10016 for (i=0; i<N; i++) { 10017 PackageParser.Service s = pkg.services.get(i); 10018 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10019 s.info.processName); 10020 mServices.addService(s); 10021 if (chatty) { 10022 if (r == null) { 10023 r = new StringBuilder(256); 10024 } else { 10025 r.append(' '); 10026 } 10027 r.append(s.info.name); 10028 } 10029 } 10030 if (r != null) { 10031 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10032 } 10033 10034 N = pkg.receivers.size(); 10035 r = null; 10036 for (i=0; i<N; i++) { 10037 PackageParser.Activity a = pkg.receivers.get(i); 10038 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10039 a.info.processName); 10040 mReceivers.addActivity(a, "receiver"); 10041 if (chatty) { 10042 if (r == null) { 10043 r = new StringBuilder(256); 10044 } else { 10045 r.append(' '); 10046 } 10047 r.append(a.info.name); 10048 } 10049 } 10050 if (r != null) { 10051 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10052 } 10053 10054 N = pkg.activities.size(); 10055 r = null; 10056 for (i=0; i<N; i++) { 10057 PackageParser.Activity a = pkg.activities.get(i); 10058 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10059 a.info.processName); 10060 mActivities.addActivity(a, "activity"); 10061 if (chatty) { 10062 if (r == null) { 10063 r = new StringBuilder(256); 10064 } else { 10065 r.append(' '); 10066 } 10067 r.append(a.info.name); 10068 } 10069 } 10070 if (r != null) { 10071 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10072 } 10073 10074 N = pkg.permissionGroups.size(); 10075 r = null; 10076 for (i=0; i<N; i++) { 10077 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10078 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10079 final String curPackageName = cur == null ? null : cur.info.packageName; 10080 // Dont allow ephemeral apps to define new permission groups. 10081 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10082 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10083 + pg.info.packageName 10084 + " ignored: instant apps cannot define new permission groups."); 10085 continue; 10086 } 10087 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10088 if (cur == null || isPackageUpdate) { 10089 mPermissionGroups.put(pg.info.name, pg); 10090 if (chatty) { 10091 if (r == null) { 10092 r = new StringBuilder(256); 10093 } else { 10094 r.append(' '); 10095 } 10096 if (isPackageUpdate) { 10097 r.append("UPD:"); 10098 } 10099 r.append(pg.info.name); 10100 } 10101 } else { 10102 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10103 + pg.info.packageName + " ignored: original from " 10104 + cur.info.packageName); 10105 if (chatty) { 10106 if (r == null) { 10107 r = new StringBuilder(256); 10108 } else { 10109 r.append(' '); 10110 } 10111 r.append("DUP:"); 10112 r.append(pg.info.name); 10113 } 10114 } 10115 } 10116 if (r != null) { 10117 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10118 } 10119 10120 N = pkg.permissions.size(); 10121 r = null; 10122 for (i=0; i<N; i++) { 10123 PackageParser.Permission p = pkg.permissions.get(i); 10124 10125 // Dont allow ephemeral apps to define new permissions. 10126 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10127 Slog.w(TAG, "Permission " + p.info.name + " from package " 10128 + p.info.packageName 10129 + " ignored: instant apps cannot define new permissions."); 10130 continue; 10131 } 10132 10133 // Assume by default that we did not install this permission into the system. 10134 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10135 10136 // Now that permission groups have a special meaning, we ignore permission 10137 // groups for legacy apps to prevent unexpected behavior. In particular, 10138 // permissions for one app being granted to someone just becase they happen 10139 // to be in a group defined by another app (before this had no implications). 10140 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10141 p.group = mPermissionGroups.get(p.info.group); 10142 // Warn for a permission in an unknown group. 10143 if (p.info.group != null && p.group == null) { 10144 Slog.w(TAG, "Permission " + p.info.name + " from package " 10145 + p.info.packageName + " in an unknown group " + p.info.group); 10146 } 10147 } 10148 10149 ArrayMap<String, BasePermission> permissionMap = 10150 p.tree ? mSettings.mPermissionTrees 10151 : mSettings.mPermissions; 10152 BasePermission bp = permissionMap.get(p.info.name); 10153 10154 // Allow system apps to redefine non-system permissions 10155 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10156 final boolean currentOwnerIsSystem = (bp.perm != null 10157 && isSystemApp(bp.perm.owner)); 10158 if (isSystemApp(p.owner)) { 10159 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10160 // It's a built-in permission and no owner, take ownership now 10161 bp.packageSetting = pkgSetting; 10162 bp.perm = p; 10163 bp.uid = pkg.applicationInfo.uid; 10164 bp.sourcePackage = p.info.packageName; 10165 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10166 } else if (!currentOwnerIsSystem) { 10167 String msg = "New decl " + p.owner + " of permission " 10168 + p.info.name + " is system; overriding " + bp.sourcePackage; 10169 reportSettingsProblem(Log.WARN, msg); 10170 bp = null; 10171 } 10172 } 10173 } 10174 10175 if (bp == null) { 10176 bp = new BasePermission(p.info.name, p.info.packageName, 10177 BasePermission.TYPE_NORMAL); 10178 permissionMap.put(p.info.name, bp); 10179 } 10180 10181 if (bp.perm == null) { 10182 if (bp.sourcePackage == null 10183 || bp.sourcePackage.equals(p.info.packageName)) { 10184 BasePermission tree = findPermissionTreeLP(p.info.name); 10185 if (tree == null 10186 || tree.sourcePackage.equals(p.info.packageName)) { 10187 bp.packageSetting = pkgSetting; 10188 bp.perm = p; 10189 bp.uid = pkg.applicationInfo.uid; 10190 bp.sourcePackage = p.info.packageName; 10191 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10192 if (chatty) { 10193 if (r == null) { 10194 r = new StringBuilder(256); 10195 } else { 10196 r.append(' '); 10197 } 10198 r.append(p.info.name); 10199 } 10200 } else { 10201 Slog.w(TAG, "Permission " + p.info.name + " from package " 10202 + p.info.packageName + " ignored: base tree " 10203 + tree.name + " is from package " 10204 + tree.sourcePackage); 10205 } 10206 } else { 10207 Slog.w(TAG, "Permission " + p.info.name + " from package " 10208 + p.info.packageName + " ignored: original from " 10209 + bp.sourcePackage); 10210 } 10211 } else if (chatty) { 10212 if (r == null) { 10213 r = new StringBuilder(256); 10214 } else { 10215 r.append(' '); 10216 } 10217 r.append("DUP:"); 10218 r.append(p.info.name); 10219 } 10220 if (bp.perm == p) { 10221 bp.protectionLevel = p.info.protectionLevel; 10222 } 10223 } 10224 10225 if (r != null) { 10226 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10227 } 10228 10229 N = pkg.instrumentation.size(); 10230 r = null; 10231 for (i=0; i<N; i++) { 10232 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10233 a.info.packageName = pkg.applicationInfo.packageName; 10234 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10235 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10236 a.info.splitNames = pkg.splitNames; 10237 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10238 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10239 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10240 a.info.dataDir = pkg.applicationInfo.dataDir; 10241 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10242 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10243 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10244 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10245 mInstrumentation.put(a.getComponentName(), a); 10246 if (chatty) { 10247 if (r == null) { 10248 r = new StringBuilder(256); 10249 } else { 10250 r.append(' '); 10251 } 10252 r.append(a.info.name); 10253 } 10254 } 10255 if (r != null) { 10256 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10257 } 10258 10259 if (pkg.protectedBroadcasts != null) { 10260 N = pkg.protectedBroadcasts.size(); 10261 for (i=0; i<N; i++) { 10262 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10263 } 10264 } 10265 10266 // Create idmap files for pairs of (packages, overlay packages). 10267 // Note: "android", ie framework-res.apk, is handled by native layers. 10268 if (pkg.mOverlayTarget != null) { 10269 // This is an overlay package. 10270 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10271 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10272 mOverlays.put(pkg.mOverlayTarget, 10273 new ArrayMap<String, PackageParser.Package>()); 10274 } 10275 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10276 map.put(pkg.packageName, pkg); 10277 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10278 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10279 createIdmapFailed = true; 10280 } 10281 } 10282 } else if (mOverlays.containsKey(pkg.packageName) && 10283 !pkg.packageName.equals("android")) { 10284 // This is a regular package, with one or more known overlay packages. 10285 createIdmapsForPackageLI(pkg); 10286 } 10287 } 10288 10289 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10290 10291 if (createIdmapFailed) { 10292 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10293 "scanPackageLI failed to createIdmap"); 10294 } 10295 } 10296 10297 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10298 PackageParser.Package update, int[] userIds) { 10299 if (existing.applicationInfo == null || update.applicationInfo == null) { 10300 // This isn't due to an app installation. 10301 return; 10302 } 10303 10304 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10305 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10306 10307 // The codePath hasn't changed, so there's nothing for us to do. 10308 if (Objects.equals(oldCodePath, newCodePath)) { 10309 return; 10310 } 10311 10312 File canonicalNewCodePath; 10313 try { 10314 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10315 } catch (IOException e) { 10316 Slog.w(TAG, "Failed to get canonical path.", e); 10317 return; 10318 } 10319 10320 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10321 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10322 // that the last component of the path (i.e, the name) doesn't need canonicalization 10323 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10324 // but may change in the future. Hopefully this function won't exist at that point. 10325 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10326 oldCodePath.getName()); 10327 10328 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10329 // with "@". 10330 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10331 if (!oldMarkerPrefix.endsWith("@")) { 10332 oldMarkerPrefix += "@"; 10333 } 10334 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10335 if (!newMarkerPrefix.endsWith("@")) { 10336 newMarkerPrefix += "@"; 10337 } 10338 10339 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10340 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10341 for (String updatedPath : updatedPaths) { 10342 String updatedPathName = new File(updatedPath).getName(); 10343 markerSuffixes.add(updatedPathName.replace('/', '@')); 10344 } 10345 10346 for (int userId : userIds) { 10347 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10348 10349 for (String markerSuffix : markerSuffixes) { 10350 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10351 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10352 if (oldForeignUseMark.exists()) { 10353 try { 10354 Os.rename(oldForeignUseMark.getAbsolutePath(), 10355 newForeignUseMark.getAbsolutePath()); 10356 } catch (ErrnoException e) { 10357 Slog.w(TAG, "Failed to rename foreign use marker", e); 10358 oldForeignUseMark.delete(); 10359 } 10360 } 10361 } 10362 } 10363 } 10364 10365 /** 10366 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10367 * is derived purely on the basis of the contents of {@code scanFile} and 10368 * {@code cpuAbiOverride}. 10369 * 10370 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10371 */ 10372 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10373 String cpuAbiOverride, boolean extractLibs, 10374 File appLib32InstallDir) 10375 throws PackageManagerException { 10376 // Give ourselves some initial paths; we'll come back for another 10377 // pass once we've determined ABI below. 10378 setNativeLibraryPaths(pkg, appLib32InstallDir); 10379 10380 // We would never need to extract libs for forward-locked and external packages, 10381 // since the container service will do it for us. We shouldn't attempt to 10382 // extract libs from system app when it was not updated. 10383 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10384 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10385 extractLibs = false; 10386 } 10387 10388 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10389 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10390 10391 NativeLibraryHelper.Handle handle = null; 10392 try { 10393 handle = NativeLibraryHelper.Handle.create(pkg); 10394 // TODO(multiArch): This can be null for apps that didn't go through the 10395 // usual installation process. We can calculate it again, like we 10396 // do during install time. 10397 // 10398 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10399 // unnecessary. 10400 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10401 10402 // Null out the abis so that they can be recalculated. 10403 pkg.applicationInfo.primaryCpuAbi = null; 10404 pkg.applicationInfo.secondaryCpuAbi = null; 10405 if (isMultiArch(pkg.applicationInfo)) { 10406 // Warn if we've set an abiOverride for multi-lib packages.. 10407 // By definition, we need to copy both 32 and 64 bit libraries for 10408 // such packages. 10409 if (pkg.cpuAbiOverride != null 10410 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10411 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10412 } 10413 10414 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10415 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10416 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10417 if (extractLibs) { 10418 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10419 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10420 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10421 useIsaSpecificSubdirs); 10422 } else { 10423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10424 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10425 } 10426 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10427 } 10428 10429 maybeThrowExceptionForMultiArchCopy( 10430 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10431 10432 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10433 if (extractLibs) { 10434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10435 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10436 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10437 useIsaSpecificSubdirs); 10438 } else { 10439 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10440 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10441 } 10442 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10443 } 10444 10445 maybeThrowExceptionForMultiArchCopy( 10446 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10447 10448 if (abi64 >= 0) { 10449 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10450 } 10451 10452 if (abi32 >= 0) { 10453 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10454 if (abi64 >= 0) { 10455 if (pkg.use32bitAbi) { 10456 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10457 pkg.applicationInfo.primaryCpuAbi = abi; 10458 } else { 10459 pkg.applicationInfo.secondaryCpuAbi = abi; 10460 } 10461 } else { 10462 pkg.applicationInfo.primaryCpuAbi = abi; 10463 } 10464 } 10465 10466 } else { 10467 String[] abiList = (cpuAbiOverride != null) ? 10468 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10469 10470 // Enable gross and lame hacks for apps that are built with old 10471 // SDK tools. We must scan their APKs for renderscript bitcode and 10472 // not launch them if it's present. Don't bother checking on devices 10473 // that don't have 64 bit support. 10474 boolean needsRenderScriptOverride = false; 10475 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10476 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10477 abiList = Build.SUPPORTED_32_BIT_ABIS; 10478 needsRenderScriptOverride = true; 10479 } 10480 10481 final int copyRet; 10482 if (extractLibs) { 10483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10484 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10485 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10486 } else { 10487 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10488 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10489 } 10490 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10491 10492 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10493 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10494 "Error unpackaging native libs for app, errorCode=" + copyRet); 10495 } 10496 10497 if (copyRet >= 0) { 10498 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10499 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10500 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10501 } else if (needsRenderScriptOverride) { 10502 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10503 } 10504 } 10505 } catch (IOException ioe) { 10506 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10507 } finally { 10508 IoUtils.closeQuietly(handle); 10509 } 10510 10511 // Now that we've calculated the ABIs and determined if it's an internal app, 10512 // we will go ahead and populate the nativeLibraryPath. 10513 setNativeLibraryPaths(pkg, appLib32InstallDir); 10514 } 10515 10516 /** 10517 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10518 * i.e, so that all packages can be run inside a single process if required. 10519 * 10520 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10521 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10522 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10523 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10524 * updating a package that belongs to a shared user. 10525 * 10526 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10527 * adds unnecessary complexity. 10528 */ 10529 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10530 PackageParser.Package scannedPackage) { 10531 String requiredInstructionSet = null; 10532 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10533 requiredInstructionSet = VMRuntime.getInstructionSet( 10534 scannedPackage.applicationInfo.primaryCpuAbi); 10535 } 10536 10537 PackageSetting requirer = null; 10538 for (PackageSetting ps : packagesForUser) { 10539 // If packagesForUser contains scannedPackage, we skip it. This will happen 10540 // when scannedPackage is an update of an existing package. Without this check, 10541 // we will never be able to change the ABI of any package belonging to a shared 10542 // user, even if it's compatible with other packages. 10543 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10544 if (ps.primaryCpuAbiString == null) { 10545 continue; 10546 } 10547 10548 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10549 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10550 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10551 // this but there's not much we can do. 10552 String errorMessage = "Instruction set mismatch, " 10553 + ((requirer == null) ? "[caller]" : requirer) 10554 + " requires " + requiredInstructionSet + " whereas " + ps 10555 + " requires " + instructionSet; 10556 Slog.w(TAG, errorMessage); 10557 } 10558 10559 if (requiredInstructionSet == null) { 10560 requiredInstructionSet = instructionSet; 10561 requirer = ps; 10562 } 10563 } 10564 } 10565 10566 if (requiredInstructionSet != null) { 10567 String adjustedAbi; 10568 if (requirer != null) { 10569 // requirer != null implies that either scannedPackage was null or that scannedPackage 10570 // did not require an ABI, in which case we have to adjust scannedPackage to match 10571 // the ABI of the set (which is the same as requirer's ABI) 10572 adjustedAbi = requirer.primaryCpuAbiString; 10573 if (scannedPackage != null) { 10574 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10575 } 10576 } else { 10577 // requirer == null implies that we're updating all ABIs in the set to 10578 // match scannedPackage. 10579 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10580 } 10581 10582 for (PackageSetting ps : packagesForUser) { 10583 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10584 if (ps.primaryCpuAbiString != null) { 10585 continue; 10586 } 10587 10588 ps.primaryCpuAbiString = adjustedAbi; 10589 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10590 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10591 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10592 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10593 + " (requirer=" 10594 + (requirer == null ? "null" : requirer.pkg.packageName) 10595 + ", scannedPackage=" 10596 + (scannedPackage != null ? scannedPackage.packageName : "null") 10597 + ")"); 10598 try { 10599 mInstaller.rmdex(ps.codePathString, 10600 getDexCodeInstructionSet(getPreferredInstructionSet())); 10601 } catch (InstallerException ignored) { 10602 } 10603 } 10604 } 10605 } 10606 } 10607 } 10608 10609 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10610 synchronized (mPackages) { 10611 mResolverReplaced = true; 10612 // Set up information for custom user intent resolution activity. 10613 mResolveActivity.applicationInfo = pkg.applicationInfo; 10614 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10615 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10616 mResolveActivity.processName = pkg.applicationInfo.packageName; 10617 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10618 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10619 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10620 mResolveActivity.theme = 0; 10621 mResolveActivity.exported = true; 10622 mResolveActivity.enabled = true; 10623 mResolveInfo.activityInfo = mResolveActivity; 10624 mResolveInfo.priority = 0; 10625 mResolveInfo.preferredOrder = 0; 10626 mResolveInfo.match = 0; 10627 mResolveComponentName = mCustomResolverComponentName; 10628 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10629 mResolveComponentName); 10630 } 10631 } 10632 10633 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 10634 if (installerComponent == null) { 10635 if (DEBUG_EPHEMERAL) { 10636 Slog.d(TAG, "Clear ephemeral installer activity"); 10637 } 10638 mEphemeralInstallerActivity.applicationInfo = null; 10639 return; 10640 } 10641 10642 if (DEBUG_EPHEMERAL) { 10643 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10644 } 10645 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10646 // Set up information for ephemeral installer activity 10647 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 10648 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 10649 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 10650 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 10651 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10652 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10653 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10654 mEphemeralInstallerActivity.theme = 0; 10655 mEphemeralInstallerActivity.exported = true; 10656 mEphemeralInstallerActivity.enabled = true; 10657 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 10658 mEphemeralInstallerInfo.priority = 0; 10659 mEphemeralInstallerInfo.preferredOrder = 1; 10660 mEphemeralInstallerInfo.isDefault = true; 10661 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10662 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10663 } 10664 10665 private static String calculateBundledApkRoot(final String codePathString) { 10666 final File codePath = new File(codePathString); 10667 final File codeRoot; 10668 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10669 codeRoot = Environment.getRootDirectory(); 10670 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10671 codeRoot = Environment.getOemDirectory(); 10672 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10673 codeRoot = Environment.getVendorDirectory(); 10674 } else { 10675 // Unrecognized code path; take its top real segment as the apk root: 10676 // e.g. /something/app/blah.apk => /something 10677 try { 10678 File f = codePath.getCanonicalFile(); 10679 File parent = f.getParentFile(); // non-null because codePath is a file 10680 File tmp; 10681 while ((tmp = parent.getParentFile()) != null) { 10682 f = parent; 10683 parent = tmp; 10684 } 10685 codeRoot = f; 10686 Slog.w(TAG, "Unrecognized code path " 10687 + codePath + " - using " + codeRoot); 10688 } catch (IOException e) { 10689 // Can't canonicalize the code path -- shenanigans? 10690 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10691 return Environment.getRootDirectory().getPath(); 10692 } 10693 } 10694 return codeRoot.getPath(); 10695 } 10696 10697 /** 10698 * Derive and set the location of native libraries for the given package, 10699 * which varies depending on where and how the package was installed. 10700 */ 10701 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10702 final ApplicationInfo info = pkg.applicationInfo; 10703 final String codePath = pkg.codePath; 10704 final File codeFile = new File(codePath); 10705 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10706 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10707 10708 info.nativeLibraryRootDir = null; 10709 info.nativeLibraryRootRequiresIsa = false; 10710 info.nativeLibraryDir = null; 10711 info.secondaryNativeLibraryDir = null; 10712 10713 if (isApkFile(codeFile)) { 10714 // Monolithic install 10715 if (bundledApp) { 10716 // If "/system/lib64/apkname" exists, assume that is the per-package 10717 // native library directory to use; otherwise use "/system/lib/apkname". 10718 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10719 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10720 getPrimaryInstructionSet(info)); 10721 10722 // This is a bundled system app so choose the path based on the ABI. 10723 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10724 // is just the default path. 10725 final String apkName = deriveCodePathName(codePath); 10726 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10727 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10728 apkName).getAbsolutePath(); 10729 10730 if (info.secondaryCpuAbi != null) { 10731 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10732 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10733 secondaryLibDir, apkName).getAbsolutePath(); 10734 } 10735 } else if (asecApp) { 10736 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10737 .getAbsolutePath(); 10738 } else { 10739 final String apkName = deriveCodePathName(codePath); 10740 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10741 .getAbsolutePath(); 10742 } 10743 10744 info.nativeLibraryRootRequiresIsa = false; 10745 info.nativeLibraryDir = info.nativeLibraryRootDir; 10746 } else { 10747 // Cluster install 10748 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10749 info.nativeLibraryRootRequiresIsa = true; 10750 10751 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10752 getPrimaryInstructionSet(info)).getAbsolutePath(); 10753 10754 if (info.secondaryCpuAbi != null) { 10755 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10756 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10757 } 10758 } 10759 } 10760 10761 /** 10762 * Calculate the abis and roots for a bundled app. These can uniquely 10763 * be determined from the contents of the system partition, i.e whether 10764 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10765 * of this information, and instead assume that the system was built 10766 * sensibly. 10767 */ 10768 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10769 PackageSetting pkgSetting) { 10770 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10771 10772 // If "/system/lib64/apkname" exists, assume that is the per-package 10773 // native library directory to use; otherwise use "/system/lib/apkname". 10774 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10775 setBundledAppAbi(pkg, apkRoot, apkName); 10776 // pkgSetting might be null during rescan following uninstall of updates 10777 // to a bundled app, so accommodate that possibility. The settings in 10778 // that case will be established later from the parsed package. 10779 // 10780 // If the settings aren't null, sync them up with what we've just derived. 10781 // note that apkRoot isn't stored in the package settings. 10782 if (pkgSetting != null) { 10783 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10784 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10785 } 10786 } 10787 10788 /** 10789 * Deduces the ABI of a bundled app and sets the relevant fields on the 10790 * parsed pkg object. 10791 * 10792 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10793 * under which system libraries are installed. 10794 * @param apkName the name of the installed package. 10795 */ 10796 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10797 final File codeFile = new File(pkg.codePath); 10798 10799 final boolean has64BitLibs; 10800 final boolean has32BitLibs; 10801 if (isApkFile(codeFile)) { 10802 // Monolithic install 10803 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10804 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10805 } else { 10806 // Cluster install 10807 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10808 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10809 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10810 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10811 has64BitLibs = (new File(rootDir, isa)).exists(); 10812 } else { 10813 has64BitLibs = false; 10814 } 10815 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10816 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10817 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10818 has32BitLibs = (new File(rootDir, isa)).exists(); 10819 } else { 10820 has32BitLibs = false; 10821 } 10822 } 10823 10824 if (has64BitLibs && !has32BitLibs) { 10825 // The package has 64 bit libs, but not 32 bit libs. Its primary 10826 // ABI should be 64 bit. We can safely assume here that the bundled 10827 // native libraries correspond to the most preferred ABI in the list. 10828 10829 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10830 pkg.applicationInfo.secondaryCpuAbi = null; 10831 } else if (has32BitLibs && !has64BitLibs) { 10832 // The package has 32 bit libs but not 64 bit libs. Its primary 10833 // ABI should be 32 bit. 10834 10835 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10836 pkg.applicationInfo.secondaryCpuAbi = null; 10837 } else if (has32BitLibs && has64BitLibs) { 10838 // The application has both 64 and 32 bit bundled libraries. We check 10839 // here that the app declares multiArch support, and warn if it doesn't. 10840 // 10841 // We will be lenient here and record both ABIs. The primary will be the 10842 // ABI that's higher on the list, i.e, a device that's configured to prefer 10843 // 64 bit apps will see a 64 bit primary ABI, 10844 10845 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10846 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10847 } 10848 10849 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10850 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10851 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10852 } else { 10853 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10854 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10855 } 10856 } else { 10857 pkg.applicationInfo.primaryCpuAbi = null; 10858 pkg.applicationInfo.secondaryCpuAbi = null; 10859 } 10860 } 10861 10862 private void killApplication(String pkgName, int appId, String reason) { 10863 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10864 } 10865 10866 private void killApplication(String pkgName, int appId, int userId, String reason) { 10867 // Request the ActivityManager to kill the process(only for existing packages) 10868 // so that we do not end up in a confused state while the user is still using the older 10869 // version of the application while the new one gets installed. 10870 final long token = Binder.clearCallingIdentity(); 10871 try { 10872 IActivityManager am = ActivityManager.getService(); 10873 if (am != null) { 10874 try { 10875 am.killApplication(pkgName, appId, userId, reason); 10876 } catch (RemoteException e) { 10877 } 10878 } 10879 } finally { 10880 Binder.restoreCallingIdentity(token); 10881 } 10882 } 10883 10884 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10885 // Remove the parent package setting 10886 PackageSetting ps = (PackageSetting) pkg.mExtras; 10887 if (ps != null) { 10888 removePackageLI(ps, chatty); 10889 } 10890 // Remove the child package setting 10891 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10892 for (int i = 0; i < childCount; i++) { 10893 PackageParser.Package childPkg = pkg.childPackages.get(i); 10894 ps = (PackageSetting) childPkg.mExtras; 10895 if (ps != null) { 10896 removePackageLI(ps, chatty); 10897 } 10898 } 10899 } 10900 10901 void removePackageLI(PackageSetting ps, boolean chatty) { 10902 if (DEBUG_INSTALL) { 10903 if (chatty) 10904 Log.d(TAG, "Removing package " + ps.name); 10905 } 10906 10907 // writer 10908 synchronized (mPackages) { 10909 mPackages.remove(ps.name); 10910 final PackageParser.Package pkg = ps.pkg; 10911 if (pkg != null) { 10912 cleanPackageDataStructuresLILPw(pkg, chatty); 10913 } 10914 } 10915 } 10916 10917 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10918 if (DEBUG_INSTALL) { 10919 if (chatty) 10920 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10921 } 10922 10923 // writer 10924 synchronized (mPackages) { 10925 // Remove the parent package 10926 mPackages.remove(pkg.applicationInfo.packageName); 10927 cleanPackageDataStructuresLILPw(pkg, chatty); 10928 10929 // Remove the child packages 10930 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10931 for (int i = 0; i < childCount; i++) { 10932 PackageParser.Package childPkg = pkg.childPackages.get(i); 10933 mPackages.remove(childPkg.applicationInfo.packageName); 10934 cleanPackageDataStructuresLILPw(childPkg, chatty); 10935 } 10936 } 10937 } 10938 10939 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10940 int N = pkg.providers.size(); 10941 StringBuilder r = null; 10942 int i; 10943 for (i=0; i<N; i++) { 10944 PackageParser.Provider p = pkg.providers.get(i); 10945 mProviders.removeProvider(p); 10946 if (p.info.authority == null) { 10947 10948 /* There was another ContentProvider with this authority when 10949 * this app was installed so this authority is null, 10950 * Ignore it as we don't have to unregister the provider. 10951 */ 10952 continue; 10953 } 10954 String names[] = p.info.authority.split(";"); 10955 for (int j = 0; j < names.length; j++) { 10956 if (mProvidersByAuthority.get(names[j]) == p) { 10957 mProvidersByAuthority.remove(names[j]); 10958 if (DEBUG_REMOVE) { 10959 if (chatty) 10960 Log.d(TAG, "Unregistered content provider: " + names[j] 10961 + ", className = " + p.info.name + ", isSyncable = " 10962 + p.info.isSyncable); 10963 } 10964 } 10965 } 10966 if (DEBUG_REMOVE && chatty) { 10967 if (r == null) { 10968 r = new StringBuilder(256); 10969 } else { 10970 r.append(' '); 10971 } 10972 r.append(p.info.name); 10973 } 10974 } 10975 if (r != null) { 10976 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10977 } 10978 10979 N = pkg.services.size(); 10980 r = null; 10981 for (i=0; i<N; i++) { 10982 PackageParser.Service s = pkg.services.get(i); 10983 mServices.removeService(s); 10984 if (chatty) { 10985 if (r == null) { 10986 r = new StringBuilder(256); 10987 } else { 10988 r.append(' '); 10989 } 10990 r.append(s.info.name); 10991 } 10992 } 10993 if (r != null) { 10994 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10995 } 10996 10997 N = pkg.receivers.size(); 10998 r = null; 10999 for (i=0; i<N; i++) { 11000 PackageParser.Activity a = pkg.receivers.get(i); 11001 mReceivers.removeActivity(a, "receiver"); 11002 if (DEBUG_REMOVE && chatty) { 11003 if (r == null) { 11004 r = new StringBuilder(256); 11005 } else { 11006 r.append(' '); 11007 } 11008 r.append(a.info.name); 11009 } 11010 } 11011 if (r != null) { 11012 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11013 } 11014 11015 N = pkg.activities.size(); 11016 r = null; 11017 for (i=0; i<N; i++) { 11018 PackageParser.Activity a = pkg.activities.get(i); 11019 mActivities.removeActivity(a, "activity"); 11020 if (DEBUG_REMOVE && chatty) { 11021 if (r == null) { 11022 r = new StringBuilder(256); 11023 } else { 11024 r.append(' '); 11025 } 11026 r.append(a.info.name); 11027 } 11028 } 11029 if (r != null) { 11030 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11031 } 11032 11033 N = pkg.permissions.size(); 11034 r = null; 11035 for (i=0; i<N; i++) { 11036 PackageParser.Permission p = pkg.permissions.get(i); 11037 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11038 if (bp == null) { 11039 bp = mSettings.mPermissionTrees.get(p.info.name); 11040 } 11041 if (bp != null && bp.perm == p) { 11042 bp.perm = null; 11043 if (DEBUG_REMOVE && chatty) { 11044 if (r == null) { 11045 r = new StringBuilder(256); 11046 } else { 11047 r.append(' '); 11048 } 11049 r.append(p.info.name); 11050 } 11051 } 11052 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11053 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11054 if (appOpPkgs != null) { 11055 appOpPkgs.remove(pkg.packageName); 11056 } 11057 } 11058 } 11059 if (r != null) { 11060 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11061 } 11062 11063 N = pkg.requestedPermissions.size(); 11064 r = null; 11065 for (i=0; i<N; i++) { 11066 String perm = pkg.requestedPermissions.get(i); 11067 BasePermission bp = mSettings.mPermissions.get(perm); 11068 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11069 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11070 if (appOpPkgs != null) { 11071 appOpPkgs.remove(pkg.packageName); 11072 if (appOpPkgs.isEmpty()) { 11073 mAppOpPermissionPackages.remove(perm); 11074 } 11075 } 11076 } 11077 } 11078 if (r != null) { 11079 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11080 } 11081 11082 N = pkg.instrumentation.size(); 11083 r = null; 11084 for (i=0; i<N; i++) { 11085 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11086 mInstrumentation.remove(a.getComponentName()); 11087 if (DEBUG_REMOVE && chatty) { 11088 if (r == null) { 11089 r = new StringBuilder(256); 11090 } else { 11091 r.append(' '); 11092 } 11093 r.append(a.info.name); 11094 } 11095 } 11096 if (r != null) { 11097 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11098 } 11099 11100 r = null; 11101 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11102 // Only system apps can hold shared libraries. 11103 if (pkg.libraryNames != null) { 11104 for (i = 0; i < pkg.libraryNames.size(); i++) { 11105 String name = pkg.libraryNames.get(i); 11106 if (removeSharedLibraryLPw(name, 0)) { 11107 if (DEBUG_REMOVE && chatty) { 11108 if (r == null) { 11109 r = new StringBuilder(256); 11110 } else { 11111 r.append(' '); 11112 } 11113 r.append(name); 11114 } 11115 } 11116 } 11117 } 11118 } 11119 11120 r = null; 11121 11122 // Any package can hold static shared libraries. 11123 if (pkg.staticSharedLibName != null) { 11124 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11125 if (DEBUG_REMOVE && chatty) { 11126 if (r == null) { 11127 r = new StringBuilder(256); 11128 } else { 11129 r.append(' '); 11130 } 11131 r.append(pkg.staticSharedLibName); 11132 } 11133 } 11134 } 11135 11136 if (r != null) { 11137 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11138 } 11139 } 11140 11141 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11142 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11143 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11144 return true; 11145 } 11146 } 11147 return false; 11148 } 11149 11150 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11151 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11152 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11153 11154 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11155 // Update the parent permissions 11156 updatePermissionsLPw(pkg.packageName, pkg, flags); 11157 // Update the child permissions 11158 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11159 for (int i = 0; i < childCount; i++) { 11160 PackageParser.Package childPkg = pkg.childPackages.get(i); 11161 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11162 } 11163 } 11164 11165 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11166 int flags) { 11167 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11168 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11169 } 11170 11171 private void updatePermissionsLPw(String changingPkg, 11172 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11173 // Make sure there are no dangling permission trees. 11174 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11175 while (it.hasNext()) { 11176 final BasePermission bp = it.next(); 11177 if (bp.packageSetting == null) { 11178 // We may not yet have parsed the package, so just see if 11179 // we still know about its settings. 11180 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11181 } 11182 if (bp.packageSetting == null) { 11183 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11184 + " from package " + bp.sourcePackage); 11185 it.remove(); 11186 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11187 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11188 Slog.i(TAG, "Removing old permission tree: " + bp.name 11189 + " from package " + bp.sourcePackage); 11190 flags |= UPDATE_PERMISSIONS_ALL; 11191 it.remove(); 11192 } 11193 } 11194 } 11195 11196 // Make sure all dynamic permissions have been assigned to a package, 11197 // and make sure there are no dangling permissions. 11198 it = mSettings.mPermissions.values().iterator(); 11199 while (it.hasNext()) { 11200 final BasePermission bp = it.next(); 11201 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11202 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11203 + bp.name + " pkg=" + bp.sourcePackage 11204 + " info=" + bp.pendingInfo); 11205 if (bp.packageSetting == null && bp.pendingInfo != null) { 11206 final BasePermission tree = findPermissionTreeLP(bp.name); 11207 if (tree != null && tree.perm != null) { 11208 bp.packageSetting = tree.packageSetting; 11209 bp.perm = new PackageParser.Permission(tree.perm.owner, 11210 new PermissionInfo(bp.pendingInfo)); 11211 bp.perm.info.packageName = tree.perm.info.packageName; 11212 bp.perm.info.name = bp.name; 11213 bp.uid = tree.uid; 11214 } 11215 } 11216 } 11217 if (bp.packageSetting == null) { 11218 // We may not yet have parsed the package, so just see if 11219 // we still know about its settings. 11220 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11221 } 11222 if (bp.packageSetting == null) { 11223 Slog.w(TAG, "Removing dangling permission: " + bp.name 11224 + " from package " + bp.sourcePackage); 11225 it.remove(); 11226 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11227 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11228 Slog.i(TAG, "Removing old permission: " + bp.name 11229 + " from package " + bp.sourcePackage); 11230 flags |= UPDATE_PERMISSIONS_ALL; 11231 it.remove(); 11232 } 11233 } 11234 } 11235 11236 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11237 // Now update the permissions for all packages, in particular 11238 // replace the granted permissions of the system packages. 11239 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11240 for (PackageParser.Package pkg : mPackages.values()) { 11241 if (pkg != pkgInfo) { 11242 // Only replace for packages on requested volume 11243 final String volumeUuid = getVolumeUuidForPackage(pkg); 11244 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11245 && Objects.equals(replaceVolumeUuid, volumeUuid); 11246 grantPermissionsLPw(pkg, replace, changingPkg); 11247 } 11248 } 11249 } 11250 11251 if (pkgInfo != null) { 11252 // Only replace for packages on requested volume 11253 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11254 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11255 && Objects.equals(replaceVolumeUuid, volumeUuid); 11256 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11257 } 11258 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11259 } 11260 11261 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11262 String packageOfInterest) { 11263 // IMPORTANT: There are two types of permissions: install and runtime. 11264 // Install time permissions are granted when the app is installed to 11265 // all device users and users added in the future. Runtime permissions 11266 // are granted at runtime explicitly to specific users. Normal and signature 11267 // protected permissions are install time permissions. Dangerous permissions 11268 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11269 // otherwise they are runtime permissions. This function does not manage 11270 // runtime permissions except for the case an app targeting Lollipop MR1 11271 // being upgraded to target a newer SDK, in which case dangerous permissions 11272 // are transformed from install time to runtime ones. 11273 11274 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11275 if (ps == null) { 11276 return; 11277 } 11278 11279 PermissionsState permissionsState = ps.getPermissionsState(); 11280 PermissionsState origPermissions = permissionsState; 11281 11282 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11283 11284 boolean runtimePermissionsRevoked = false; 11285 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11286 11287 boolean changedInstallPermission = false; 11288 11289 if (replace) { 11290 ps.installPermissionsFixed = false; 11291 if (!ps.isSharedUser()) { 11292 origPermissions = new PermissionsState(permissionsState); 11293 permissionsState.reset(); 11294 } else { 11295 // We need to know only about runtime permission changes since the 11296 // calling code always writes the install permissions state but 11297 // the runtime ones are written only if changed. The only cases of 11298 // changed runtime permissions here are promotion of an install to 11299 // runtime and revocation of a runtime from a shared user. 11300 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11301 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11302 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11303 runtimePermissionsRevoked = true; 11304 } 11305 } 11306 } 11307 11308 permissionsState.setGlobalGids(mGlobalGids); 11309 11310 final int N = pkg.requestedPermissions.size(); 11311 for (int i=0; i<N; i++) { 11312 final String name = pkg.requestedPermissions.get(i); 11313 final BasePermission bp = mSettings.mPermissions.get(name); 11314 11315 if (DEBUG_INSTALL) { 11316 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11317 } 11318 11319 if (bp == null || bp.packageSetting == null) { 11320 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11321 Slog.w(TAG, "Unknown permission " + name 11322 + " in package " + pkg.packageName); 11323 } 11324 continue; 11325 } 11326 11327 11328 // Limit ephemeral apps to ephemeral allowed permissions. 11329 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11330 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11331 + pkg.packageName); 11332 continue; 11333 } 11334 11335 final String perm = bp.name; 11336 boolean allowedSig = false; 11337 int grant = GRANT_DENIED; 11338 11339 // Keep track of app op permissions. 11340 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11341 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11342 if (pkgs == null) { 11343 pkgs = new ArraySet<>(); 11344 mAppOpPermissionPackages.put(bp.name, pkgs); 11345 } 11346 pkgs.add(pkg.packageName); 11347 } 11348 11349 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11350 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11351 >= Build.VERSION_CODES.M; 11352 switch (level) { 11353 case PermissionInfo.PROTECTION_NORMAL: { 11354 // For all apps normal permissions are install time ones. 11355 grant = GRANT_INSTALL; 11356 } break; 11357 11358 case PermissionInfo.PROTECTION_DANGEROUS: { 11359 // If a permission review is required for legacy apps we represent 11360 // their permissions as always granted runtime ones since we need 11361 // to keep the review required permission flag per user while an 11362 // install permission's state is shared across all users. 11363 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11364 // For legacy apps dangerous permissions are install time ones. 11365 grant = GRANT_INSTALL; 11366 } else if (origPermissions.hasInstallPermission(bp.name)) { 11367 // For legacy apps that became modern, install becomes runtime. 11368 grant = GRANT_UPGRADE; 11369 } else if (mPromoteSystemApps 11370 && isSystemApp(ps) 11371 && mExistingSystemPackages.contains(ps.name)) { 11372 // For legacy system apps, install becomes runtime. 11373 // We cannot check hasInstallPermission() for system apps since those 11374 // permissions were granted implicitly and not persisted pre-M. 11375 grant = GRANT_UPGRADE; 11376 } else { 11377 // For modern apps keep runtime permissions unchanged. 11378 grant = GRANT_RUNTIME; 11379 } 11380 } break; 11381 11382 case PermissionInfo.PROTECTION_SIGNATURE: { 11383 // For all apps signature permissions are install time ones. 11384 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11385 if (allowedSig) { 11386 grant = GRANT_INSTALL; 11387 } 11388 } break; 11389 } 11390 11391 if (DEBUG_INSTALL) { 11392 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11393 } 11394 11395 if (grant != GRANT_DENIED) { 11396 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11397 // If this is an existing, non-system package, then 11398 // we can't add any new permissions to it. 11399 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11400 // Except... if this is a permission that was added 11401 // to the platform (note: need to only do this when 11402 // updating the platform). 11403 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11404 grant = GRANT_DENIED; 11405 } 11406 } 11407 } 11408 11409 switch (grant) { 11410 case GRANT_INSTALL: { 11411 // Revoke this as runtime permission to handle the case of 11412 // a runtime permission being downgraded to an install one. 11413 // Also in permission review mode we keep dangerous permissions 11414 // for legacy apps 11415 for (int userId : UserManagerService.getInstance().getUserIds()) { 11416 if (origPermissions.getRuntimePermissionState( 11417 bp.name, userId) != null) { 11418 // Revoke the runtime permission and clear the flags. 11419 origPermissions.revokeRuntimePermission(bp, userId); 11420 origPermissions.updatePermissionFlags(bp, userId, 11421 PackageManager.MASK_PERMISSION_FLAGS, 0); 11422 // If we revoked a permission permission, we have to write. 11423 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11424 changedRuntimePermissionUserIds, userId); 11425 } 11426 } 11427 // Grant an install permission. 11428 if (permissionsState.grantInstallPermission(bp) != 11429 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11430 changedInstallPermission = true; 11431 } 11432 } break; 11433 11434 case GRANT_RUNTIME: { 11435 // Grant previously granted runtime permissions. 11436 for (int userId : UserManagerService.getInstance().getUserIds()) { 11437 PermissionState permissionState = origPermissions 11438 .getRuntimePermissionState(bp.name, userId); 11439 int flags = permissionState != null 11440 ? permissionState.getFlags() : 0; 11441 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11442 // Don't propagate the permission in a permission review mode if 11443 // the former was revoked, i.e. marked to not propagate on upgrade. 11444 // Note that in a permission review mode install permissions are 11445 // represented as constantly granted runtime ones since we need to 11446 // keep a per user state associated with the permission. Also the 11447 // revoke on upgrade flag is no longer applicable and is reset. 11448 final boolean revokeOnUpgrade = (flags & PackageManager 11449 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11450 if (revokeOnUpgrade) { 11451 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11452 // Since we changed the flags, we have to write. 11453 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11454 changedRuntimePermissionUserIds, userId); 11455 } 11456 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11457 if (permissionsState.grantRuntimePermission(bp, userId) == 11458 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11459 // If we cannot put the permission as it was, 11460 // we have to write. 11461 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11462 changedRuntimePermissionUserIds, userId); 11463 } 11464 } 11465 11466 // If the app supports runtime permissions no need for a review. 11467 if (mPermissionReviewRequired 11468 && appSupportsRuntimePermissions 11469 && (flags & PackageManager 11470 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11471 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11472 // Since we changed the flags, we have to write. 11473 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11474 changedRuntimePermissionUserIds, userId); 11475 } 11476 } else if (mPermissionReviewRequired 11477 && !appSupportsRuntimePermissions) { 11478 // For legacy apps that need a permission review, every new 11479 // runtime permission is granted but it is pending a review. 11480 // We also need to review only platform defined runtime 11481 // permissions as these are the only ones the platform knows 11482 // how to disable the API to simulate revocation as legacy 11483 // apps don't expect to run with revoked permissions. 11484 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11485 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11486 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11487 // We changed the flags, hence have to write. 11488 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11489 changedRuntimePermissionUserIds, userId); 11490 } 11491 } 11492 if (permissionsState.grantRuntimePermission(bp, userId) 11493 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11494 // We changed the permission, hence have to write. 11495 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11496 changedRuntimePermissionUserIds, userId); 11497 } 11498 } 11499 // Propagate the permission flags. 11500 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11501 } 11502 } break; 11503 11504 case GRANT_UPGRADE: { 11505 // Grant runtime permissions for a previously held install permission. 11506 PermissionState permissionState = origPermissions 11507 .getInstallPermissionState(bp.name); 11508 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11509 11510 if (origPermissions.revokeInstallPermission(bp) 11511 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11512 // We will be transferring the permission flags, so clear them. 11513 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11514 PackageManager.MASK_PERMISSION_FLAGS, 0); 11515 changedInstallPermission = true; 11516 } 11517 11518 // If the permission is not to be promoted to runtime we ignore it and 11519 // also its other flags as they are not applicable to install permissions. 11520 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11521 for (int userId : currentUserIds) { 11522 if (permissionsState.grantRuntimePermission(bp, userId) != 11523 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11524 // Transfer the permission flags. 11525 permissionsState.updatePermissionFlags(bp, userId, 11526 flags, flags); 11527 // If we granted the permission, we have to write. 11528 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11529 changedRuntimePermissionUserIds, userId); 11530 } 11531 } 11532 } 11533 } break; 11534 11535 default: { 11536 if (packageOfInterest == null 11537 || packageOfInterest.equals(pkg.packageName)) { 11538 Slog.w(TAG, "Not granting permission " + perm 11539 + " to package " + pkg.packageName 11540 + " because it was previously installed without"); 11541 } 11542 } break; 11543 } 11544 } else { 11545 if (permissionsState.revokeInstallPermission(bp) != 11546 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11547 // Also drop the permission flags. 11548 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11549 PackageManager.MASK_PERMISSION_FLAGS, 0); 11550 changedInstallPermission = true; 11551 Slog.i(TAG, "Un-granting permission " + perm 11552 + " from package " + pkg.packageName 11553 + " (protectionLevel=" + bp.protectionLevel 11554 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11555 + ")"); 11556 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11557 // Don't print warning for app op permissions, since it is fine for them 11558 // not to be granted, there is a UI for the user to decide. 11559 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11560 Slog.w(TAG, "Not granting permission " + perm 11561 + " to package " + pkg.packageName 11562 + " (protectionLevel=" + bp.protectionLevel 11563 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11564 + ")"); 11565 } 11566 } 11567 } 11568 } 11569 11570 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11571 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11572 // This is the first that we have heard about this package, so the 11573 // permissions we have now selected are fixed until explicitly 11574 // changed. 11575 ps.installPermissionsFixed = true; 11576 } 11577 11578 // Persist the runtime permissions state for users with changes. If permissions 11579 // were revoked because no app in the shared user declares them we have to 11580 // write synchronously to avoid losing runtime permissions state. 11581 for (int userId : changedRuntimePermissionUserIds) { 11582 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11583 } 11584 } 11585 11586 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11587 boolean allowed = false; 11588 final int NP = PackageParser.NEW_PERMISSIONS.length; 11589 for (int ip=0; ip<NP; ip++) { 11590 final PackageParser.NewPermissionInfo npi 11591 = PackageParser.NEW_PERMISSIONS[ip]; 11592 if (npi.name.equals(perm) 11593 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11594 allowed = true; 11595 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11596 + pkg.packageName); 11597 break; 11598 } 11599 } 11600 return allowed; 11601 } 11602 11603 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11604 BasePermission bp, PermissionsState origPermissions) { 11605 boolean privilegedPermission = (bp.protectionLevel 11606 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11607 boolean privappPermissionsDisable = 11608 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11609 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11610 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11611 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11612 && !platformPackage && platformPermission) { 11613 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11614 .getPrivAppPermissions(pkg.packageName); 11615 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11616 if (!whitelisted) { 11617 Slog.w(TAG, "Privileged permission " + perm + " for package " 11618 + pkg.packageName + " - not in privapp-permissions whitelist"); 11619 if (!mSystemReady) { 11620 if (mPrivappPermissionsViolations == null) { 11621 mPrivappPermissionsViolations = new ArraySet<>(); 11622 } 11623 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11624 } 11625 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11626 return false; 11627 } 11628 } 11629 } 11630 boolean allowed = (compareSignatures( 11631 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11632 == PackageManager.SIGNATURE_MATCH) 11633 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11634 == PackageManager.SIGNATURE_MATCH); 11635 if (!allowed && privilegedPermission) { 11636 if (isSystemApp(pkg)) { 11637 // For updated system applications, a system permission 11638 // is granted only if it had been defined by the original application. 11639 if (pkg.isUpdatedSystemApp()) { 11640 final PackageSetting sysPs = mSettings 11641 .getDisabledSystemPkgLPr(pkg.packageName); 11642 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11643 // If the original was granted this permission, we take 11644 // that grant decision as read and propagate it to the 11645 // update. 11646 if (sysPs.isPrivileged()) { 11647 allowed = true; 11648 } 11649 } else { 11650 // The system apk may have been updated with an older 11651 // version of the one on the data partition, but which 11652 // granted a new system permission that it didn't have 11653 // before. In this case we do want to allow the app to 11654 // now get the new permission if the ancestral apk is 11655 // privileged to get it. 11656 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11657 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11658 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11659 allowed = true; 11660 break; 11661 } 11662 } 11663 } 11664 // Also if a privileged parent package on the system image or any of 11665 // its children requested a privileged permission, the updated child 11666 // packages can also get the permission. 11667 if (pkg.parentPackage != null) { 11668 final PackageSetting disabledSysParentPs = mSettings 11669 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11670 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11671 && disabledSysParentPs.isPrivileged()) { 11672 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11673 allowed = true; 11674 } else if (disabledSysParentPs.pkg.childPackages != null) { 11675 final int count = disabledSysParentPs.pkg.childPackages.size(); 11676 for (int i = 0; i < count; i++) { 11677 PackageParser.Package disabledSysChildPkg = 11678 disabledSysParentPs.pkg.childPackages.get(i); 11679 if (isPackageRequestingPermission(disabledSysChildPkg, 11680 perm)) { 11681 allowed = true; 11682 break; 11683 } 11684 } 11685 } 11686 } 11687 } 11688 } 11689 } else { 11690 allowed = isPrivilegedApp(pkg); 11691 } 11692 } 11693 } 11694 if (!allowed) { 11695 if (!allowed && (bp.protectionLevel 11696 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11697 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11698 // If this was a previously normal/dangerous permission that got moved 11699 // to a system permission as part of the runtime permission redesign, then 11700 // we still want to blindly grant it to old apps. 11701 allowed = true; 11702 } 11703 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11704 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11705 // If this permission is to be granted to the system installer and 11706 // this app is an installer, then it gets the permission. 11707 allowed = true; 11708 } 11709 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11710 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11711 // If this permission is to be granted to the system verifier and 11712 // this app is a verifier, then it gets the permission. 11713 allowed = true; 11714 } 11715 if (!allowed && (bp.protectionLevel 11716 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11717 && isSystemApp(pkg)) { 11718 // Any pre-installed system app is allowed to get this permission. 11719 allowed = true; 11720 } 11721 if (!allowed && (bp.protectionLevel 11722 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11723 // For development permissions, a development permission 11724 // is granted only if it was already granted. 11725 allowed = origPermissions.hasInstallPermission(perm); 11726 } 11727 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11728 && pkg.packageName.equals(mSetupWizardPackage)) { 11729 // If this permission is to be granted to the system setup wizard and 11730 // this app is a setup wizard, then it gets the permission. 11731 allowed = true; 11732 } 11733 } 11734 return allowed; 11735 } 11736 11737 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11738 final int permCount = pkg.requestedPermissions.size(); 11739 for (int j = 0; j < permCount; j++) { 11740 String requestedPermission = pkg.requestedPermissions.get(j); 11741 if (permission.equals(requestedPermission)) { 11742 return true; 11743 } 11744 } 11745 return false; 11746 } 11747 11748 final class ActivityIntentResolver 11749 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11750 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11751 boolean defaultOnly, int userId) { 11752 if (!sUserManager.exists(userId)) return null; 11753 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11754 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11755 } 11756 11757 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11758 int userId) { 11759 if (!sUserManager.exists(userId)) return null; 11760 mFlags = flags; 11761 return super.queryIntent(intent, resolvedType, 11762 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11763 userId); 11764 } 11765 11766 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11767 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11768 if (!sUserManager.exists(userId)) return null; 11769 if (packageActivities == null) { 11770 return null; 11771 } 11772 mFlags = flags; 11773 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11774 final int N = packageActivities.size(); 11775 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11776 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11777 11778 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11779 for (int i = 0; i < N; ++i) { 11780 intentFilters = packageActivities.get(i).intents; 11781 if (intentFilters != null && intentFilters.size() > 0) { 11782 PackageParser.ActivityIntentInfo[] array = 11783 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11784 intentFilters.toArray(array); 11785 listCut.add(array); 11786 } 11787 } 11788 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11789 } 11790 11791 /** 11792 * Finds a privileged activity that matches the specified activity names. 11793 */ 11794 private PackageParser.Activity findMatchingActivity( 11795 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11796 for (PackageParser.Activity sysActivity : activityList) { 11797 if (sysActivity.info.name.equals(activityInfo.name)) { 11798 return sysActivity; 11799 } 11800 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11801 return sysActivity; 11802 } 11803 if (sysActivity.info.targetActivity != null) { 11804 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11805 return sysActivity; 11806 } 11807 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11808 return sysActivity; 11809 } 11810 } 11811 } 11812 return null; 11813 } 11814 11815 public class IterGenerator<E> { 11816 public Iterator<E> generate(ActivityIntentInfo info) { 11817 return null; 11818 } 11819 } 11820 11821 public class ActionIterGenerator extends IterGenerator<String> { 11822 @Override 11823 public Iterator<String> generate(ActivityIntentInfo info) { 11824 return info.actionsIterator(); 11825 } 11826 } 11827 11828 public class CategoriesIterGenerator extends IterGenerator<String> { 11829 @Override 11830 public Iterator<String> generate(ActivityIntentInfo info) { 11831 return info.categoriesIterator(); 11832 } 11833 } 11834 11835 public class SchemesIterGenerator extends IterGenerator<String> { 11836 @Override 11837 public Iterator<String> generate(ActivityIntentInfo info) { 11838 return info.schemesIterator(); 11839 } 11840 } 11841 11842 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11843 @Override 11844 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11845 return info.authoritiesIterator(); 11846 } 11847 } 11848 11849 /** 11850 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11851 * MODIFIED. Do not pass in a list that should not be changed. 11852 */ 11853 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11854 IterGenerator<T> generator, Iterator<T> searchIterator) { 11855 // loop through the set of actions; every one must be found in the intent filter 11856 while (searchIterator.hasNext()) { 11857 // we must have at least one filter in the list to consider a match 11858 if (intentList.size() == 0) { 11859 break; 11860 } 11861 11862 final T searchAction = searchIterator.next(); 11863 11864 // loop through the set of intent filters 11865 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11866 while (intentIter.hasNext()) { 11867 final ActivityIntentInfo intentInfo = intentIter.next(); 11868 boolean selectionFound = false; 11869 11870 // loop through the intent filter's selection criteria; at least one 11871 // of them must match the searched criteria 11872 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11873 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11874 final T intentSelection = intentSelectionIter.next(); 11875 if (intentSelection != null && intentSelection.equals(searchAction)) { 11876 selectionFound = true; 11877 break; 11878 } 11879 } 11880 11881 // the selection criteria wasn't found in this filter's set; this filter 11882 // is not a potential match 11883 if (!selectionFound) { 11884 intentIter.remove(); 11885 } 11886 } 11887 } 11888 } 11889 11890 private boolean isProtectedAction(ActivityIntentInfo filter) { 11891 final Iterator<String> actionsIter = filter.actionsIterator(); 11892 while (actionsIter != null && actionsIter.hasNext()) { 11893 final String filterAction = actionsIter.next(); 11894 if (PROTECTED_ACTIONS.contains(filterAction)) { 11895 return true; 11896 } 11897 } 11898 return false; 11899 } 11900 11901 /** 11902 * Adjusts the priority of the given intent filter according to policy. 11903 * <p> 11904 * <ul> 11905 * <li>The priority for non privileged applications is capped to '0'</li> 11906 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11907 * <li>The priority for unbundled updates to privileged applications is capped to the 11908 * priority defined on the system partition</li> 11909 * </ul> 11910 * <p> 11911 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11912 * allowed to obtain any priority on any action. 11913 */ 11914 private void adjustPriority( 11915 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11916 // nothing to do; priority is fine as-is 11917 if (intent.getPriority() <= 0) { 11918 return; 11919 } 11920 11921 final ActivityInfo activityInfo = intent.activity.info; 11922 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11923 11924 final boolean privilegedApp = 11925 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11926 if (!privilegedApp) { 11927 // non-privileged applications can never define a priority >0 11928 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11929 + " package: " + applicationInfo.packageName 11930 + " activity: " + intent.activity.className 11931 + " origPrio: " + intent.getPriority()); 11932 intent.setPriority(0); 11933 return; 11934 } 11935 11936 if (systemActivities == null) { 11937 // the system package is not disabled; we're parsing the system partition 11938 if (isProtectedAction(intent)) { 11939 if (mDeferProtectedFilters) { 11940 // We can't deal with these just yet. No component should ever obtain a 11941 // >0 priority for a protected actions, with ONE exception -- the setup 11942 // wizard. The setup wizard, however, cannot be known until we're able to 11943 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11944 // until all intent filters have been processed. Chicken, meet egg. 11945 // Let the filter temporarily have a high priority and rectify the 11946 // priorities after all system packages have been scanned. 11947 mProtectedFilters.add(intent); 11948 if (DEBUG_FILTERS) { 11949 Slog.i(TAG, "Protected action; save for later;" 11950 + " package: " + applicationInfo.packageName 11951 + " activity: " + intent.activity.className 11952 + " origPrio: " + intent.getPriority()); 11953 } 11954 return; 11955 } else { 11956 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11957 Slog.i(TAG, "No setup wizard;" 11958 + " All protected intents capped to priority 0"); 11959 } 11960 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11961 if (DEBUG_FILTERS) { 11962 Slog.i(TAG, "Found setup wizard;" 11963 + " allow priority " + intent.getPriority() + ";" 11964 + " package: " + intent.activity.info.packageName 11965 + " activity: " + intent.activity.className 11966 + " priority: " + intent.getPriority()); 11967 } 11968 // setup wizard gets whatever it wants 11969 return; 11970 } 11971 Slog.w(TAG, "Protected action; cap priority to 0;" 11972 + " package: " + intent.activity.info.packageName 11973 + " activity: " + intent.activity.className 11974 + " origPrio: " + intent.getPriority()); 11975 intent.setPriority(0); 11976 return; 11977 } 11978 } 11979 // privileged apps on the system image get whatever priority they request 11980 return; 11981 } 11982 11983 // privileged app unbundled update ... try to find the same activity 11984 final PackageParser.Activity foundActivity = 11985 findMatchingActivity(systemActivities, activityInfo); 11986 if (foundActivity == null) { 11987 // this is a new activity; it cannot obtain >0 priority 11988 if (DEBUG_FILTERS) { 11989 Slog.i(TAG, "New activity; cap priority to 0;" 11990 + " package: " + applicationInfo.packageName 11991 + " activity: " + intent.activity.className 11992 + " origPrio: " + intent.getPriority()); 11993 } 11994 intent.setPriority(0); 11995 return; 11996 } 11997 11998 // found activity, now check for filter equivalence 11999 12000 // a shallow copy is enough; we modify the list, not its contents 12001 final List<ActivityIntentInfo> intentListCopy = 12002 new ArrayList<>(foundActivity.intents); 12003 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12004 12005 // find matching action subsets 12006 final Iterator<String> actionsIterator = intent.actionsIterator(); 12007 if (actionsIterator != null) { 12008 getIntentListSubset( 12009 intentListCopy, new ActionIterGenerator(), actionsIterator); 12010 if (intentListCopy.size() == 0) { 12011 // no more intents to match; we're not equivalent 12012 if (DEBUG_FILTERS) { 12013 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12014 + " package: " + applicationInfo.packageName 12015 + " activity: " + intent.activity.className 12016 + " origPrio: " + intent.getPriority()); 12017 } 12018 intent.setPriority(0); 12019 return; 12020 } 12021 } 12022 12023 // find matching category subsets 12024 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12025 if (categoriesIterator != null) { 12026 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12027 categoriesIterator); 12028 if (intentListCopy.size() == 0) { 12029 // no more intents to match; we're not equivalent 12030 if (DEBUG_FILTERS) { 12031 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12032 + " package: " + applicationInfo.packageName 12033 + " activity: " + intent.activity.className 12034 + " origPrio: " + intent.getPriority()); 12035 } 12036 intent.setPriority(0); 12037 return; 12038 } 12039 } 12040 12041 // find matching schemes subsets 12042 final Iterator<String> schemesIterator = intent.schemesIterator(); 12043 if (schemesIterator != null) { 12044 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12045 schemesIterator); 12046 if (intentListCopy.size() == 0) { 12047 // no more intents to match; we're not equivalent 12048 if (DEBUG_FILTERS) { 12049 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12050 + " package: " + applicationInfo.packageName 12051 + " activity: " + intent.activity.className 12052 + " origPrio: " + intent.getPriority()); 12053 } 12054 intent.setPriority(0); 12055 return; 12056 } 12057 } 12058 12059 // find matching authorities subsets 12060 final Iterator<IntentFilter.AuthorityEntry> 12061 authoritiesIterator = intent.authoritiesIterator(); 12062 if (authoritiesIterator != null) { 12063 getIntentListSubset(intentListCopy, 12064 new AuthoritiesIterGenerator(), 12065 authoritiesIterator); 12066 if (intentListCopy.size() == 0) { 12067 // no more intents to match; we're not equivalent 12068 if (DEBUG_FILTERS) { 12069 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12070 + " package: " + applicationInfo.packageName 12071 + " activity: " + intent.activity.className 12072 + " origPrio: " + intent.getPriority()); 12073 } 12074 intent.setPriority(0); 12075 return; 12076 } 12077 } 12078 12079 // we found matching filter(s); app gets the max priority of all intents 12080 int cappedPriority = 0; 12081 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12082 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12083 } 12084 if (intent.getPriority() > cappedPriority) { 12085 if (DEBUG_FILTERS) { 12086 Slog.i(TAG, "Found matching filter(s);" 12087 + " cap priority to " + cappedPriority + ";" 12088 + " package: " + applicationInfo.packageName 12089 + " activity: " + intent.activity.className 12090 + " origPrio: " + intent.getPriority()); 12091 } 12092 intent.setPriority(cappedPriority); 12093 return; 12094 } 12095 // all this for nothing; the requested priority was <= what was on the system 12096 } 12097 12098 public final void addActivity(PackageParser.Activity a, String type) { 12099 mActivities.put(a.getComponentName(), a); 12100 if (DEBUG_SHOW_INFO) 12101 Log.v( 12102 TAG, " " + type + " " + 12103 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12104 if (DEBUG_SHOW_INFO) 12105 Log.v(TAG, " Class=" + a.info.name); 12106 final int NI = a.intents.size(); 12107 for (int j=0; j<NI; j++) { 12108 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12109 if ("activity".equals(type)) { 12110 final PackageSetting ps = 12111 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12112 final List<PackageParser.Activity> systemActivities = 12113 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12114 adjustPriority(systemActivities, intent); 12115 } 12116 if (DEBUG_SHOW_INFO) { 12117 Log.v(TAG, " IntentFilter:"); 12118 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12119 } 12120 if (!intent.debugCheck()) { 12121 Log.w(TAG, "==> For Activity " + a.info.name); 12122 } 12123 addFilter(intent); 12124 } 12125 } 12126 12127 public final void removeActivity(PackageParser.Activity a, String type) { 12128 mActivities.remove(a.getComponentName()); 12129 if (DEBUG_SHOW_INFO) { 12130 Log.v(TAG, " " + type + " " 12131 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12132 : a.info.name) + ":"); 12133 Log.v(TAG, " Class=" + a.info.name); 12134 } 12135 final int NI = a.intents.size(); 12136 for (int j=0; j<NI; j++) { 12137 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12138 if (DEBUG_SHOW_INFO) { 12139 Log.v(TAG, " IntentFilter:"); 12140 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12141 } 12142 removeFilter(intent); 12143 } 12144 } 12145 12146 @Override 12147 protected boolean allowFilterResult( 12148 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12149 ActivityInfo filterAi = filter.activity.info; 12150 for (int i=dest.size()-1; i>=0; i--) { 12151 ActivityInfo destAi = dest.get(i).activityInfo; 12152 if (destAi.name == filterAi.name 12153 && destAi.packageName == filterAi.packageName) { 12154 return false; 12155 } 12156 } 12157 return true; 12158 } 12159 12160 @Override 12161 protected ActivityIntentInfo[] newArray(int size) { 12162 return new ActivityIntentInfo[size]; 12163 } 12164 12165 @Override 12166 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12167 if (!sUserManager.exists(userId)) return true; 12168 PackageParser.Package p = filter.activity.owner; 12169 if (p != null) { 12170 PackageSetting ps = (PackageSetting)p.mExtras; 12171 if (ps != null) { 12172 // System apps are never considered stopped for purposes of 12173 // filtering, because there may be no way for the user to 12174 // actually re-launch them. 12175 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12176 && ps.getStopped(userId); 12177 } 12178 } 12179 return false; 12180 } 12181 12182 @Override 12183 protected boolean isPackageForFilter(String packageName, 12184 PackageParser.ActivityIntentInfo info) { 12185 return packageName.equals(info.activity.owner.packageName); 12186 } 12187 12188 @Override 12189 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12190 int match, int userId) { 12191 if (!sUserManager.exists(userId)) return null; 12192 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12193 return null; 12194 } 12195 final PackageParser.Activity activity = info.activity; 12196 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12197 if (ps == null) { 12198 return null; 12199 } 12200 final PackageUserState userState = ps.readUserState(userId); 12201 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12202 userState, userId); 12203 if (ai == null) { 12204 return null; 12205 } 12206 final boolean matchVisibleToInstantApp = 12207 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12208 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12209 // throw out filters that aren't visible to ephemeral apps 12210 if (matchVisibleToInstantApp 12211 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12212 return null; 12213 } 12214 // throw out ephemeral filters if we're not explicitly requesting them 12215 if (!isInstantApp && userState.instantApp) { 12216 return null; 12217 } 12218 final ResolveInfo res = new ResolveInfo(); 12219 res.activityInfo = ai; 12220 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12221 res.filter = info; 12222 } 12223 if (info != null) { 12224 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12225 } 12226 res.priority = info.getPriority(); 12227 res.preferredOrder = activity.owner.mPreferredOrder; 12228 //System.out.println("Result: " + res.activityInfo.className + 12229 // " = " + res.priority); 12230 res.match = match; 12231 res.isDefault = info.hasDefault; 12232 res.labelRes = info.labelRes; 12233 res.nonLocalizedLabel = info.nonLocalizedLabel; 12234 if (userNeedsBadging(userId)) { 12235 res.noResourceId = true; 12236 } else { 12237 res.icon = info.icon; 12238 } 12239 res.iconResourceId = info.icon; 12240 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12241 return res; 12242 } 12243 12244 @Override 12245 protected void sortResults(List<ResolveInfo> results) { 12246 Collections.sort(results, mResolvePrioritySorter); 12247 } 12248 12249 @Override 12250 protected void dumpFilter(PrintWriter out, String prefix, 12251 PackageParser.ActivityIntentInfo filter) { 12252 out.print(prefix); out.print( 12253 Integer.toHexString(System.identityHashCode(filter.activity))); 12254 out.print(' '); 12255 filter.activity.printComponentShortName(out); 12256 out.print(" filter "); 12257 out.println(Integer.toHexString(System.identityHashCode(filter))); 12258 } 12259 12260 @Override 12261 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12262 return filter.activity; 12263 } 12264 12265 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12266 PackageParser.Activity activity = (PackageParser.Activity)label; 12267 out.print(prefix); out.print( 12268 Integer.toHexString(System.identityHashCode(activity))); 12269 out.print(' '); 12270 activity.printComponentShortName(out); 12271 if (count > 1) { 12272 out.print(" ("); out.print(count); out.print(" filters)"); 12273 } 12274 out.println(); 12275 } 12276 12277 // Keys are String (activity class name), values are Activity. 12278 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12279 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12280 private int mFlags; 12281 } 12282 12283 private final class ServiceIntentResolver 12284 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12285 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12286 boolean defaultOnly, int userId) { 12287 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12288 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12289 } 12290 12291 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12292 int userId) { 12293 if (!sUserManager.exists(userId)) return null; 12294 mFlags = flags; 12295 return super.queryIntent(intent, resolvedType, 12296 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12297 userId); 12298 } 12299 12300 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12301 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12302 if (!sUserManager.exists(userId)) return null; 12303 if (packageServices == null) { 12304 return null; 12305 } 12306 mFlags = flags; 12307 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12308 final int N = packageServices.size(); 12309 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12310 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12311 12312 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12313 for (int i = 0; i < N; ++i) { 12314 intentFilters = packageServices.get(i).intents; 12315 if (intentFilters != null && intentFilters.size() > 0) { 12316 PackageParser.ServiceIntentInfo[] array = 12317 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12318 intentFilters.toArray(array); 12319 listCut.add(array); 12320 } 12321 } 12322 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12323 } 12324 12325 public final void addService(PackageParser.Service s) { 12326 mServices.put(s.getComponentName(), s); 12327 if (DEBUG_SHOW_INFO) { 12328 Log.v(TAG, " " 12329 + (s.info.nonLocalizedLabel != null 12330 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12331 Log.v(TAG, " Class=" + s.info.name); 12332 } 12333 final int NI = s.intents.size(); 12334 int j; 12335 for (j=0; j<NI; j++) { 12336 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12337 if (DEBUG_SHOW_INFO) { 12338 Log.v(TAG, " IntentFilter:"); 12339 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12340 } 12341 if (!intent.debugCheck()) { 12342 Log.w(TAG, "==> For Service " + s.info.name); 12343 } 12344 addFilter(intent); 12345 } 12346 } 12347 12348 public final void removeService(PackageParser.Service s) { 12349 mServices.remove(s.getComponentName()); 12350 if (DEBUG_SHOW_INFO) { 12351 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12352 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12353 Log.v(TAG, " Class=" + s.info.name); 12354 } 12355 final int NI = s.intents.size(); 12356 int j; 12357 for (j=0; j<NI; j++) { 12358 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12359 if (DEBUG_SHOW_INFO) { 12360 Log.v(TAG, " IntentFilter:"); 12361 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12362 } 12363 removeFilter(intent); 12364 } 12365 } 12366 12367 @Override 12368 protected boolean allowFilterResult( 12369 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12370 ServiceInfo filterSi = filter.service.info; 12371 for (int i=dest.size()-1; i>=0; i--) { 12372 ServiceInfo destAi = dest.get(i).serviceInfo; 12373 if (destAi.name == filterSi.name 12374 && destAi.packageName == filterSi.packageName) { 12375 return false; 12376 } 12377 } 12378 return true; 12379 } 12380 12381 @Override 12382 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12383 return new PackageParser.ServiceIntentInfo[size]; 12384 } 12385 12386 @Override 12387 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12388 if (!sUserManager.exists(userId)) return true; 12389 PackageParser.Package p = filter.service.owner; 12390 if (p != null) { 12391 PackageSetting ps = (PackageSetting)p.mExtras; 12392 if (ps != null) { 12393 // System apps are never considered stopped for purposes of 12394 // filtering, because there may be no way for the user to 12395 // actually re-launch them. 12396 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12397 && ps.getStopped(userId); 12398 } 12399 } 12400 return false; 12401 } 12402 12403 @Override 12404 protected boolean isPackageForFilter(String packageName, 12405 PackageParser.ServiceIntentInfo info) { 12406 return packageName.equals(info.service.owner.packageName); 12407 } 12408 12409 @Override 12410 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12411 int match, int userId) { 12412 if (!sUserManager.exists(userId)) return null; 12413 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12414 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12415 return null; 12416 } 12417 final PackageParser.Service service = info.service; 12418 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12419 if (ps == null) { 12420 return null; 12421 } 12422 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12423 ps.readUserState(userId), userId); 12424 if (si == null) { 12425 return null; 12426 } 12427 final ResolveInfo res = new ResolveInfo(); 12428 res.serviceInfo = si; 12429 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12430 res.filter = filter; 12431 } 12432 res.priority = info.getPriority(); 12433 res.preferredOrder = service.owner.mPreferredOrder; 12434 res.match = match; 12435 res.isDefault = info.hasDefault; 12436 res.labelRes = info.labelRes; 12437 res.nonLocalizedLabel = info.nonLocalizedLabel; 12438 res.icon = info.icon; 12439 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12440 return res; 12441 } 12442 12443 @Override 12444 protected void sortResults(List<ResolveInfo> results) { 12445 Collections.sort(results, mResolvePrioritySorter); 12446 } 12447 12448 @Override 12449 protected void dumpFilter(PrintWriter out, String prefix, 12450 PackageParser.ServiceIntentInfo filter) { 12451 out.print(prefix); out.print( 12452 Integer.toHexString(System.identityHashCode(filter.service))); 12453 out.print(' '); 12454 filter.service.printComponentShortName(out); 12455 out.print(" filter "); 12456 out.println(Integer.toHexString(System.identityHashCode(filter))); 12457 } 12458 12459 @Override 12460 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12461 return filter.service; 12462 } 12463 12464 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12465 PackageParser.Service service = (PackageParser.Service)label; 12466 out.print(prefix); out.print( 12467 Integer.toHexString(System.identityHashCode(service))); 12468 out.print(' '); 12469 service.printComponentShortName(out); 12470 if (count > 1) { 12471 out.print(" ("); out.print(count); out.print(" filters)"); 12472 } 12473 out.println(); 12474 } 12475 12476// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12477// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12478// final List<ResolveInfo> retList = Lists.newArrayList(); 12479// while (i.hasNext()) { 12480// final ResolveInfo resolveInfo = (ResolveInfo) i; 12481// if (isEnabledLP(resolveInfo.serviceInfo)) { 12482// retList.add(resolveInfo); 12483// } 12484// } 12485// return retList; 12486// } 12487 12488 // Keys are String (activity class name), values are Activity. 12489 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12490 = new ArrayMap<ComponentName, PackageParser.Service>(); 12491 private int mFlags; 12492 } 12493 12494 private final class ProviderIntentResolver 12495 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12496 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12497 boolean defaultOnly, int userId) { 12498 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12499 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12500 } 12501 12502 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12503 int userId) { 12504 if (!sUserManager.exists(userId)) 12505 return null; 12506 mFlags = flags; 12507 return super.queryIntent(intent, resolvedType, 12508 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12509 userId); 12510 } 12511 12512 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12513 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12514 if (!sUserManager.exists(userId)) 12515 return null; 12516 if (packageProviders == null) { 12517 return null; 12518 } 12519 mFlags = flags; 12520 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12521 final int N = packageProviders.size(); 12522 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12523 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12524 12525 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12526 for (int i = 0; i < N; ++i) { 12527 intentFilters = packageProviders.get(i).intents; 12528 if (intentFilters != null && intentFilters.size() > 0) { 12529 PackageParser.ProviderIntentInfo[] array = 12530 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12531 intentFilters.toArray(array); 12532 listCut.add(array); 12533 } 12534 } 12535 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12536 } 12537 12538 public final void addProvider(PackageParser.Provider p) { 12539 if (mProviders.containsKey(p.getComponentName())) { 12540 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12541 return; 12542 } 12543 12544 mProviders.put(p.getComponentName(), p); 12545 if (DEBUG_SHOW_INFO) { 12546 Log.v(TAG, " " 12547 + (p.info.nonLocalizedLabel != null 12548 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12549 Log.v(TAG, " Class=" + p.info.name); 12550 } 12551 final int NI = p.intents.size(); 12552 int j; 12553 for (j = 0; j < NI; j++) { 12554 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12555 if (DEBUG_SHOW_INFO) { 12556 Log.v(TAG, " IntentFilter:"); 12557 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12558 } 12559 if (!intent.debugCheck()) { 12560 Log.w(TAG, "==> For Provider " + p.info.name); 12561 } 12562 addFilter(intent); 12563 } 12564 } 12565 12566 public final void removeProvider(PackageParser.Provider p) { 12567 mProviders.remove(p.getComponentName()); 12568 if (DEBUG_SHOW_INFO) { 12569 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12570 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12571 Log.v(TAG, " Class=" + p.info.name); 12572 } 12573 final int NI = p.intents.size(); 12574 int j; 12575 for (j = 0; j < NI; j++) { 12576 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12577 if (DEBUG_SHOW_INFO) { 12578 Log.v(TAG, " IntentFilter:"); 12579 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12580 } 12581 removeFilter(intent); 12582 } 12583 } 12584 12585 @Override 12586 protected boolean allowFilterResult( 12587 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12588 ProviderInfo filterPi = filter.provider.info; 12589 for (int i = dest.size() - 1; i >= 0; i--) { 12590 ProviderInfo destPi = dest.get(i).providerInfo; 12591 if (destPi.name == filterPi.name 12592 && destPi.packageName == filterPi.packageName) { 12593 return false; 12594 } 12595 } 12596 return true; 12597 } 12598 12599 @Override 12600 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12601 return new PackageParser.ProviderIntentInfo[size]; 12602 } 12603 12604 @Override 12605 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12606 if (!sUserManager.exists(userId)) 12607 return true; 12608 PackageParser.Package p = filter.provider.owner; 12609 if (p != null) { 12610 PackageSetting ps = (PackageSetting) p.mExtras; 12611 if (ps != null) { 12612 // System apps are never considered stopped for purposes of 12613 // filtering, because there may be no way for the user to 12614 // actually re-launch them. 12615 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12616 && ps.getStopped(userId); 12617 } 12618 } 12619 return false; 12620 } 12621 12622 @Override 12623 protected boolean isPackageForFilter(String packageName, 12624 PackageParser.ProviderIntentInfo info) { 12625 return packageName.equals(info.provider.owner.packageName); 12626 } 12627 12628 @Override 12629 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12630 int match, int userId) { 12631 if (!sUserManager.exists(userId)) 12632 return null; 12633 final PackageParser.ProviderIntentInfo info = filter; 12634 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12635 return null; 12636 } 12637 final PackageParser.Provider provider = info.provider; 12638 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12639 if (ps == null) { 12640 return null; 12641 } 12642 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12643 ps.readUserState(userId), userId); 12644 if (pi == null) { 12645 return null; 12646 } 12647 final ResolveInfo res = new ResolveInfo(); 12648 res.providerInfo = pi; 12649 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12650 res.filter = filter; 12651 } 12652 res.priority = info.getPriority(); 12653 res.preferredOrder = provider.owner.mPreferredOrder; 12654 res.match = match; 12655 res.isDefault = info.hasDefault; 12656 res.labelRes = info.labelRes; 12657 res.nonLocalizedLabel = info.nonLocalizedLabel; 12658 res.icon = info.icon; 12659 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12660 return res; 12661 } 12662 12663 @Override 12664 protected void sortResults(List<ResolveInfo> results) { 12665 Collections.sort(results, mResolvePrioritySorter); 12666 } 12667 12668 @Override 12669 protected void dumpFilter(PrintWriter out, String prefix, 12670 PackageParser.ProviderIntentInfo filter) { 12671 out.print(prefix); 12672 out.print( 12673 Integer.toHexString(System.identityHashCode(filter.provider))); 12674 out.print(' '); 12675 filter.provider.printComponentShortName(out); 12676 out.print(" filter "); 12677 out.println(Integer.toHexString(System.identityHashCode(filter))); 12678 } 12679 12680 @Override 12681 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12682 return filter.provider; 12683 } 12684 12685 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12686 PackageParser.Provider provider = (PackageParser.Provider)label; 12687 out.print(prefix); out.print( 12688 Integer.toHexString(System.identityHashCode(provider))); 12689 out.print(' '); 12690 provider.printComponentShortName(out); 12691 if (count > 1) { 12692 out.print(" ("); out.print(count); out.print(" filters)"); 12693 } 12694 out.println(); 12695 } 12696 12697 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12698 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12699 private int mFlags; 12700 } 12701 12702 static final class EphemeralIntentResolver 12703 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 12704 /** 12705 * The result that has the highest defined order. Ordering applies on a 12706 * per-package basis. Mapping is from package name to Pair of order and 12707 * EphemeralResolveInfo. 12708 * <p> 12709 * NOTE: This is implemented as a field variable for convenience and efficiency. 12710 * By having a field variable, we're able to track filter ordering as soon as 12711 * a non-zero order is defined. Otherwise, multiple loops across the result set 12712 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12713 * this needs to be contained entirely within {@link #filterResults()}. 12714 */ 12715 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12716 12717 @Override 12718 protected EphemeralResponse[] newArray(int size) { 12719 return new EphemeralResponse[size]; 12720 } 12721 12722 @Override 12723 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 12724 return true; 12725 } 12726 12727 @Override 12728 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 12729 int userId) { 12730 if (!sUserManager.exists(userId)) { 12731 return null; 12732 } 12733 final String packageName = responseObj.resolveInfo.getPackageName(); 12734 final Integer order = responseObj.getOrder(); 12735 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12736 mOrderResult.get(packageName); 12737 // ordering is enabled and this item's order isn't high enough 12738 if (lastOrderResult != null && lastOrderResult.first >= order) { 12739 return null; 12740 } 12741 final EphemeralResolveInfo res = responseObj.resolveInfo; 12742 if (order > 0) { 12743 // non-zero order, enable ordering 12744 mOrderResult.put(packageName, new Pair<>(order, res)); 12745 } 12746 return responseObj; 12747 } 12748 12749 @Override 12750 protected void filterResults(List<EphemeralResponse> results) { 12751 // only do work if ordering is enabled [most of the time it won't be] 12752 if (mOrderResult.size() == 0) { 12753 return; 12754 } 12755 int resultSize = results.size(); 12756 for (int i = 0; i < resultSize; i++) { 12757 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12758 final String packageName = info.getPackageName(); 12759 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12760 if (savedInfo == null) { 12761 // package doesn't having ordering 12762 continue; 12763 } 12764 if (savedInfo.second == info) { 12765 // circled back to the highest ordered item; remove from order list 12766 mOrderResult.remove(savedInfo); 12767 if (mOrderResult.size() == 0) { 12768 // no more ordered items 12769 break; 12770 } 12771 continue; 12772 } 12773 // item has a worse order, remove it from the result list 12774 results.remove(i); 12775 resultSize--; 12776 i--; 12777 } 12778 } 12779 } 12780 12781 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12782 new Comparator<ResolveInfo>() { 12783 public int compare(ResolveInfo r1, ResolveInfo r2) { 12784 int v1 = r1.priority; 12785 int v2 = r2.priority; 12786 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12787 if (v1 != v2) { 12788 return (v1 > v2) ? -1 : 1; 12789 } 12790 v1 = r1.preferredOrder; 12791 v2 = r2.preferredOrder; 12792 if (v1 != v2) { 12793 return (v1 > v2) ? -1 : 1; 12794 } 12795 if (r1.isDefault != r2.isDefault) { 12796 return r1.isDefault ? -1 : 1; 12797 } 12798 v1 = r1.match; 12799 v2 = r2.match; 12800 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12801 if (v1 != v2) { 12802 return (v1 > v2) ? -1 : 1; 12803 } 12804 if (r1.system != r2.system) { 12805 return r1.system ? -1 : 1; 12806 } 12807 if (r1.activityInfo != null) { 12808 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12809 } 12810 if (r1.serviceInfo != null) { 12811 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12812 } 12813 if (r1.providerInfo != null) { 12814 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12815 } 12816 return 0; 12817 } 12818 }; 12819 12820 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12821 new Comparator<ProviderInfo>() { 12822 public int compare(ProviderInfo p1, ProviderInfo p2) { 12823 final int v1 = p1.initOrder; 12824 final int v2 = p2.initOrder; 12825 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12826 } 12827 }; 12828 12829 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12830 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12831 final int[] userIds) { 12832 mHandler.post(new Runnable() { 12833 @Override 12834 public void run() { 12835 try { 12836 final IActivityManager am = ActivityManager.getService(); 12837 if (am == null) return; 12838 final int[] resolvedUserIds; 12839 if (userIds == null) { 12840 resolvedUserIds = am.getRunningUserIds(); 12841 } else { 12842 resolvedUserIds = userIds; 12843 } 12844 for (int id : resolvedUserIds) { 12845 final Intent intent = new Intent(action, 12846 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12847 if (extras != null) { 12848 intent.putExtras(extras); 12849 } 12850 if (targetPkg != null) { 12851 intent.setPackage(targetPkg); 12852 } 12853 // Modify the UID when posting to other users 12854 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12855 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12856 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12857 intent.putExtra(Intent.EXTRA_UID, uid); 12858 } 12859 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12860 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12861 if (DEBUG_BROADCASTS) { 12862 RuntimeException here = new RuntimeException("here"); 12863 here.fillInStackTrace(); 12864 Slog.d(TAG, "Sending to user " + id + ": " 12865 + intent.toShortString(false, true, false, false) 12866 + " " + intent.getExtras(), here); 12867 } 12868 am.broadcastIntent(null, intent, null, finishedReceiver, 12869 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12870 null, finishedReceiver != null, false, id); 12871 } 12872 } catch (RemoteException ex) { 12873 } 12874 } 12875 }); 12876 } 12877 12878 /** 12879 * Check if the external storage media is available. This is true if there 12880 * is a mounted external storage medium or if the external storage is 12881 * emulated. 12882 */ 12883 private boolean isExternalMediaAvailable() { 12884 return mMediaMounted || Environment.isExternalStorageEmulated(); 12885 } 12886 12887 @Override 12888 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12889 // writer 12890 synchronized (mPackages) { 12891 if (!isExternalMediaAvailable()) { 12892 // If the external storage is no longer mounted at this point, 12893 // the caller may not have been able to delete all of this 12894 // packages files and can not delete any more. Bail. 12895 return null; 12896 } 12897 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12898 if (lastPackage != null) { 12899 pkgs.remove(lastPackage); 12900 } 12901 if (pkgs.size() > 0) { 12902 return pkgs.get(0); 12903 } 12904 } 12905 return null; 12906 } 12907 12908 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12909 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12910 userId, andCode ? 1 : 0, packageName); 12911 if (mSystemReady) { 12912 msg.sendToTarget(); 12913 } else { 12914 if (mPostSystemReadyMessages == null) { 12915 mPostSystemReadyMessages = new ArrayList<>(); 12916 } 12917 mPostSystemReadyMessages.add(msg); 12918 } 12919 } 12920 12921 void startCleaningPackages() { 12922 // reader 12923 if (!isExternalMediaAvailable()) { 12924 return; 12925 } 12926 synchronized (mPackages) { 12927 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12928 return; 12929 } 12930 } 12931 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12932 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12933 IActivityManager am = ActivityManager.getService(); 12934 if (am != null) { 12935 try { 12936 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12937 UserHandle.USER_SYSTEM); 12938 } catch (RemoteException e) { 12939 } 12940 } 12941 } 12942 12943 @Override 12944 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12945 int installFlags, String installerPackageName, int userId) { 12946 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12947 12948 final int callingUid = Binder.getCallingUid(); 12949 enforceCrossUserPermission(callingUid, userId, 12950 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12951 12952 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12953 try { 12954 if (observer != null) { 12955 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12956 } 12957 } catch (RemoteException re) { 12958 } 12959 return; 12960 } 12961 12962 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12963 installFlags |= PackageManager.INSTALL_FROM_ADB; 12964 12965 } else { 12966 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12967 // about installerPackageName. 12968 12969 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12970 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12971 } 12972 12973 UserHandle user; 12974 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12975 user = UserHandle.ALL; 12976 } else { 12977 user = new UserHandle(userId); 12978 } 12979 12980 // Only system components can circumvent runtime permissions when installing. 12981 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12982 && mContext.checkCallingOrSelfPermission(Manifest.permission 12983 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12984 throw new SecurityException("You need the " 12985 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12986 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12987 } 12988 12989 final File originFile = new File(originPath); 12990 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12991 12992 final Message msg = mHandler.obtainMessage(INIT_COPY); 12993 final VerificationInfo verificationInfo = new VerificationInfo( 12994 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12995 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12996 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12997 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12998 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12999 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13000 msg.obj = params; 13001 13002 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13003 System.identityHashCode(msg.obj)); 13004 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13005 System.identityHashCode(msg.obj)); 13006 13007 mHandler.sendMessage(msg); 13008 } 13009 13010 13011 /** 13012 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13013 * it is acting on behalf on an enterprise or the user). 13014 * 13015 * Note that the ordering of the conditionals in this method is important. The checks we perform 13016 * are as follows, in this order: 13017 * 13018 * 1) If the install is being performed by a system app, we can trust the app to have set the 13019 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13020 * what it is. 13021 * 2) If the install is being performed by a device or profile owner app, the install reason 13022 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13023 * set the install reason correctly. If the app targets an older SDK version where install 13024 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13025 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13026 * 3) In all other cases, the install is being performed by a regular app that is neither part 13027 * of the system nor a device or profile owner. We have no reason to believe that this app is 13028 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13029 * set to enterprise policy and if so, change it to unknown instead. 13030 */ 13031 private int fixUpInstallReason(String installerPackageName, int installerUid, 13032 int installReason) { 13033 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13034 == PERMISSION_GRANTED) { 13035 // If the install is being performed by a system app, we trust that app to have set the 13036 // install reason correctly. 13037 return installReason; 13038 } 13039 13040 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13041 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13042 if (dpm != null) { 13043 ComponentName owner = null; 13044 try { 13045 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13046 if (owner == null) { 13047 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13048 } 13049 } catch (RemoteException e) { 13050 } 13051 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13052 // If the install is being performed by a device or profile owner, the install 13053 // reason should be enterprise policy. 13054 return PackageManager.INSTALL_REASON_POLICY; 13055 } 13056 } 13057 13058 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13059 // If the install is being performed by a regular app (i.e. neither system app nor 13060 // device or profile owner), we have no reason to believe that the app is acting on 13061 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13062 // change it to unknown instead. 13063 return PackageManager.INSTALL_REASON_UNKNOWN; 13064 } 13065 13066 // If the install is being performed by a regular app and the install reason was set to any 13067 // value but enterprise policy, leave the install reason unchanged. 13068 return installReason; 13069 } 13070 13071 void installStage(String packageName, File stagedDir, String stagedCid, 13072 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13073 String installerPackageName, int installerUid, UserHandle user, 13074 Certificate[][] certificates) { 13075 if (DEBUG_EPHEMERAL) { 13076 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13077 Slog.d(TAG, "Ephemeral install of " + packageName); 13078 } 13079 } 13080 final VerificationInfo verificationInfo = new VerificationInfo( 13081 sessionParams.originatingUri, sessionParams.referrerUri, 13082 sessionParams.originatingUid, installerUid); 13083 13084 final OriginInfo origin; 13085 if (stagedDir != null) { 13086 origin = OriginInfo.fromStagedFile(stagedDir); 13087 } else { 13088 origin = OriginInfo.fromStagedContainer(stagedCid); 13089 } 13090 13091 final Message msg = mHandler.obtainMessage(INIT_COPY); 13092 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13093 sessionParams.installReason); 13094 final InstallParams params = new InstallParams(origin, null, observer, 13095 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13096 verificationInfo, user, sessionParams.abiOverride, 13097 sessionParams.grantedRuntimePermissions, certificates, installReason); 13098 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13099 msg.obj = params; 13100 13101 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13102 System.identityHashCode(msg.obj)); 13103 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13104 System.identityHashCode(msg.obj)); 13105 13106 mHandler.sendMessage(msg); 13107 } 13108 13109 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13110 int userId) { 13111 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13112 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13113 } 13114 13115 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13116 int appId, int... userIds) { 13117 if (ArrayUtils.isEmpty(userIds)) { 13118 return; 13119 } 13120 Bundle extras = new Bundle(1); 13121 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13122 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13123 13124 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13125 packageName, extras, 0, null, null, userIds); 13126 if (isSystem) { 13127 mHandler.post(() -> { 13128 for (int userId : userIds) { 13129 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13130 } 13131 } 13132 ); 13133 } 13134 } 13135 13136 /** 13137 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13138 * automatically without needing an explicit launch. 13139 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13140 */ 13141 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13142 // If user is not running, the app didn't miss any broadcast 13143 if (!mUserManagerInternal.isUserRunning(userId)) { 13144 return; 13145 } 13146 final IActivityManager am = ActivityManager.getService(); 13147 try { 13148 // Deliver LOCKED_BOOT_COMPLETED first 13149 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13150 .setPackage(packageName); 13151 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13152 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13153 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13154 13155 // Deliver BOOT_COMPLETED only if user is unlocked 13156 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13157 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13158 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13159 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13160 } 13161 } catch (RemoteException e) { 13162 throw e.rethrowFromSystemServer(); 13163 } 13164 } 13165 13166 @Override 13167 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13168 int userId) { 13169 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13170 PackageSetting pkgSetting; 13171 final int uid = Binder.getCallingUid(); 13172 enforceCrossUserPermission(uid, userId, 13173 true /* requireFullPermission */, true /* checkShell */, 13174 "setApplicationHiddenSetting for user " + userId); 13175 13176 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13177 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13178 return false; 13179 } 13180 13181 long callingId = Binder.clearCallingIdentity(); 13182 try { 13183 boolean sendAdded = false; 13184 boolean sendRemoved = false; 13185 // writer 13186 synchronized (mPackages) { 13187 pkgSetting = mSettings.mPackages.get(packageName); 13188 if (pkgSetting == null) { 13189 return false; 13190 } 13191 // Do not allow "android" is being disabled 13192 if ("android".equals(packageName)) { 13193 Slog.w(TAG, "Cannot hide package: android"); 13194 return false; 13195 } 13196 // Cannot hide static shared libs as they are considered 13197 // a part of the using app (emulating static linking). Also 13198 // static libs are installed always on internal storage. 13199 PackageParser.Package pkg = mPackages.get(packageName); 13200 if (pkg != null && pkg.staticSharedLibName != null) { 13201 Slog.w(TAG, "Cannot hide package: " + packageName 13202 + " providing static shared library: " 13203 + pkg.staticSharedLibName); 13204 return false; 13205 } 13206 // Only allow protected packages to hide themselves. 13207 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13208 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13209 Slog.w(TAG, "Not hiding protected package: " + packageName); 13210 return false; 13211 } 13212 13213 if (pkgSetting.getHidden(userId) != hidden) { 13214 pkgSetting.setHidden(hidden, userId); 13215 mSettings.writePackageRestrictionsLPr(userId); 13216 if (hidden) { 13217 sendRemoved = true; 13218 } else { 13219 sendAdded = true; 13220 } 13221 } 13222 } 13223 if (sendAdded) { 13224 sendPackageAddedForUser(packageName, pkgSetting, userId); 13225 return true; 13226 } 13227 if (sendRemoved) { 13228 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13229 "hiding pkg"); 13230 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13231 return true; 13232 } 13233 } finally { 13234 Binder.restoreCallingIdentity(callingId); 13235 } 13236 return false; 13237 } 13238 13239 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13240 int userId) { 13241 final PackageRemovedInfo info = new PackageRemovedInfo(); 13242 info.removedPackage = packageName; 13243 info.removedUsers = new int[] {userId}; 13244 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13245 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13246 } 13247 13248 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13249 if (pkgList.length > 0) { 13250 Bundle extras = new Bundle(1); 13251 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13252 13253 sendPackageBroadcast( 13254 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13255 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13256 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13257 new int[] {userId}); 13258 } 13259 } 13260 13261 /** 13262 * Returns true if application is not found or there was an error. Otherwise it returns 13263 * the hidden state of the package for the given user. 13264 */ 13265 @Override 13266 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13267 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13268 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13269 true /* requireFullPermission */, false /* checkShell */, 13270 "getApplicationHidden for user " + userId); 13271 PackageSetting pkgSetting; 13272 long callingId = Binder.clearCallingIdentity(); 13273 try { 13274 // writer 13275 synchronized (mPackages) { 13276 pkgSetting = mSettings.mPackages.get(packageName); 13277 if (pkgSetting == null) { 13278 return true; 13279 } 13280 return pkgSetting.getHidden(userId); 13281 } 13282 } finally { 13283 Binder.restoreCallingIdentity(callingId); 13284 } 13285 } 13286 13287 /** 13288 * @hide 13289 */ 13290 @Override 13291 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13292 int installReason) { 13293 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13294 null); 13295 PackageSetting pkgSetting; 13296 final int uid = Binder.getCallingUid(); 13297 enforceCrossUserPermission(uid, userId, 13298 true /* requireFullPermission */, true /* checkShell */, 13299 "installExistingPackage for user " + userId); 13300 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13301 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13302 } 13303 13304 long callingId = Binder.clearCallingIdentity(); 13305 try { 13306 boolean installed = false; 13307 final boolean instantApp = 13308 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13309 final boolean fullApp = 13310 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13311 13312 // writer 13313 synchronized (mPackages) { 13314 pkgSetting = mSettings.mPackages.get(packageName); 13315 if (pkgSetting == null) { 13316 return PackageManager.INSTALL_FAILED_INVALID_URI; 13317 } 13318 if (!pkgSetting.getInstalled(userId)) { 13319 pkgSetting.setInstalled(true, userId); 13320 pkgSetting.setHidden(false, userId); 13321 pkgSetting.setInstallReason(installReason, userId); 13322 mSettings.writePackageRestrictionsLPr(userId); 13323 mSettings.writeKernelMappingLPr(pkgSetting); 13324 installed = true; 13325 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13326 // upgrade app from instant to full; we don't allow app downgrade 13327 installed = true; 13328 } 13329 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13330 } 13331 13332 if (installed) { 13333 if (pkgSetting.pkg != null) { 13334 synchronized (mInstallLock) { 13335 // We don't need to freeze for a brand new install 13336 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13337 } 13338 } 13339 sendPackageAddedForUser(packageName, pkgSetting, userId); 13340 synchronized (mPackages) { 13341 updateSequenceNumberLP(packageName, new int[]{ userId }); 13342 } 13343 } 13344 } finally { 13345 Binder.restoreCallingIdentity(callingId); 13346 } 13347 13348 return PackageManager.INSTALL_SUCCEEDED; 13349 } 13350 13351 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13352 boolean instantApp, boolean fullApp) { 13353 // no state specified; do nothing 13354 if (!instantApp && !fullApp) { 13355 return; 13356 } 13357 if (userId != UserHandle.USER_ALL) { 13358 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13359 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13360 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13361 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13362 } 13363 } else { 13364 for (int currentUserId : sUserManager.getUserIds()) { 13365 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13366 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13367 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13368 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13369 } 13370 } 13371 } 13372 } 13373 13374 boolean isUserRestricted(int userId, String restrictionKey) { 13375 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13376 if (restrictions.getBoolean(restrictionKey, false)) { 13377 Log.w(TAG, "User is restricted: " + restrictionKey); 13378 return true; 13379 } 13380 return false; 13381 } 13382 13383 @Override 13384 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13385 int userId) { 13386 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13387 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13388 true /* requireFullPermission */, true /* checkShell */, 13389 "setPackagesSuspended for user " + userId); 13390 13391 if (ArrayUtils.isEmpty(packageNames)) { 13392 return packageNames; 13393 } 13394 13395 // List of package names for whom the suspended state has changed. 13396 List<String> changedPackages = new ArrayList<>(packageNames.length); 13397 // List of package names for whom the suspended state is not set as requested in this 13398 // method. 13399 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13400 long callingId = Binder.clearCallingIdentity(); 13401 try { 13402 for (int i = 0; i < packageNames.length; i++) { 13403 String packageName = packageNames[i]; 13404 boolean changed = false; 13405 final int appId; 13406 synchronized (mPackages) { 13407 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13408 if (pkgSetting == null) { 13409 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13410 + "\". Skipping suspending/un-suspending."); 13411 unactionedPackages.add(packageName); 13412 continue; 13413 } 13414 appId = pkgSetting.appId; 13415 if (pkgSetting.getSuspended(userId) != suspended) { 13416 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13417 unactionedPackages.add(packageName); 13418 continue; 13419 } 13420 pkgSetting.setSuspended(suspended, userId); 13421 mSettings.writePackageRestrictionsLPr(userId); 13422 changed = true; 13423 changedPackages.add(packageName); 13424 } 13425 } 13426 13427 if (changed && suspended) { 13428 killApplication(packageName, UserHandle.getUid(userId, appId), 13429 "suspending package"); 13430 } 13431 } 13432 } finally { 13433 Binder.restoreCallingIdentity(callingId); 13434 } 13435 13436 if (!changedPackages.isEmpty()) { 13437 sendPackagesSuspendedForUser(changedPackages.toArray( 13438 new String[changedPackages.size()]), userId, suspended); 13439 } 13440 13441 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13442 } 13443 13444 @Override 13445 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13446 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13447 true /* requireFullPermission */, false /* checkShell */, 13448 "isPackageSuspendedForUser for user " + userId); 13449 synchronized (mPackages) { 13450 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13451 if (pkgSetting == null) { 13452 throw new IllegalArgumentException("Unknown target package: " + packageName); 13453 } 13454 return pkgSetting.getSuspended(userId); 13455 } 13456 } 13457 13458 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13459 if (isPackageDeviceAdmin(packageName, userId)) { 13460 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13461 + "\": has an active device admin"); 13462 return false; 13463 } 13464 13465 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13466 if (packageName.equals(activeLauncherPackageName)) { 13467 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13468 + "\": contains the active launcher"); 13469 return false; 13470 } 13471 13472 if (packageName.equals(mRequiredInstallerPackage)) { 13473 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13474 + "\": required for package installation"); 13475 return false; 13476 } 13477 13478 if (packageName.equals(mRequiredUninstallerPackage)) { 13479 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13480 + "\": required for package uninstallation"); 13481 return false; 13482 } 13483 13484 if (packageName.equals(mRequiredVerifierPackage)) { 13485 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13486 + "\": required for package verification"); 13487 return false; 13488 } 13489 13490 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13491 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13492 + "\": is the default dialer"); 13493 return false; 13494 } 13495 13496 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13497 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13498 + "\": protected package"); 13499 return false; 13500 } 13501 13502 // Cannot suspend static shared libs as they are considered 13503 // a part of the using app (emulating static linking). Also 13504 // static libs are installed always on internal storage. 13505 PackageParser.Package pkg = mPackages.get(packageName); 13506 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13507 Slog.w(TAG, "Cannot suspend package: " + packageName 13508 + " providing static shared library: " 13509 + pkg.staticSharedLibName); 13510 return false; 13511 } 13512 13513 return true; 13514 } 13515 13516 private String getActiveLauncherPackageName(int userId) { 13517 Intent intent = new Intent(Intent.ACTION_MAIN); 13518 intent.addCategory(Intent.CATEGORY_HOME); 13519 ResolveInfo resolveInfo = resolveIntent( 13520 intent, 13521 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13522 PackageManager.MATCH_DEFAULT_ONLY, 13523 userId); 13524 13525 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13526 } 13527 13528 private String getDefaultDialerPackageName(int userId) { 13529 synchronized (mPackages) { 13530 return mSettings.getDefaultDialerPackageNameLPw(userId); 13531 } 13532 } 13533 13534 @Override 13535 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13536 mContext.enforceCallingOrSelfPermission( 13537 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13538 "Only package verification agents can verify applications"); 13539 13540 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13541 final PackageVerificationResponse response = new PackageVerificationResponse( 13542 verificationCode, Binder.getCallingUid()); 13543 msg.arg1 = id; 13544 msg.obj = response; 13545 mHandler.sendMessage(msg); 13546 } 13547 13548 @Override 13549 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13550 long millisecondsToDelay) { 13551 mContext.enforceCallingOrSelfPermission( 13552 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13553 "Only package verification agents can extend verification timeouts"); 13554 13555 final PackageVerificationState state = mPendingVerification.get(id); 13556 final PackageVerificationResponse response = new PackageVerificationResponse( 13557 verificationCodeAtTimeout, Binder.getCallingUid()); 13558 13559 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13560 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13561 } 13562 if (millisecondsToDelay < 0) { 13563 millisecondsToDelay = 0; 13564 } 13565 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13566 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13567 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13568 } 13569 13570 if ((state != null) && !state.timeoutExtended()) { 13571 state.extendTimeout(); 13572 13573 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13574 msg.arg1 = id; 13575 msg.obj = response; 13576 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13577 } 13578 } 13579 13580 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13581 int verificationCode, UserHandle user) { 13582 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13583 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13584 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13585 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13586 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13587 13588 mContext.sendBroadcastAsUser(intent, user, 13589 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13590 } 13591 13592 private ComponentName matchComponentForVerifier(String packageName, 13593 List<ResolveInfo> receivers) { 13594 ActivityInfo targetReceiver = null; 13595 13596 final int NR = receivers.size(); 13597 for (int i = 0; i < NR; i++) { 13598 final ResolveInfo info = receivers.get(i); 13599 if (info.activityInfo == null) { 13600 continue; 13601 } 13602 13603 if (packageName.equals(info.activityInfo.packageName)) { 13604 targetReceiver = info.activityInfo; 13605 break; 13606 } 13607 } 13608 13609 if (targetReceiver == null) { 13610 return null; 13611 } 13612 13613 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13614 } 13615 13616 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13617 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13618 if (pkgInfo.verifiers.length == 0) { 13619 return null; 13620 } 13621 13622 final int N = pkgInfo.verifiers.length; 13623 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13624 for (int i = 0; i < N; i++) { 13625 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13626 13627 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13628 receivers); 13629 if (comp == null) { 13630 continue; 13631 } 13632 13633 final int verifierUid = getUidForVerifier(verifierInfo); 13634 if (verifierUid == -1) { 13635 continue; 13636 } 13637 13638 if (DEBUG_VERIFY) { 13639 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13640 + " with the correct signature"); 13641 } 13642 sufficientVerifiers.add(comp); 13643 verificationState.addSufficientVerifier(verifierUid); 13644 } 13645 13646 return sufficientVerifiers; 13647 } 13648 13649 private int getUidForVerifier(VerifierInfo verifierInfo) { 13650 synchronized (mPackages) { 13651 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13652 if (pkg == null) { 13653 return -1; 13654 } else if (pkg.mSignatures.length != 1) { 13655 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13656 + " has more than one signature; ignoring"); 13657 return -1; 13658 } 13659 13660 /* 13661 * If the public key of the package's signature does not match 13662 * our expected public key, then this is a different package and 13663 * we should skip. 13664 */ 13665 13666 final byte[] expectedPublicKey; 13667 try { 13668 final Signature verifierSig = pkg.mSignatures[0]; 13669 final PublicKey publicKey = verifierSig.getPublicKey(); 13670 expectedPublicKey = publicKey.getEncoded(); 13671 } catch (CertificateException e) { 13672 return -1; 13673 } 13674 13675 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13676 13677 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13678 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13679 + " does not have the expected public key; ignoring"); 13680 return -1; 13681 } 13682 13683 return pkg.applicationInfo.uid; 13684 } 13685 } 13686 13687 @Override 13688 public void finishPackageInstall(int token, boolean didLaunch) { 13689 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13690 13691 if (DEBUG_INSTALL) { 13692 Slog.v(TAG, "BM finishing package install for " + token); 13693 } 13694 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13695 13696 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13697 mHandler.sendMessage(msg); 13698 } 13699 13700 /** 13701 * Get the verification agent timeout. 13702 * 13703 * @return verification timeout in milliseconds 13704 */ 13705 private long getVerificationTimeout() { 13706 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13707 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13708 DEFAULT_VERIFICATION_TIMEOUT); 13709 } 13710 13711 /** 13712 * Get the default verification agent response code. 13713 * 13714 * @return default verification response code 13715 */ 13716 private int getDefaultVerificationResponse() { 13717 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13718 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13719 DEFAULT_VERIFICATION_RESPONSE); 13720 } 13721 13722 /** 13723 * Check whether or not package verification has been enabled. 13724 * 13725 * @return true if verification should be performed 13726 */ 13727 private boolean isVerificationEnabled(int userId, int installFlags) { 13728 if (!DEFAULT_VERIFY_ENABLE) { 13729 return false; 13730 } 13731 // Ephemeral apps don't get the full verification treatment 13732 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13733 if (DEBUG_EPHEMERAL) { 13734 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13735 } 13736 return false; 13737 } 13738 13739 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13740 13741 // Check if installing from ADB 13742 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13743 // Do not run verification in a test harness environment 13744 if (ActivityManager.isRunningInTestHarness()) { 13745 return false; 13746 } 13747 if (ensureVerifyAppsEnabled) { 13748 return true; 13749 } 13750 // Check if the developer does not want package verification for ADB installs 13751 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13752 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13753 return false; 13754 } 13755 } 13756 13757 if (ensureVerifyAppsEnabled) { 13758 return true; 13759 } 13760 13761 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13762 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13763 } 13764 13765 @Override 13766 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13767 throws RemoteException { 13768 mContext.enforceCallingOrSelfPermission( 13769 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13770 "Only intentfilter verification agents can verify applications"); 13771 13772 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13773 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13774 Binder.getCallingUid(), verificationCode, failedDomains); 13775 msg.arg1 = id; 13776 msg.obj = response; 13777 mHandler.sendMessage(msg); 13778 } 13779 13780 @Override 13781 public int getIntentVerificationStatus(String packageName, int userId) { 13782 synchronized (mPackages) { 13783 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13784 } 13785 } 13786 13787 @Override 13788 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13789 mContext.enforceCallingOrSelfPermission( 13790 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13791 13792 boolean result = false; 13793 synchronized (mPackages) { 13794 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13795 } 13796 if (result) { 13797 scheduleWritePackageRestrictionsLocked(userId); 13798 } 13799 return result; 13800 } 13801 13802 @Override 13803 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13804 String packageName) { 13805 synchronized (mPackages) { 13806 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13807 } 13808 } 13809 13810 @Override 13811 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13812 if (TextUtils.isEmpty(packageName)) { 13813 return ParceledListSlice.emptyList(); 13814 } 13815 synchronized (mPackages) { 13816 PackageParser.Package pkg = mPackages.get(packageName); 13817 if (pkg == null || pkg.activities == null) { 13818 return ParceledListSlice.emptyList(); 13819 } 13820 final int count = pkg.activities.size(); 13821 ArrayList<IntentFilter> result = new ArrayList<>(); 13822 for (int n=0; n<count; n++) { 13823 PackageParser.Activity activity = pkg.activities.get(n); 13824 if (activity.intents != null && activity.intents.size() > 0) { 13825 result.addAll(activity.intents); 13826 } 13827 } 13828 return new ParceledListSlice<>(result); 13829 } 13830 } 13831 13832 @Override 13833 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13834 mContext.enforceCallingOrSelfPermission( 13835 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13836 13837 synchronized (mPackages) { 13838 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13839 if (packageName != null) { 13840 result |= updateIntentVerificationStatus(packageName, 13841 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13842 userId); 13843 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13844 packageName, userId); 13845 } 13846 return result; 13847 } 13848 } 13849 13850 @Override 13851 public String getDefaultBrowserPackageName(int userId) { 13852 synchronized (mPackages) { 13853 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13854 } 13855 } 13856 13857 /** 13858 * Get the "allow unknown sources" setting. 13859 * 13860 * @return the current "allow unknown sources" setting 13861 */ 13862 private int getUnknownSourcesSettings() { 13863 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13864 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13865 -1); 13866 } 13867 13868 @Override 13869 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13870 final int uid = Binder.getCallingUid(); 13871 // writer 13872 synchronized (mPackages) { 13873 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13874 if (targetPackageSetting == null) { 13875 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13876 } 13877 13878 PackageSetting installerPackageSetting; 13879 if (installerPackageName != null) { 13880 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13881 if (installerPackageSetting == null) { 13882 throw new IllegalArgumentException("Unknown installer package: " 13883 + installerPackageName); 13884 } 13885 } else { 13886 installerPackageSetting = null; 13887 } 13888 13889 Signature[] callerSignature; 13890 Object obj = mSettings.getUserIdLPr(uid); 13891 if (obj != null) { 13892 if (obj instanceof SharedUserSetting) { 13893 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13894 } else if (obj instanceof PackageSetting) { 13895 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13896 } else { 13897 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13898 } 13899 } else { 13900 throw new SecurityException("Unknown calling UID: " + uid); 13901 } 13902 13903 // Verify: can't set installerPackageName to a package that is 13904 // not signed with the same cert as the caller. 13905 if (installerPackageSetting != null) { 13906 if (compareSignatures(callerSignature, 13907 installerPackageSetting.signatures.mSignatures) 13908 != PackageManager.SIGNATURE_MATCH) { 13909 throw new SecurityException( 13910 "Caller does not have same cert as new installer package " 13911 + installerPackageName); 13912 } 13913 } 13914 13915 // Verify: if target already has an installer package, it must 13916 // be signed with the same cert as the caller. 13917 if (targetPackageSetting.installerPackageName != null) { 13918 PackageSetting setting = mSettings.mPackages.get( 13919 targetPackageSetting.installerPackageName); 13920 // If the currently set package isn't valid, then it's always 13921 // okay to change it. 13922 if (setting != null) { 13923 if (compareSignatures(callerSignature, 13924 setting.signatures.mSignatures) 13925 != PackageManager.SIGNATURE_MATCH) { 13926 throw new SecurityException( 13927 "Caller does not have same cert as old installer package " 13928 + targetPackageSetting.installerPackageName); 13929 } 13930 } 13931 } 13932 13933 // Okay! 13934 targetPackageSetting.installerPackageName = installerPackageName; 13935 if (installerPackageName != null) { 13936 mSettings.mInstallerPackages.add(installerPackageName); 13937 } 13938 scheduleWriteSettingsLocked(); 13939 } 13940 } 13941 13942 @Override 13943 public void setApplicationCategoryHint(String packageName, int categoryHint, 13944 String callerPackageName) { 13945 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13946 callerPackageName); 13947 synchronized (mPackages) { 13948 PackageSetting ps = mSettings.mPackages.get(packageName); 13949 if (ps == null) { 13950 throw new IllegalArgumentException("Unknown target package " + packageName); 13951 } 13952 13953 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13954 throw new IllegalArgumentException("Calling package " + callerPackageName 13955 + " is not installer for " + packageName); 13956 } 13957 13958 if (ps.categoryHint != categoryHint) { 13959 ps.categoryHint = categoryHint; 13960 scheduleWriteSettingsLocked(); 13961 } 13962 } 13963 } 13964 13965 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13966 // Queue up an async operation since the package installation may take a little while. 13967 mHandler.post(new Runnable() { 13968 public void run() { 13969 mHandler.removeCallbacks(this); 13970 // Result object to be returned 13971 PackageInstalledInfo res = new PackageInstalledInfo(); 13972 res.setReturnCode(currentStatus); 13973 res.uid = -1; 13974 res.pkg = null; 13975 res.removedInfo = null; 13976 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13977 args.doPreInstall(res.returnCode); 13978 synchronized (mInstallLock) { 13979 installPackageTracedLI(args, res); 13980 } 13981 args.doPostInstall(res.returnCode, res.uid); 13982 } 13983 13984 // A restore should be performed at this point if (a) the install 13985 // succeeded, (b) the operation is not an update, and (c) the new 13986 // package has not opted out of backup participation. 13987 final boolean update = res.removedInfo != null 13988 && res.removedInfo.removedPackage != null; 13989 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13990 boolean doRestore = !update 13991 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13992 13993 // Set up the post-install work request bookkeeping. This will be used 13994 // and cleaned up by the post-install event handling regardless of whether 13995 // there's a restore pass performed. Token values are >= 1. 13996 int token; 13997 if (mNextInstallToken < 0) mNextInstallToken = 1; 13998 token = mNextInstallToken++; 13999 14000 PostInstallData data = new PostInstallData(args, res); 14001 mRunningInstalls.put(token, data); 14002 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14003 14004 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14005 // Pass responsibility to the Backup Manager. It will perform a 14006 // restore if appropriate, then pass responsibility back to the 14007 // Package Manager to run the post-install observer callbacks 14008 // and broadcasts. 14009 IBackupManager bm = IBackupManager.Stub.asInterface( 14010 ServiceManager.getService(Context.BACKUP_SERVICE)); 14011 if (bm != null) { 14012 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14013 + " to BM for possible restore"); 14014 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14015 try { 14016 // TODO: http://b/22388012 14017 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14018 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14019 } else { 14020 doRestore = false; 14021 } 14022 } catch (RemoteException e) { 14023 // can't happen; the backup manager is local 14024 } catch (Exception e) { 14025 Slog.e(TAG, "Exception trying to enqueue restore", e); 14026 doRestore = false; 14027 } 14028 } else { 14029 Slog.e(TAG, "Backup Manager not found!"); 14030 doRestore = false; 14031 } 14032 } 14033 14034 if (!doRestore) { 14035 // No restore possible, or the Backup Manager was mysteriously not 14036 // available -- just fire the post-install work request directly. 14037 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14038 14039 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14040 14041 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14042 mHandler.sendMessage(msg); 14043 } 14044 } 14045 }); 14046 } 14047 14048 /** 14049 * Callback from PackageSettings whenever an app is first transitioned out of the 14050 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14051 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14052 * here whether the app is the target of an ongoing install, and only send the 14053 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14054 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14055 * handling. 14056 */ 14057 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14058 // Serialize this with the rest of the install-process message chain. In the 14059 // restore-at-install case, this Runnable will necessarily run before the 14060 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14061 // are coherent. In the non-restore case, the app has already completed install 14062 // and been launched through some other means, so it is not in a problematic 14063 // state for observers to see the FIRST_LAUNCH signal. 14064 mHandler.post(new Runnable() { 14065 @Override 14066 public void run() { 14067 for (int i = 0; i < mRunningInstalls.size(); i++) { 14068 final PostInstallData data = mRunningInstalls.valueAt(i); 14069 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14070 continue; 14071 } 14072 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14073 // right package; but is it for the right user? 14074 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14075 if (userId == data.res.newUsers[uIndex]) { 14076 if (DEBUG_BACKUP) { 14077 Slog.i(TAG, "Package " + pkgName 14078 + " being restored so deferring FIRST_LAUNCH"); 14079 } 14080 return; 14081 } 14082 } 14083 } 14084 } 14085 // didn't find it, so not being restored 14086 if (DEBUG_BACKUP) { 14087 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14088 } 14089 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14090 } 14091 }); 14092 } 14093 14094 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14095 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14096 installerPkg, null, userIds); 14097 } 14098 14099 private abstract class HandlerParams { 14100 private static final int MAX_RETRIES = 4; 14101 14102 /** 14103 * Number of times startCopy() has been attempted and had a non-fatal 14104 * error. 14105 */ 14106 private int mRetries = 0; 14107 14108 /** User handle for the user requesting the information or installation. */ 14109 private final UserHandle mUser; 14110 String traceMethod; 14111 int traceCookie; 14112 14113 HandlerParams(UserHandle user) { 14114 mUser = user; 14115 } 14116 14117 UserHandle getUser() { 14118 return mUser; 14119 } 14120 14121 HandlerParams setTraceMethod(String traceMethod) { 14122 this.traceMethod = traceMethod; 14123 return this; 14124 } 14125 14126 HandlerParams setTraceCookie(int traceCookie) { 14127 this.traceCookie = traceCookie; 14128 return this; 14129 } 14130 14131 final boolean startCopy() { 14132 boolean res; 14133 try { 14134 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14135 14136 if (++mRetries > MAX_RETRIES) { 14137 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14138 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14139 handleServiceError(); 14140 return false; 14141 } else { 14142 handleStartCopy(); 14143 res = true; 14144 } 14145 } catch (RemoteException e) { 14146 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14147 mHandler.sendEmptyMessage(MCS_RECONNECT); 14148 res = false; 14149 } 14150 handleReturnCode(); 14151 return res; 14152 } 14153 14154 final void serviceError() { 14155 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14156 handleServiceError(); 14157 handleReturnCode(); 14158 } 14159 14160 abstract void handleStartCopy() throws RemoteException; 14161 abstract void handleServiceError(); 14162 abstract void handleReturnCode(); 14163 } 14164 14165 class MeasureParams extends HandlerParams { 14166 private final PackageStats mStats; 14167 private boolean mSuccess; 14168 14169 private final IPackageStatsObserver mObserver; 14170 14171 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 14172 super(new UserHandle(stats.userHandle)); 14173 mObserver = observer; 14174 mStats = stats; 14175 } 14176 14177 @Override 14178 public String toString() { 14179 return "MeasureParams{" 14180 + Integer.toHexString(System.identityHashCode(this)) 14181 + " " + mStats.packageName + "}"; 14182 } 14183 14184 @Override 14185 void handleStartCopy() throws RemoteException { 14186 synchronized (mInstallLock) { 14187 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 14188 } 14189 14190 if (mSuccess) { 14191 boolean mounted = false; 14192 try { 14193 final String status = Environment.getExternalStorageState(); 14194 mounted = (Environment.MEDIA_MOUNTED.equals(status) 14195 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 14196 } catch (Exception e) { 14197 } 14198 14199 if (mounted) { 14200 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 14201 14202 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 14203 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 14204 14205 mStats.externalDataSize = calculateDirectorySize(mContainerService, 14206 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 14207 14208 // Always subtract cache size, since it's a subdirectory 14209 mStats.externalDataSize -= mStats.externalCacheSize; 14210 14211 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 14212 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 14213 14214 mStats.externalObbSize = calculateDirectorySize(mContainerService, 14215 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 14216 } 14217 } 14218 } 14219 14220 @Override 14221 void handleReturnCode() { 14222 if (mObserver != null) { 14223 try { 14224 mObserver.onGetStatsCompleted(mStats, mSuccess); 14225 } catch (RemoteException e) { 14226 Slog.i(TAG, "Observer no longer exists."); 14227 } 14228 } 14229 } 14230 14231 @Override 14232 void handleServiceError() { 14233 Slog.e(TAG, "Could not measure application " + mStats.packageName 14234 + " external storage"); 14235 } 14236 } 14237 14238 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 14239 throws RemoteException { 14240 long result = 0; 14241 for (File path : paths) { 14242 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 14243 } 14244 return result; 14245 } 14246 14247 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14248 for (File path : paths) { 14249 try { 14250 mcs.clearDirectory(path.getAbsolutePath()); 14251 } catch (RemoteException e) { 14252 } 14253 } 14254 } 14255 14256 static class OriginInfo { 14257 /** 14258 * Location where install is coming from, before it has been 14259 * copied/renamed into place. This could be a single monolithic APK 14260 * file, or a cluster directory. This location may be untrusted. 14261 */ 14262 final File file; 14263 final String cid; 14264 14265 /** 14266 * Flag indicating that {@link #file} or {@link #cid} has already been 14267 * staged, meaning downstream users don't need to defensively copy the 14268 * contents. 14269 */ 14270 final boolean staged; 14271 14272 /** 14273 * Flag indicating that {@link #file} or {@link #cid} is an already 14274 * installed app that is being moved. 14275 */ 14276 final boolean existing; 14277 14278 final String resolvedPath; 14279 final File resolvedFile; 14280 14281 static OriginInfo fromNothing() { 14282 return new OriginInfo(null, null, false, false); 14283 } 14284 14285 static OriginInfo fromUntrustedFile(File file) { 14286 return new OriginInfo(file, null, false, false); 14287 } 14288 14289 static OriginInfo fromExistingFile(File file) { 14290 return new OriginInfo(file, null, false, true); 14291 } 14292 14293 static OriginInfo fromStagedFile(File file) { 14294 return new OriginInfo(file, null, true, false); 14295 } 14296 14297 static OriginInfo fromStagedContainer(String cid) { 14298 return new OriginInfo(null, cid, true, false); 14299 } 14300 14301 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14302 this.file = file; 14303 this.cid = cid; 14304 this.staged = staged; 14305 this.existing = existing; 14306 14307 if (cid != null) { 14308 resolvedPath = PackageHelper.getSdDir(cid); 14309 resolvedFile = new File(resolvedPath); 14310 } else if (file != null) { 14311 resolvedPath = file.getAbsolutePath(); 14312 resolvedFile = file; 14313 } else { 14314 resolvedPath = null; 14315 resolvedFile = null; 14316 } 14317 } 14318 } 14319 14320 static class MoveInfo { 14321 final int moveId; 14322 final String fromUuid; 14323 final String toUuid; 14324 final String packageName; 14325 final String dataAppName; 14326 final int appId; 14327 final String seinfo; 14328 final int targetSdkVersion; 14329 14330 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14331 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14332 this.moveId = moveId; 14333 this.fromUuid = fromUuid; 14334 this.toUuid = toUuid; 14335 this.packageName = packageName; 14336 this.dataAppName = dataAppName; 14337 this.appId = appId; 14338 this.seinfo = seinfo; 14339 this.targetSdkVersion = targetSdkVersion; 14340 } 14341 } 14342 14343 static class VerificationInfo { 14344 /** A constant used to indicate that a uid value is not present. */ 14345 public static final int NO_UID = -1; 14346 14347 /** URI referencing where the package was downloaded from. */ 14348 final Uri originatingUri; 14349 14350 /** HTTP referrer URI associated with the originatingURI. */ 14351 final Uri referrer; 14352 14353 /** UID of the application that the install request originated from. */ 14354 final int originatingUid; 14355 14356 /** UID of application requesting the install */ 14357 final int installerUid; 14358 14359 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14360 this.originatingUri = originatingUri; 14361 this.referrer = referrer; 14362 this.originatingUid = originatingUid; 14363 this.installerUid = installerUid; 14364 } 14365 } 14366 14367 class InstallParams extends HandlerParams { 14368 final OriginInfo origin; 14369 final MoveInfo move; 14370 final IPackageInstallObserver2 observer; 14371 int installFlags; 14372 final String installerPackageName; 14373 final String volumeUuid; 14374 private InstallArgs mArgs; 14375 private int mRet; 14376 final String packageAbiOverride; 14377 final String[] grantedRuntimePermissions; 14378 final VerificationInfo verificationInfo; 14379 final Certificate[][] certificates; 14380 final int installReason; 14381 14382 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14383 int installFlags, String installerPackageName, String volumeUuid, 14384 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14385 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14386 super(user); 14387 this.origin = origin; 14388 this.move = move; 14389 this.observer = observer; 14390 this.installFlags = installFlags; 14391 this.installerPackageName = installerPackageName; 14392 this.volumeUuid = volumeUuid; 14393 this.verificationInfo = verificationInfo; 14394 this.packageAbiOverride = packageAbiOverride; 14395 this.grantedRuntimePermissions = grantedPermissions; 14396 this.certificates = certificates; 14397 this.installReason = installReason; 14398 } 14399 14400 @Override 14401 public String toString() { 14402 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14403 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14404 } 14405 14406 private int installLocationPolicy(PackageInfoLite pkgLite) { 14407 String packageName = pkgLite.packageName; 14408 int installLocation = pkgLite.installLocation; 14409 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14410 // reader 14411 synchronized (mPackages) { 14412 // Currently installed package which the new package is attempting to replace or 14413 // null if no such package is installed. 14414 PackageParser.Package installedPkg = mPackages.get(packageName); 14415 // Package which currently owns the data which the new package will own if installed. 14416 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14417 // will be null whereas dataOwnerPkg will contain information about the package 14418 // which was uninstalled while keeping its data. 14419 PackageParser.Package dataOwnerPkg = installedPkg; 14420 if (dataOwnerPkg == null) { 14421 PackageSetting ps = mSettings.mPackages.get(packageName); 14422 if (ps != null) { 14423 dataOwnerPkg = ps.pkg; 14424 } 14425 } 14426 14427 if (dataOwnerPkg != null) { 14428 // If installed, the package will get access to data left on the device by its 14429 // predecessor. As a security measure, this is permited only if this is not a 14430 // version downgrade or if the predecessor package is marked as debuggable and 14431 // a downgrade is explicitly requested. 14432 // 14433 // On debuggable platform builds, downgrades are permitted even for 14434 // non-debuggable packages to make testing easier. Debuggable platform builds do 14435 // not offer security guarantees and thus it's OK to disable some security 14436 // mechanisms to make debugging/testing easier on those builds. However, even on 14437 // debuggable builds downgrades of packages are permitted only if requested via 14438 // installFlags. This is because we aim to keep the behavior of debuggable 14439 // platform builds as close as possible to the behavior of non-debuggable 14440 // platform builds. 14441 final boolean downgradeRequested = 14442 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14443 final boolean packageDebuggable = 14444 (dataOwnerPkg.applicationInfo.flags 14445 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14446 final boolean downgradePermitted = 14447 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14448 if (!downgradePermitted) { 14449 try { 14450 checkDowngrade(dataOwnerPkg, pkgLite); 14451 } catch (PackageManagerException e) { 14452 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14453 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14454 } 14455 } 14456 } 14457 14458 if (installedPkg != null) { 14459 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14460 // Check for updated system application. 14461 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14462 if (onSd) { 14463 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14464 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14465 } 14466 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14467 } else { 14468 if (onSd) { 14469 // Install flag overrides everything. 14470 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14471 } 14472 // If current upgrade specifies particular preference 14473 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14474 // Application explicitly specified internal. 14475 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14476 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14477 // App explictly prefers external. Let policy decide 14478 } else { 14479 // Prefer previous location 14480 if (isExternal(installedPkg)) { 14481 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14482 } 14483 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14484 } 14485 } 14486 } else { 14487 // Invalid install. Return error code 14488 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14489 } 14490 } 14491 } 14492 // All the special cases have been taken care of. 14493 // Return result based on recommended install location. 14494 if (onSd) { 14495 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14496 } 14497 return pkgLite.recommendedInstallLocation; 14498 } 14499 14500 /* 14501 * Invoke remote method to get package information and install 14502 * location values. Override install location based on default 14503 * policy if needed and then create install arguments based 14504 * on the install location. 14505 */ 14506 public void handleStartCopy() throws RemoteException { 14507 int ret = PackageManager.INSTALL_SUCCEEDED; 14508 14509 // If we're already staged, we've firmly committed to an install location 14510 if (origin.staged) { 14511 if (origin.file != null) { 14512 installFlags |= PackageManager.INSTALL_INTERNAL; 14513 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14514 } else if (origin.cid != null) { 14515 installFlags |= PackageManager.INSTALL_EXTERNAL; 14516 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14517 } else { 14518 throw new IllegalStateException("Invalid stage location"); 14519 } 14520 } 14521 14522 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14523 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14524 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14525 PackageInfoLite pkgLite = null; 14526 14527 if (onInt && onSd) { 14528 // Check if both bits are set. 14529 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14530 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14531 } else if (onSd && ephemeral) { 14532 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14533 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14534 } else { 14535 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14536 packageAbiOverride); 14537 14538 if (DEBUG_EPHEMERAL && ephemeral) { 14539 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14540 } 14541 14542 /* 14543 * If we have too little free space, try to free cache 14544 * before giving up. 14545 */ 14546 if (!origin.staged && pkgLite.recommendedInstallLocation 14547 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14548 // TODO: focus freeing disk space on the target device 14549 final StorageManager storage = StorageManager.from(mContext); 14550 final long lowThreshold = storage.getStorageLowBytes( 14551 Environment.getDataDirectory()); 14552 14553 final long sizeBytes = mContainerService.calculateInstalledSize( 14554 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14555 14556 try { 14557 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14558 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14559 installFlags, packageAbiOverride); 14560 } catch (InstallerException e) { 14561 Slog.w(TAG, "Failed to free cache", e); 14562 } 14563 14564 /* 14565 * The cache free must have deleted the file we 14566 * downloaded to install. 14567 * 14568 * TODO: fix the "freeCache" call to not delete 14569 * the file we care about. 14570 */ 14571 if (pkgLite.recommendedInstallLocation 14572 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14573 pkgLite.recommendedInstallLocation 14574 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14575 } 14576 } 14577 } 14578 14579 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14580 int loc = pkgLite.recommendedInstallLocation; 14581 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14582 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14583 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14584 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14585 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14586 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14587 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14588 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14589 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14590 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14591 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14592 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14593 } else { 14594 // Override with defaults if needed. 14595 loc = installLocationPolicy(pkgLite); 14596 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14597 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14598 } else if (!onSd && !onInt) { 14599 // Override install location with flags 14600 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14601 // Set the flag to install on external media. 14602 installFlags |= PackageManager.INSTALL_EXTERNAL; 14603 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14604 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14605 if (DEBUG_EPHEMERAL) { 14606 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14607 } 14608 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14609 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14610 |PackageManager.INSTALL_INTERNAL); 14611 } else { 14612 // Make sure the flag for installing on external 14613 // media is unset 14614 installFlags |= PackageManager.INSTALL_INTERNAL; 14615 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14616 } 14617 } 14618 } 14619 } 14620 14621 final InstallArgs args = createInstallArgs(this); 14622 mArgs = args; 14623 14624 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14625 // TODO: http://b/22976637 14626 // Apps installed for "all" users use the device owner to verify the app 14627 UserHandle verifierUser = getUser(); 14628 if (verifierUser == UserHandle.ALL) { 14629 verifierUser = UserHandle.SYSTEM; 14630 } 14631 14632 /* 14633 * Determine if we have any installed package verifiers. If we 14634 * do, then we'll defer to them to verify the packages. 14635 */ 14636 final int requiredUid = mRequiredVerifierPackage == null ? -1 14637 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14638 verifierUser.getIdentifier()); 14639 if (!origin.existing && requiredUid != -1 14640 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14641 final Intent verification = new Intent( 14642 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14643 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14644 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14645 PACKAGE_MIME_TYPE); 14646 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14647 14648 // Query all live verifiers based on current user state 14649 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14650 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14651 14652 if (DEBUG_VERIFY) { 14653 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14654 + verification.toString() + " with " + pkgLite.verifiers.length 14655 + " optional verifiers"); 14656 } 14657 14658 final int verificationId = mPendingVerificationToken++; 14659 14660 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14661 14662 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14663 installerPackageName); 14664 14665 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14666 installFlags); 14667 14668 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14669 pkgLite.packageName); 14670 14671 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14672 pkgLite.versionCode); 14673 14674 if (verificationInfo != null) { 14675 if (verificationInfo.originatingUri != null) { 14676 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14677 verificationInfo.originatingUri); 14678 } 14679 if (verificationInfo.referrer != null) { 14680 verification.putExtra(Intent.EXTRA_REFERRER, 14681 verificationInfo.referrer); 14682 } 14683 if (verificationInfo.originatingUid >= 0) { 14684 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14685 verificationInfo.originatingUid); 14686 } 14687 if (verificationInfo.installerUid >= 0) { 14688 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14689 verificationInfo.installerUid); 14690 } 14691 } 14692 14693 final PackageVerificationState verificationState = new PackageVerificationState( 14694 requiredUid, args); 14695 14696 mPendingVerification.append(verificationId, verificationState); 14697 14698 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14699 receivers, verificationState); 14700 14701 /* 14702 * If any sufficient verifiers were listed in the package 14703 * manifest, attempt to ask them. 14704 */ 14705 if (sufficientVerifiers != null) { 14706 final int N = sufficientVerifiers.size(); 14707 if (N == 0) { 14708 Slog.i(TAG, "Additional verifiers required, but none installed."); 14709 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14710 } else { 14711 for (int i = 0; i < N; i++) { 14712 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14713 14714 final Intent sufficientIntent = new Intent(verification); 14715 sufficientIntent.setComponent(verifierComponent); 14716 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14717 } 14718 } 14719 } 14720 14721 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14722 mRequiredVerifierPackage, receivers); 14723 if (ret == PackageManager.INSTALL_SUCCEEDED 14724 && mRequiredVerifierPackage != null) { 14725 Trace.asyncTraceBegin( 14726 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14727 /* 14728 * Send the intent to the required verification agent, 14729 * but only start the verification timeout after the 14730 * target BroadcastReceivers have run. 14731 */ 14732 verification.setComponent(requiredVerifierComponent); 14733 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14734 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14735 new BroadcastReceiver() { 14736 @Override 14737 public void onReceive(Context context, Intent intent) { 14738 final Message msg = mHandler 14739 .obtainMessage(CHECK_PENDING_VERIFICATION); 14740 msg.arg1 = verificationId; 14741 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14742 } 14743 }, null, 0, null, null); 14744 14745 /* 14746 * We don't want the copy to proceed until verification 14747 * succeeds, so null out this field. 14748 */ 14749 mArgs = null; 14750 } 14751 } else { 14752 /* 14753 * No package verification is enabled, so immediately start 14754 * the remote call to initiate copy using temporary file. 14755 */ 14756 ret = args.copyApk(mContainerService, true); 14757 } 14758 } 14759 14760 mRet = ret; 14761 } 14762 14763 @Override 14764 void handleReturnCode() { 14765 // If mArgs is null, then MCS couldn't be reached. When it 14766 // reconnects, it will try again to install. At that point, this 14767 // will succeed. 14768 if (mArgs != null) { 14769 processPendingInstall(mArgs, mRet); 14770 } 14771 } 14772 14773 @Override 14774 void handleServiceError() { 14775 mArgs = createInstallArgs(this); 14776 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14777 } 14778 14779 public boolean isForwardLocked() { 14780 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14781 } 14782 } 14783 14784 /** 14785 * Used during creation of InstallArgs 14786 * 14787 * @param installFlags package installation flags 14788 * @return true if should be installed on external storage 14789 */ 14790 private static boolean installOnExternalAsec(int installFlags) { 14791 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14792 return false; 14793 } 14794 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14795 return true; 14796 } 14797 return false; 14798 } 14799 14800 /** 14801 * Used during creation of InstallArgs 14802 * 14803 * @param installFlags package installation flags 14804 * @return true if should be installed as forward locked 14805 */ 14806 private static boolean installForwardLocked(int installFlags) { 14807 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14808 } 14809 14810 private InstallArgs createInstallArgs(InstallParams params) { 14811 if (params.move != null) { 14812 return new MoveInstallArgs(params); 14813 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14814 return new AsecInstallArgs(params); 14815 } else { 14816 return new FileInstallArgs(params); 14817 } 14818 } 14819 14820 /** 14821 * Create args that describe an existing installed package. Typically used 14822 * when cleaning up old installs, or used as a move source. 14823 */ 14824 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14825 String resourcePath, String[] instructionSets) { 14826 final boolean isInAsec; 14827 if (installOnExternalAsec(installFlags)) { 14828 /* Apps on SD card are always in ASEC containers. */ 14829 isInAsec = true; 14830 } else if (installForwardLocked(installFlags) 14831 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14832 /* 14833 * Forward-locked apps are only in ASEC containers if they're the 14834 * new style 14835 */ 14836 isInAsec = true; 14837 } else { 14838 isInAsec = false; 14839 } 14840 14841 if (isInAsec) { 14842 return new AsecInstallArgs(codePath, instructionSets, 14843 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14844 } else { 14845 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14846 } 14847 } 14848 14849 static abstract class InstallArgs { 14850 /** @see InstallParams#origin */ 14851 final OriginInfo origin; 14852 /** @see InstallParams#move */ 14853 final MoveInfo move; 14854 14855 final IPackageInstallObserver2 observer; 14856 // Always refers to PackageManager flags only 14857 final int installFlags; 14858 final String installerPackageName; 14859 final String volumeUuid; 14860 final UserHandle user; 14861 final String abiOverride; 14862 final String[] installGrantPermissions; 14863 /** If non-null, drop an async trace when the install completes */ 14864 final String traceMethod; 14865 final int traceCookie; 14866 final Certificate[][] certificates; 14867 final int installReason; 14868 14869 // The list of instruction sets supported by this app. This is currently 14870 // only used during the rmdex() phase to clean up resources. We can get rid of this 14871 // if we move dex files under the common app path. 14872 /* nullable */ String[] instructionSets; 14873 14874 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14875 int installFlags, String installerPackageName, String volumeUuid, 14876 UserHandle user, String[] instructionSets, 14877 String abiOverride, String[] installGrantPermissions, 14878 String traceMethod, int traceCookie, Certificate[][] certificates, 14879 int installReason) { 14880 this.origin = origin; 14881 this.move = move; 14882 this.installFlags = installFlags; 14883 this.observer = observer; 14884 this.installerPackageName = installerPackageName; 14885 this.volumeUuid = volumeUuid; 14886 this.user = user; 14887 this.instructionSets = instructionSets; 14888 this.abiOverride = abiOverride; 14889 this.installGrantPermissions = installGrantPermissions; 14890 this.traceMethod = traceMethod; 14891 this.traceCookie = traceCookie; 14892 this.certificates = certificates; 14893 this.installReason = installReason; 14894 } 14895 14896 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14897 abstract int doPreInstall(int status); 14898 14899 /** 14900 * Rename package into final resting place. All paths on the given 14901 * scanned package should be updated to reflect the rename. 14902 */ 14903 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14904 abstract int doPostInstall(int status, int uid); 14905 14906 /** @see PackageSettingBase#codePathString */ 14907 abstract String getCodePath(); 14908 /** @see PackageSettingBase#resourcePathString */ 14909 abstract String getResourcePath(); 14910 14911 // Need installer lock especially for dex file removal. 14912 abstract void cleanUpResourcesLI(); 14913 abstract boolean doPostDeleteLI(boolean delete); 14914 14915 /** 14916 * Called before the source arguments are copied. This is used mostly 14917 * for MoveParams when it needs to read the source file to put it in the 14918 * destination. 14919 */ 14920 int doPreCopy() { 14921 return PackageManager.INSTALL_SUCCEEDED; 14922 } 14923 14924 /** 14925 * Called after the source arguments are copied. This is used mostly for 14926 * MoveParams when it needs to read the source file to put it in the 14927 * destination. 14928 */ 14929 int doPostCopy(int uid) { 14930 return PackageManager.INSTALL_SUCCEEDED; 14931 } 14932 14933 protected boolean isFwdLocked() { 14934 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14935 } 14936 14937 protected boolean isExternalAsec() { 14938 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14939 } 14940 14941 protected boolean isEphemeral() { 14942 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14943 } 14944 14945 UserHandle getUser() { 14946 return user; 14947 } 14948 } 14949 14950 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14951 if (!allCodePaths.isEmpty()) { 14952 if (instructionSets == null) { 14953 throw new IllegalStateException("instructionSet == null"); 14954 } 14955 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14956 for (String codePath : allCodePaths) { 14957 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14958 try { 14959 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14960 } catch (InstallerException ignored) { 14961 } 14962 } 14963 } 14964 } 14965 } 14966 14967 /** 14968 * Logic to handle installation of non-ASEC applications, including copying 14969 * and renaming logic. 14970 */ 14971 class FileInstallArgs extends InstallArgs { 14972 private File codeFile; 14973 private File resourceFile; 14974 14975 // Example topology: 14976 // /data/app/com.example/base.apk 14977 // /data/app/com.example/split_foo.apk 14978 // /data/app/com.example/lib/arm/libfoo.so 14979 // /data/app/com.example/lib/arm64/libfoo.so 14980 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14981 14982 /** New install */ 14983 FileInstallArgs(InstallParams params) { 14984 super(params.origin, params.move, params.observer, params.installFlags, 14985 params.installerPackageName, params.volumeUuid, 14986 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14987 params.grantedRuntimePermissions, 14988 params.traceMethod, params.traceCookie, params.certificates, 14989 params.installReason); 14990 if (isFwdLocked()) { 14991 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14992 } 14993 } 14994 14995 /** Existing install */ 14996 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14997 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14998 null, null, null, 0, null /*certificates*/, 14999 PackageManager.INSTALL_REASON_UNKNOWN); 15000 this.codeFile = (codePath != null) ? new File(codePath) : null; 15001 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15002 } 15003 15004 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15005 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15006 try { 15007 return doCopyApk(imcs, temp); 15008 } finally { 15009 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15010 } 15011 } 15012 15013 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15014 if (origin.staged) { 15015 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15016 codeFile = origin.file; 15017 resourceFile = origin.file; 15018 return PackageManager.INSTALL_SUCCEEDED; 15019 } 15020 15021 try { 15022 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15023 final File tempDir = 15024 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15025 codeFile = tempDir; 15026 resourceFile = tempDir; 15027 } catch (IOException e) { 15028 Slog.w(TAG, "Failed to create copy file: " + e); 15029 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15030 } 15031 15032 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15033 @Override 15034 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15035 if (!FileUtils.isValidExtFilename(name)) { 15036 throw new IllegalArgumentException("Invalid filename: " + name); 15037 } 15038 try { 15039 final File file = new File(codeFile, name); 15040 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15041 O_RDWR | O_CREAT, 0644); 15042 Os.chmod(file.getAbsolutePath(), 0644); 15043 return new ParcelFileDescriptor(fd); 15044 } catch (ErrnoException e) { 15045 throw new RemoteException("Failed to open: " + e.getMessage()); 15046 } 15047 } 15048 }; 15049 15050 int ret = PackageManager.INSTALL_SUCCEEDED; 15051 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15052 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15053 Slog.e(TAG, "Failed to copy package"); 15054 return ret; 15055 } 15056 15057 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15058 NativeLibraryHelper.Handle handle = null; 15059 try { 15060 handle = NativeLibraryHelper.Handle.create(codeFile); 15061 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15062 abiOverride); 15063 } catch (IOException e) { 15064 Slog.e(TAG, "Copying native libraries failed", e); 15065 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15066 } finally { 15067 IoUtils.closeQuietly(handle); 15068 } 15069 15070 return ret; 15071 } 15072 15073 int doPreInstall(int status) { 15074 if (status != PackageManager.INSTALL_SUCCEEDED) { 15075 cleanUp(); 15076 } 15077 return status; 15078 } 15079 15080 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15081 if (status != PackageManager.INSTALL_SUCCEEDED) { 15082 cleanUp(); 15083 return false; 15084 } 15085 15086 final File targetDir = codeFile.getParentFile(); 15087 final File beforeCodeFile = codeFile; 15088 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15089 15090 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15091 try { 15092 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15093 } catch (ErrnoException e) { 15094 Slog.w(TAG, "Failed to rename", e); 15095 return false; 15096 } 15097 15098 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15099 Slog.w(TAG, "Failed to restorecon"); 15100 return false; 15101 } 15102 15103 // Reflect the rename internally 15104 codeFile = afterCodeFile; 15105 resourceFile = afterCodeFile; 15106 15107 // Reflect the rename in scanned details 15108 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15109 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15110 afterCodeFile, pkg.baseCodePath)); 15111 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15112 afterCodeFile, pkg.splitCodePaths)); 15113 15114 // Reflect the rename in app info 15115 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15116 pkg.setApplicationInfoCodePath(pkg.codePath); 15117 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15118 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15119 pkg.setApplicationInfoResourcePath(pkg.codePath); 15120 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15121 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15122 15123 return true; 15124 } 15125 15126 int doPostInstall(int status, int uid) { 15127 if (status != PackageManager.INSTALL_SUCCEEDED) { 15128 cleanUp(); 15129 } 15130 return status; 15131 } 15132 15133 @Override 15134 String getCodePath() { 15135 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15136 } 15137 15138 @Override 15139 String getResourcePath() { 15140 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15141 } 15142 15143 private boolean cleanUp() { 15144 if (codeFile == null || !codeFile.exists()) { 15145 return false; 15146 } 15147 15148 removeCodePathLI(codeFile); 15149 15150 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15151 resourceFile.delete(); 15152 } 15153 15154 return true; 15155 } 15156 15157 void cleanUpResourcesLI() { 15158 // Try enumerating all code paths before deleting 15159 List<String> allCodePaths = Collections.EMPTY_LIST; 15160 if (codeFile != null && codeFile.exists()) { 15161 try { 15162 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15163 allCodePaths = pkg.getAllCodePaths(); 15164 } catch (PackageParserException e) { 15165 // Ignored; we tried our best 15166 } 15167 } 15168 15169 cleanUp(); 15170 removeDexFiles(allCodePaths, instructionSets); 15171 } 15172 15173 boolean doPostDeleteLI(boolean delete) { 15174 // XXX err, shouldn't we respect the delete flag? 15175 cleanUpResourcesLI(); 15176 return true; 15177 } 15178 } 15179 15180 private boolean isAsecExternal(String cid) { 15181 final String asecPath = PackageHelper.getSdFilesystem(cid); 15182 return !asecPath.startsWith(mAsecInternalPath); 15183 } 15184 15185 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15186 PackageManagerException { 15187 if (copyRet < 0) { 15188 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15189 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15190 throw new PackageManagerException(copyRet, message); 15191 } 15192 } 15193 } 15194 15195 /** 15196 * Extract the StorageManagerService "container ID" from the full code path of an 15197 * .apk. 15198 */ 15199 static String cidFromCodePath(String fullCodePath) { 15200 int eidx = fullCodePath.lastIndexOf("/"); 15201 String subStr1 = fullCodePath.substring(0, eidx); 15202 int sidx = subStr1.lastIndexOf("/"); 15203 return subStr1.substring(sidx+1, eidx); 15204 } 15205 15206 /** 15207 * Logic to handle installation of ASEC applications, including copying and 15208 * renaming logic. 15209 */ 15210 class AsecInstallArgs extends InstallArgs { 15211 static final String RES_FILE_NAME = "pkg.apk"; 15212 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15213 15214 String cid; 15215 String packagePath; 15216 String resourcePath; 15217 15218 /** New install */ 15219 AsecInstallArgs(InstallParams params) { 15220 super(params.origin, params.move, params.observer, params.installFlags, 15221 params.installerPackageName, params.volumeUuid, 15222 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15223 params.grantedRuntimePermissions, 15224 params.traceMethod, params.traceCookie, params.certificates, 15225 params.installReason); 15226 } 15227 15228 /** Existing install */ 15229 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15230 boolean isExternal, boolean isForwardLocked) { 15231 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15232 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15233 instructionSets, null, null, null, 0, null /*certificates*/, 15234 PackageManager.INSTALL_REASON_UNKNOWN); 15235 // Hackily pretend we're still looking at a full code path 15236 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15237 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15238 } 15239 15240 // Extract cid from fullCodePath 15241 int eidx = fullCodePath.lastIndexOf("/"); 15242 String subStr1 = fullCodePath.substring(0, eidx); 15243 int sidx = subStr1.lastIndexOf("/"); 15244 cid = subStr1.substring(sidx+1, eidx); 15245 setMountPath(subStr1); 15246 } 15247 15248 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15249 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15250 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15251 instructionSets, null, null, null, 0, null /*certificates*/, 15252 PackageManager.INSTALL_REASON_UNKNOWN); 15253 this.cid = cid; 15254 setMountPath(PackageHelper.getSdDir(cid)); 15255 } 15256 15257 void createCopyFile() { 15258 cid = mInstallerService.allocateExternalStageCidLegacy(); 15259 } 15260 15261 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15262 if (origin.staged && origin.cid != null) { 15263 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15264 cid = origin.cid; 15265 setMountPath(PackageHelper.getSdDir(cid)); 15266 return PackageManager.INSTALL_SUCCEEDED; 15267 } 15268 15269 if (temp) { 15270 createCopyFile(); 15271 } else { 15272 /* 15273 * Pre-emptively destroy the container since it's destroyed if 15274 * copying fails due to it existing anyway. 15275 */ 15276 PackageHelper.destroySdDir(cid); 15277 } 15278 15279 final String newMountPath = imcs.copyPackageToContainer( 15280 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15281 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15282 15283 if (newMountPath != null) { 15284 setMountPath(newMountPath); 15285 return PackageManager.INSTALL_SUCCEEDED; 15286 } else { 15287 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15288 } 15289 } 15290 15291 @Override 15292 String getCodePath() { 15293 return packagePath; 15294 } 15295 15296 @Override 15297 String getResourcePath() { 15298 return resourcePath; 15299 } 15300 15301 int doPreInstall(int status) { 15302 if (status != PackageManager.INSTALL_SUCCEEDED) { 15303 // Destroy container 15304 PackageHelper.destroySdDir(cid); 15305 } else { 15306 boolean mounted = PackageHelper.isContainerMounted(cid); 15307 if (!mounted) { 15308 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15309 Process.SYSTEM_UID); 15310 if (newMountPath != null) { 15311 setMountPath(newMountPath); 15312 } else { 15313 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15314 } 15315 } 15316 } 15317 return status; 15318 } 15319 15320 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15321 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15322 String newMountPath = null; 15323 if (PackageHelper.isContainerMounted(cid)) { 15324 // Unmount the container 15325 if (!PackageHelper.unMountSdDir(cid)) { 15326 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15327 return false; 15328 } 15329 } 15330 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15331 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15332 " which might be stale. Will try to clean up."); 15333 // Clean up the stale container and proceed to recreate. 15334 if (!PackageHelper.destroySdDir(newCacheId)) { 15335 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15336 return false; 15337 } 15338 // Successfully cleaned up stale container. Try to rename again. 15339 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15340 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15341 + " inspite of cleaning it up."); 15342 return false; 15343 } 15344 } 15345 if (!PackageHelper.isContainerMounted(newCacheId)) { 15346 Slog.w(TAG, "Mounting container " + newCacheId); 15347 newMountPath = PackageHelper.mountSdDir(newCacheId, 15348 getEncryptKey(), Process.SYSTEM_UID); 15349 } else { 15350 newMountPath = PackageHelper.getSdDir(newCacheId); 15351 } 15352 if (newMountPath == null) { 15353 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15354 return false; 15355 } 15356 Log.i(TAG, "Succesfully renamed " + cid + 15357 " to " + newCacheId + 15358 " at new path: " + newMountPath); 15359 cid = newCacheId; 15360 15361 final File beforeCodeFile = new File(packagePath); 15362 setMountPath(newMountPath); 15363 final File afterCodeFile = new File(packagePath); 15364 15365 // Reflect the rename in scanned details 15366 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15367 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15368 afterCodeFile, pkg.baseCodePath)); 15369 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15370 afterCodeFile, pkg.splitCodePaths)); 15371 15372 // Reflect the rename in app info 15373 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15374 pkg.setApplicationInfoCodePath(pkg.codePath); 15375 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15376 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15377 pkg.setApplicationInfoResourcePath(pkg.codePath); 15378 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15379 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15380 15381 return true; 15382 } 15383 15384 private void setMountPath(String mountPath) { 15385 final File mountFile = new File(mountPath); 15386 15387 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15388 if (monolithicFile.exists()) { 15389 packagePath = monolithicFile.getAbsolutePath(); 15390 if (isFwdLocked()) { 15391 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15392 } else { 15393 resourcePath = packagePath; 15394 } 15395 } else { 15396 packagePath = mountFile.getAbsolutePath(); 15397 resourcePath = packagePath; 15398 } 15399 } 15400 15401 int doPostInstall(int status, int uid) { 15402 if (status != PackageManager.INSTALL_SUCCEEDED) { 15403 cleanUp(); 15404 } else { 15405 final int groupOwner; 15406 final String protectedFile; 15407 if (isFwdLocked()) { 15408 groupOwner = UserHandle.getSharedAppGid(uid); 15409 protectedFile = RES_FILE_NAME; 15410 } else { 15411 groupOwner = -1; 15412 protectedFile = null; 15413 } 15414 15415 if (uid < Process.FIRST_APPLICATION_UID 15416 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15417 Slog.e(TAG, "Failed to finalize " + cid); 15418 PackageHelper.destroySdDir(cid); 15419 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15420 } 15421 15422 boolean mounted = PackageHelper.isContainerMounted(cid); 15423 if (!mounted) { 15424 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15425 } 15426 } 15427 return status; 15428 } 15429 15430 private void cleanUp() { 15431 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15432 15433 // Destroy secure container 15434 PackageHelper.destroySdDir(cid); 15435 } 15436 15437 private List<String> getAllCodePaths() { 15438 final File codeFile = new File(getCodePath()); 15439 if (codeFile != null && codeFile.exists()) { 15440 try { 15441 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15442 return pkg.getAllCodePaths(); 15443 } catch (PackageParserException e) { 15444 // Ignored; we tried our best 15445 } 15446 } 15447 return Collections.EMPTY_LIST; 15448 } 15449 15450 void cleanUpResourcesLI() { 15451 // Enumerate all code paths before deleting 15452 cleanUpResourcesLI(getAllCodePaths()); 15453 } 15454 15455 private void cleanUpResourcesLI(List<String> allCodePaths) { 15456 cleanUp(); 15457 removeDexFiles(allCodePaths, instructionSets); 15458 } 15459 15460 String getPackageName() { 15461 return getAsecPackageName(cid); 15462 } 15463 15464 boolean doPostDeleteLI(boolean delete) { 15465 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15466 final List<String> allCodePaths = getAllCodePaths(); 15467 boolean mounted = PackageHelper.isContainerMounted(cid); 15468 if (mounted) { 15469 // Unmount first 15470 if (PackageHelper.unMountSdDir(cid)) { 15471 mounted = false; 15472 } 15473 } 15474 if (!mounted && delete) { 15475 cleanUpResourcesLI(allCodePaths); 15476 } 15477 return !mounted; 15478 } 15479 15480 @Override 15481 int doPreCopy() { 15482 if (isFwdLocked()) { 15483 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15484 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15485 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15486 } 15487 } 15488 15489 return PackageManager.INSTALL_SUCCEEDED; 15490 } 15491 15492 @Override 15493 int doPostCopy(int uid) { 15494 if (isFwdLocked()) { 15495 if (uid < Process.FIRST_APPLICATION_UID 15496 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15497 RES_FILE_NAME)) { 15498 Slog.e(TAG, "Failed to finalize " + cid); 15499 PackageHelper.destroySdDir(cid); 15500 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15501 } 15502 } 15503 15504 return PackageManager.INSTALL_SUCCEEDED; 15505 } 15506 } 15507 15508 /** 15509 * Logic to handle movement of existing installed applications. 15510 */ 15511 class MoveInstallArgs extends InstallArgs { 15512 private File codeFile; 15513 private File resourceFile; 15514 15515 /** New install */ 15516 MoveInstallArgs(InstallParams params) { 15517 super(params.origin, params.move, params.observer, params.installFlags, 15518 params.installerPackageName, params.volumeUuid, 15519 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15520 params.grantedRuntimePermissions, 15521 params.traceMethod, params.traceCookie, params.certificates, 15522 params.installReason); 15523 } 15524 15525 int copyApk(IMediaContainerService imcs, boolean temp) { 15526 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15527 + move.fromUuid + " to " + move.toUuid); 15528 synchronized (mInstaller) { 15529 try { 15530 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15531 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15532 } catch (InstallerException e) { 15533 Slog.w(TAG, "Failed to move app", e); 15534 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15535 } 15536 } 15537 15538 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15539 resourceFile = codeFile; 15540 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15541 15542 return PackageManager.INSTALL_SUCCEEDED; 15543 } 15544 15545 int doPreInstall(int status) { 15546 if (status != PackageManager.INSTALL_SUCCEEDED) { 15547 cleanUp(move.toUuid); 15548 } 15549 return status; 15550 } 15551 15552 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15553 if (status != PackageManager.INSTALL_SUCCEEDED) { 15554 cleanUp(move.toUuid); 15555 return false; 15556 } 15557 15558 // Reflect the move in app info 15559 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15560 pkg.setApplicationInfoCodePath(pkg.codePath); 15561 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15562 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15563 pkg.setApplicationInfoResourcePath(pkg.codePath); 15564 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15565 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15566 15567 return true; 15568 } 15569 15570 int doPostInstall(int status, int uid) { 15571 if (status == PackageManager.INSTALL_SUCCEEDED) { 15572 cleanUp(move.fromUuid); 15573 } else { 15574 cleanUp(move.toUuid); 15575 } 15576 return status; 15577 } 15578 15579 @Override 15580 String getCodePath() { 15581 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15582 } 15583 15584 @Override 15585 String getResourcePath() { 15586 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15587 } 15588 15589 private boolean cleanUp(String volumeUuid) { 15590 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15591 move.dataAppName); 15592 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15593 final int[] userIds = sUserManager.getUserIds(); 15594 synchronized (mInstallLock) { 15595 // Clean up both app data and code 15596 // All package moves are frozen until finished 15597 for (int userId : userIds) { 15598 try { 15599 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15600 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15601 } catch (InstallerException e) { 15602 Slog.w(TAG, String.valueOf(e)); 15603 } 15604 } 15605 removeCodePathLI(codeFile); 15606 } 15607 return true; 15608 } 15609 15610 void cleanUpResourcesLI() { 15611 throw new UnsupportedOperationException(); 15612 } 15613 15614 boolean doPostDeleteLI(boolean delete) { 15615 throw new UnsupportedOperationException(); 15616 } 15617 } 15618 15619 static String getAsecPackageName(String packageCid) { 15620 int idx = packageCid.lastIndexOf("-"); 15621 if (idx == -1) { 15622 return packageCid; 15623 } 15624 return packageCid.substring(0, idx); 15625 } 15626 15627 // Utility method used to create code paths based on package name and available index. 15628 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15629 String idxStr = ""; 15630 int idx = 1; 15631 // Fall back to default value of idx=1 if prefix is not 15632 // part of oldCodePath 15633 if (oldCodePath != null) { 15634 String subStr = oldCodePath; 15635 // Drop the suffix right away 15636 if (suffix != null && subStr.endsWith(suffix)) { 15637 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15638 } 15639 // If oldCodePath already contains prefix find out the 15640 // ending index to either increment or decrement. 15641 int sidx = subStr.lastIndexOf(prefix); 15642 if (sidx != -1) { 15643 subStr = subStr.substring(sidx + prefix.length()); 15644 if (subStr != null) { 15645 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15646 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15647 } 15648 try { 15649 idx = Integer.parseInt(subStr); 15650 if (idx <= 1) { 15651 idx++; 15652 } else { 15653 idx--; 15654 } 15655 } catch(NumberFormatException e) { 15656 } 15657 } 15658 } 15659 } 15660 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15661 return prefix + idxStr; 15662 } 15663 15664 private File getNextCodePath(File targetDir, String packageName) { 15665 File result; 15666 SecureRandom random = new SecureRandom(); 15667 byte[] bytes = new byte[16]; 15668 do { 15669 random.nextBytes(bytes); 15670 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15671 result = new File(targetDir, packageName + "-" + suffix); 15672 } while (result.exists()); 15673 return result; 15674 } 15675 15676 // Utility method that returns the relative package path with respect 15677 // to the installation directory. Like say for /data/data/com.test-1.apk 15678 // string com.test-1 is returned. 15679 static String deriveCodePathName(String codePath) { 15680 if (codePath == null) { 15681 return null; 15682 } 15683 final File codeFile = new File(codePath); 15684 final String name = codeFile.getName(); 15685 if (codeFile.isDirectory()) { 15686 return name; 15687 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15688 final int lastDot = name.lastIndexOf('.'); 15689 return name.substring(0, lastDot); 15690 } else { 15691 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15692 return null; 15693 } 15694 } 15695 15696 static class PackageInstalledInfo { 15697 String name; 15698 int uid; 15699 // The set of users that originally had this package installed. 15700 int[] origUsers; 15701 // The set of users that now have this package installed. 15702 int[] newUsers; 15703 PackageParser.Package pkg; 15704 int returnCode; 15705 String returnMsg; 15706 PackageRemovedInfo removedInfo; 15707 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15708 15709 public void setError(int code, String msg) { 15710 setReturnCode(code); 15711 setReturnMessage(msg); 15712 Slog.w(TAG, msg); 15713 } 15714 15715 public void setError(String msg, PackageParserException e) { 15716 setReturnCode(e.error); 15717 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15718 Slog.w(TAG, msg, e); 15719 } 15720 15721 public void setError(String msg, PackageManagerException e) { 15722 returnCode = e.error; 15723 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15724 Slog.w(TAG, msg, e); 15725 } 15726 15727 public void setReturnCode(int returnCode) { 15728 this.returnCode = returnCode; 15729 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15730 for (int i = 0; i < childCount; i++) { 15731 addedChildPackages.valueAt(i).returnCode = returnCode; 15732 } 15733 } 15734 15735 private void setReturnMessage(String returnMsg) { 15736 this.returnMsg = returnMsg; 15737 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15738 for (int i = 0; i < childCount; i++) { 15739 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15740 } 15741 } 15742 15743 // In some error cases we want to convey more info back to the observer 15744 String origPackage; 15745 String origPermission; 15746 } 15747 15748 /* 15749 * Install a non-existing package. 15750 */ 15751 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15752 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15753 PackageInstalledInfo res, int installReason) { 15754 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15755 15756 // Remember this for later, in case we need to rollback this install 15757 String pkgName = pkg.packageName; 15758 15759 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15760 15761 synchronized(mPackages) { 15762 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15763 if (renamedPackage != null) { 15764 // A package with the same name is already installed, though 15765 // it has been renamed to an older name. The package we 15766 // are trying to install should be installed as an update to 15767 // the existing one, but that has not been requested, so bail. 15768 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15769 + " without first uninstalling package running as " 15770 + renamedPackage); 15771 return; 15772 } 15773 if (mPackages.containsKey(pkgName)) { 15774 // Don't allow installation over an existing package with the same name. 15775 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15776 + " without first uninstalling."); 15777 return; 15778 } 15779 } 15780 15781 try { 15782 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15783 System.currentTimeMillis(), user); 15784 15785 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15786 15787 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15788 prepareAppDataAfterInstallLIF(newPackage); 15789 15790 } else { 15791 // Remove package from internal structures, but keep around any 15792 // data that might have already existed 15793 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15794 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15795 } 15796 } catch (PackageManagerException e) { 15797 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15798 } 15799 15800 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15801 } 15802 15803 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15804 // Can't rotate keys during boot or if sharedUser. 15805 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15806 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15807 return false; 15808 } 15809 // app is using upgradeKeySets; make sure all are valid 15810 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15811 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15812 for (int i = 0; i < upgradeKeySets.length; i++) { 15813 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15814 Slog.wtf(TAG, "Package " 15815 + (oldPs.name != null ? oldPs.name : "<null>") 15816 + " contains upgrade-key-set reference to unknown key-set: " 15817 + upgradeKeySets[i] 15818 + " reverting to signatures check."); 15819 return false; 15820 } 15821 } 15822 return true; 15823 } 15824 15825 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15826 // Upgrade keysets are being used. Determine if new package has a superset of the 15827 // required keys. 15828 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15829 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15830 for (int i = 0; i < upgradeKeySets.length; i++) { 15831 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15832 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15833 return true; 15834 } 15835 } 15836 return false; 15837 } 15838 15839 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15840 try (DigestInputStream digestStream = 15841 new DigestInputStream(new FileInputStream(file), digest)) { 15842 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15843 } 15844 } 15845 15846 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15847 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15848 int installReason) { 15849 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15850 15851 final PackageParser.Package oldPackage; 15852 final String pkgName = pkg.packageName; 15853 final int[] allUsers; 15854 final int[] installedUsers; 15855 15856 synchronized(mPackages) { 15857 oldPackage = mPackages.get(pkgName); 15858 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15859 15860 // don't allow upgrade to target a release SDK from a pre-release SDK 15861 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15862 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15863 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15864 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15865 if (oldTargetsPreRelease 15866 && !newTargetsPreRelease 15867 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15868 Slog.w(TAG, "Can't install package targeting released sdk"); 15869 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15870 return; 15871 } 15872 15873 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15874 15875 // don't allow an upgrade from full to ephemeral 15876 if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) { 15877 // can't downgrade from full to instant 15878 Slog.w(TAG, "Can't replace app with instant app: " + pkgName); 15879 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15880 return; 15881 } 15882 15883 // verify signatures are valid 15884 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15885 if (!checkUpgradeKeySetLP(ps, pkg)) { 15886 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15887 "New package not signed by keys specified by upgrade-keysets: " 15888 + pkgName); 15889 return; 15890 } 15891 } else { 15892 // default to original signature matching 15893 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15894 != PackageManager.SIGNATURE_MATCH) { 15895 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15896 "New package has a different signature: " + pkgName); 15897 return; 15898 } 15899 } 15900 15901 // don't allow a system upgrade unless the upgrade hash matches 15902 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15903 byte[] digestBytes = null; 15904 try { 15905 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15906 updateDigest(digest, new File(pkg.baseCodePath)); 15907 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15908 for (String path : pkg.splitCodePaths) { 15909 updateDigest(digest, new File(path)); 15910 } 15911 } 15912 digestBytes = digest.digest(); 15913 } catch (NoSuchAlgorithmException | IOException e) { 15914 res.setError(INSTALL_FAILED_INVALID_APK, 15915 "Could not compute hash: " + pkgName); 15916 return; 15917 } 15918 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15919 res.setError(INSTALL_FAILED_INVALID_APK, 15920 "New package fails restrict-update check: " + pkgName); 15921 return; 15922 } 15923 // retain upgrade restriction 15924 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15925 } 15926 15927 // Check for shared user id changes 15928 String invalidPackageName = 15929 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15930 if (invalidPackageName != null) { 15931 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15932 "Package " + invalidPackageName + " tried to change user " 15933 + oldPackage.mSharedUserId); 15934 return; 15935 } 15936 15937 // In case of rollback, remember per-user/profile install state 15938 allUsers = sUserManager.getUserIds(); 15939 installedUsers = ps.queryInstalledUsers(allUsers, true); 15940 } 15941 15942 // Update what is removed 15943 res.removedInfo = new PackageRemovedInfo(); 15944 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15945 res.removedInfo.removedPackage = oldPackage.packageName; 15946 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15947 res.removedInfo.isUpdate = true; 15948 res.removedInfo.origUsers = installedUsers; 15949 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15950 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15951 for (int i = 0; i < installedUsers.length; i++) { 15952 final int userId = installedUsers[i]; 15953 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15954 } 15955 15956 final int childCount = (oldPackage.childPackages != null) 15957 ? oldPackage.childPackages.size() : 0; 15958 for (int i = 0; i < childCount; i++) { 15959 boolean childPackageUpdated = false; 15960 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15961 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15962 if (res.addedChildPackages != null) { 15963 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15964 if (childRes != null) { 15965 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15966 childRes.removedInfo.removedPackage = childPkg.packageName; 15967 childRes.removedInfo.isUpdate = true; 15968 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15969 childPackageUpdated = true; 15970 } 15971 } 15972 if (!childPackageUpdated) { 15973 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15974 childRemovedRes.removedPackage = childPkg.packageName; 15975 childRemovedRes.isUpdate = false; 15976 childRemovedRes.dataRemoved = true; 15977 synchronized (mPackages) { 15978 if (childPs != null) { 15979 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15980 } 15981 } 15982 if (res.removedInfo.removedChildPackages == null) { 15983 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15984 } 15985 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15986 } 15987 } 15988 15989 boolean sysPkg = (isSystemApp(oldPackage)); 15990 if (sysPkg) { 15991 // Set the system/privileged flags as needed 15992 final boolean privileged = 15993 (oldPackage.applicationInfo.privateFlags 15994 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15995 final int systemPolicyFlags = policyFlags 15996 | PackageParser.PARSE_IS_SYSTEM 15997 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15998 15999 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16000 user, allUsers, installerPackageName, res, installReason); 16001 } else { 16002 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16003 user, allUsers, installerPackageName, res, installReason); 16004 } 16005 } 16006 16007 public List<String> getPreviousCodePaths(String packageName) { 16008 final PackageSetting ps = mSettings.mPackages.get(packageName); 16009 final List<String> result = new ArrayList<String>(); 16010 if (ps != null && ps.oldCodePaths != null) { 16011 result.addAll(ps.oldCodePaths); 16012 } 16013 return result; 16014 } 16015 16016 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16017 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16018 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16019 int installReason) { 16020 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16021 + deletedPackage); 16022 16023 String pkgName = deletedPackage.packageName; 16024 boolean deletedPkg = true; 16025 boolean addedPkg = false; 16026 boolean updatedSettings = false; 16027 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16028 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16029 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16030 16031 final long origUpdateTime = (pkg.mExtras != null) 16032 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16033 16034 // First delete the existing package while retaining the data directory 16035 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16036 res.removedInfo, true, pkg)) { 16037 // If the existing package wasn't successfully deleted 16038 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16039 deletedPkg = false; 16040 } else { 16041 // Successfully deleted the old package; proceed with replace. 16042 16043 // If deleted package lived in a container, give users a chance to 16044 // relinquish resources before killing. 16045 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16046 if (DEBUG_INSTALL) { 16047 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16048 } 16049 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16050 final ArrayList<String> pkgList = new ArrayList<String>(1); 16051 pkgList.add(deletedPackage.applicationInfo.packageName); 16052 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16053 } 16054 16055 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16056 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16057 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16058 16059 try { 16060 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16061 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16062 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16063 installReason); 16064 16065 // Update the in-memory copy of the previous code paths. 16066 PackageSetting ps = mSettings.mPackages.get(pkgName); 16067 if (!killApp) { 16068 if (ps.oldCodePaths == null) { 16069 ps.oldCodePaths = new ArraySet<>(); 16070 } 16071 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16072 if (deletedPackage.splitCodePaths != null) { 16073 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16074 } 16075 } else { 16076 ps.oldCodePaths = null; 16077 } 16078 if (ps.childPackageNames != null) { 16079 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16080 final String childPkgName = ps.childPackageNames.get(i); 16081 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16082 childPs.oldCodePaths = ps.oldCodePaths; 16083 } 16084 } 16085 // set instant app status, but, only if it's explicitly specified 16086 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16087 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16088 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16089 prepareAppDataAfterInstallLIF(newPackage); 16090 addedPkg = true; 16091 } catch (PackageManagerException e) { 16092 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16093 } 16094 } 16095 16096 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16097 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16098 16099 // Revert all internal state mutations and added folders for the failed install 16100 if (addedPkg) { 16101 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16102 res.removedInfo, true, null); 16103 } 16104 16105 // Restore the old package 16106 if (deletedPkg) { 16107 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16108 File restoreFile = new File(deletedPackage.codePath); 16109 // Parse old package 16110 boolean oldExternal = isExternal(deletedPackage); 16111 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16112 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16113 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16114 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16115 try { 16116 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16117 null); 16118 } catch (PackageManagerException e) { 16119 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16120 + e.getMessage()); 16121 return; 16122 } 16123 16124 synchronized (mPackages) { 16125 // Ensure the installer package name up to date 16126 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16127 16128 // Update permissions for restored package 16129 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16130 16131 mSettings.writeLPr(); 16132 } 16133 16134 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16135 } 16136 } else { 16137 synchronized (mPackages) { 16138 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16139 if (ps != null) { 16140 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16141 if (res.removedInfo.removedChildPackages != null) { 16142 final int childCount = res.removedInfo.removedChildPackages.size(); 16143 // Iterate in reverse as we may modify the collection 16144 for (int i = childCount - 1; i >= 0; i--) { 16145 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16146 if (res.addedChildPackages.containsKey(childPackageName)) { 16147 res.removedInfo.removedChildPackages.removeAt(i); 16148 } else { 16149 PackageRemovedInfo childInfo = res.removedInfo 16150 .removedChildPackages.valueAt(i); 16151 childInfo.removedForAllUsers = mPackages.get( 16152 childInfo.removedPackage) == null; 16153 } 16154 } 16155 } 16156 } 16157 } 16158 } 16159 } 16160 16161 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16162 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16163 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16164 int installReason) { 16165 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16166 + ", old=" + deletedPackage); 16167 16168 final boolean disabledSystem; 16169 16170 // Remove existing system package 16171 removePackageLI(deletedPackage, true); 16172 16173 synchronized (mPackages) { 16174 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16175 } 16176 if (!disabledSystem) { 16177 // We didn't need to disable the .apk as a current system package, 16178 // which means we are replacing another update that is already 16179 // installed. We need to make sure to delete the older one's .apk. 16180 res.removedInfo.args = createInstallArgsForExisting(0, 16181 deletedPackage.applicationInfo.getCodePath(), 16182 deletedPackage.applicationInfo.getResourcePath(), 16183 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16184 } else { 16185 res.removedInfo.args = null; 16186 } 16187 16188 // Successfully disabled the old package. Now proceed with re-installation 16189 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16190 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16191 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16192 16193 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16194 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16195 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16196 16197 PackageParser.Package newPackage = null; 16198 try { 16199 // Add the package to the internal data structures 16200 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16201 16202 // Set the update and install times 16203 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16204 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16205 System.currentTimeMillis()); 16206 16207 // Update the package dynamic state if succeeded 16208 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16209 // Now that the install succeeded make sure we remove data 16210 // directories for any child package the update removed. 16211 final int deletedChildCount = (deletedPackage.childPackages != null) 16212 ? deletedPackage.childPackages.size() : 0; 16213 final int newChildCount = (newPackage.childPackages != null) 16214 ? newPackage.childPackages.size() : 0; 16215 for (int i = 0; i < deletedChildCount; i++) { 16216 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16217 boolean childPackageDeleted = true; 16218 for (int j = 0; j < newChildCount; j++) { 16219 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16220 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16221 childPackageDeleted = false; 16222 break; 16223 } 16224 } 16225 if (childPackageDeleted) { 16226 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16227 deletedChildPkg.packageName); 16228 if (ps != null && res.removedInfo.removedChildPackages != null) { 16229 PackageRemovedInfo removedChildRes = res.removedInfo 16230 .removedChildPackages.get(deletedChildPkg.packageName); 16231 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16232 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16233 } 16234 } 16235 } 16236 16237 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16238 installReason); 16239 prepareAppDataAfterInstallLIF(newPackage); 16240 } 16241 } catch (PackageManagerException e) { 16242 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16243 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16244 } 16245 16246 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16247 // Re installation failed. Restore old information 16248 // Remove new pkg information 16249 if (newPackage != null) { 16250 removeInstalledPackageLI(newPackage, true); 16251 } 16252 // Add back the old system package 16253 try { 16254 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16255 } catch (PackageManagerException e) { 16256 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16257 } 16258 16259 synchronized (mPackages) { 16260 if (disabledSystem) { 16261 enableSystemPackageLPw(deletedPackage); 16262 } 16263 16264 // Ensure the installer package name up to date 16265 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16266 16267 // Update permissions for restored package 16268 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16269 16270 mSettings.writeLPr(); 16271 } 16272 16273 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16274 + " after failed upgrade"); 16275 } 16276 } 16277 16278 /** 16279 * Checks whether the parent or any of the child packages have a change shared 16280 * user. For a package to be a valid update the shred users of the parent and 16281 * the children should match. We may later support changing child shared users. 16282 * @param oldPkg The updated package. 16283 * @param newPkg The update package. 16284 * @return The shared user that change between the versions. 16285 */ 16286 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16287 PackageParser.Package newPkg) { 16288 // Check parent shared user 16289 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16290 return newPkg.packageName; 16291 } 16292 // Check child shared users 16293 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16294 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16295 for (int i = 0; i < newChildCount; i++) { 16296 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16297 // If this child was present, did it have the same shared user? 16298 for (int j = 0; j < oldChildCount; j++) { 16299 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16300 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16301 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16302 return newChildPkg.packageName; 16303 } 16304 } 16305 } 16306 return null; 16307 } 16308 16309 private void removeNativeBinariesLI(PackageSetting ps) { 16310 // Remove the lib path for the parent package 16311 if (ps != null) { 16312 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16313 // Remove the lib path for the child packages 16314 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16315 for (int i = 0; i < childCount; i++) { 16316 PackageSetting childPs = null; 16317 synchronized (mPackages) { 16318 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16319 } 16320 if (childPs != null) { 16321 NativeLibraryHelper.removeNativeBinariesLI(childPs 16322 .legacyNativeLibraryPathString); 16323 } 16324 } 16325 } 16326 } 16327 16328 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16329 // Enable the parent package 16330 mSettings.enableSystemPackageLPw(pkg.packageName); 16331 // Enable the child packages 16332 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16333 for (int i = 0; i < childCount; i++) { 16334 PackageParser.Package childPkg = pkg.childPackages.get(i); 16335 mSettings.enableSystemPackageLPw(childPkg.packageName); 16336 } 16337 } 16338 16339 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16340 PackageParser.Package newPkg) { 16341 // Disable the parent package (parent always replaced) 16342 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16343 // Disable the child packages 16344 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16345 for (int i = 0; i < childCount; i++) { 16346 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16347 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16348 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16349 } 16350 return disabled; 16351 } 16352 16353 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16354 String installerPackageName) { 16355 // Enable the parent package 16356 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16357 // Enable the child packages 16358 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16359 for (int i = 0; i < childCount; i++) { 16360 PackageParser.Package childPkg = pkg.childPackages.get(i); 16361 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16362 } 16363 } 16364 16365 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16366 // Collect all used permissions in the UID 16367 ArraySet<String> usedPermissions = new ArraySet<>(); 16368 final int packageCount = su.packages.size(); 16369 for (int i = 0; i < packageCount; i++) { 16370 PackageSetting ps = su.packages.valueAt(i); 16371 if (ps.pkg == null) { 16372 continue; 16373 } 16374 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16375 for (int j = 0; j < requestedPermCount; j++) { 16376 String permission = ps.pkg.requestedPermissions.get(j); 16377 BasePermission bp = mSettings.mPermissions.get(permission); 16378 if (bp != null) { 16379 usedPermissions.add(permission); 16380 } 16381 } 16382 } 16383 16384 PermissionsState permissionsState = su.getPermissionsState(); 16385 // Prune install permissions 16386 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16387 final int installPermCount = installPermStates.size(); 16388 for (int i = installPermCount - 1; i >= 0; i--) { 16389 PermissionState permissionState = installPermStates.get(i); 16390 if (!usedPermissions.contains(permissionState.getName())) { 16391 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16392 if (bp != null) { 16393 permissionsState.revokeInstallPermission(bp); 16394 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16395 PackageManager.MASK_PERMISSION_FLAGS, 0); 16396 } 16397 } 16398 } 16399 16400 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16401 16402 // Prune runtime permissions 16403 for (int userId : allUserIds) { 16404 List<PermissionState> runtimePermStates = permissionsState 16405 .getRuntimePermissionStates(userId); 16406 final int runtimePermCount = runtimePermStates.size(); 16407 for (int i = runtimePermCount - 1; i >= 0; i--) { 16408 PermissionState permissionState = runtimePermStates.get(i); 16409 if (!usedPermissions.contains(permissionState.getName())) { 16410 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16411 if (bp != null) { 16412 permissionsState.revokeRuntimePermission(bp, userId); 16413 permissionsState.updatePermissionFlags(bp, userId, 16414 PackageManager.MASK_PERMISSION_FLAGS, 0); 16415 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16416 runtimePermissionChangedUserIds, userId); 16417 } 16418 } 16419 } 16420 } 16421 16422 return runtimePermissionChangedUserIds; 16423 } 16424 16425 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16426 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16427 // Update the parent package setting 16428 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16429 res, user, installReason); 16430 // Update the child packages setting 16431 final int childCount = (newPackage.childPackages != null) 16432 ? newPackage.childPackages.size() : 0; 16433 for (int i = 0; i < childCount; i++) { 16434 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16435 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16436 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16437 childRes.origUsers, childRes, user, installReason); 16438 } 16439 } 16440 16441 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16442 String installerPackageName, int[] allUsers, int[] installedForUsers, 16443 PackageInstalledInfo res, UserHandle user, int installReason) { 16444 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16445 16446 String pkgName = newPackage.packageName; 16447 synchronized (mPackages) { 16448 //write settings. the installStatus will be incomplete at this stage. 16449 //note that the new package setting would have already been 16450 //added to mPackages. It hasn't been persisted yet. 16451 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16452 // TODO: Remove this write? It's also written at the end of this method 16453 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16454 mSettings.writeLPr(); 16455 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16456 } 16457 16458 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16459 synchronized (mPackages) { 16460 updatePermissionsLPw(newPackage.packageName, newPackage, 16461 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16462 ? UPDATE_PERMISSIONS_ALL : 0)); 16463 // For system-bundled packages, we assume that installing an upgraded version 16464 // of the package implies that the user actually wants to run that new code, 16465 // so we enable the package. 16466 PackageSetting ps = mSettings.mPackages.get(pkgName); 16467 final int userId = user.getIdentifier(); 16468 if (ps != null) { 16469 if (isSystemApp(newPackage)) { 16470 if (DEBUG_INSTALL) { 16471 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16472 } 16473 // Enable system package for requested users 16474 if (res.origUsers != null) { 16475 for (int origUserId : res.origUsers) { 16476 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16477 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16478 origUserId, installerPackageName); 16479 } 16480 } 16481 } 16482 // Also convey the prior install/uninstall state 16483 if (allUsers != null && installedForUsers != null) { 16484 for (int currentUserId : allUsers) { 16485 final boolean installed = ArrayUtils.contains( 16486 installedForUsers, currentUserId); 16487 if (DEBUG_INSTALL) { 16488 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16489 } 16490 ps.setInstalled(installed, currentUserId); 16491 } 16492 // these install state changes will be persisted in the 16493 // upcoming call to mSettings.writeLPr(). 16494 } 16495 } 16496 // It's implied that when a user requests installation, they want the app to be 16497 // installed and enabled. 16498 if (userId != UserHandle.USER_ALL) { 16499 ps.setInstalled(true, userId); 16500 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16501 } 16502 16503 // When replacing an existing package, preserve the original install reason for all 16504 // users that had the package installed before. 16505 final Set<Integer> previousUserIds = new ArraySet<>(); 16506 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16507 final int installReasonCount = res.removedInfo.installReasons.size(); 16508 for (int i = 0; i < installReasonCount; i++) { 16509 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16510 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16511 ps.setInstallReason(previousInstallReason, previousUserId); 16512 previousUserIds.add(previousUserId); 16513 } 16514 } 16515 16516 // Set install reason for users that are having the package newly installed. 16517 if (userId == UserHandle.USER_ALL) { 16518 for (int currentUserId : sUserManager.getUserIds()) { 16519 if (!previousUserIds.contains(currentUserId)) { 16520 ps.setInstallReason(installReason, currentUserId); 16521 } 16522 } 16523 } else if (!previousUserIds.contains(userId)) { 16524 ps.setInstallReason(installReason, userId); 16525 } 16526 mSettings.writeKernelMappingLPr(ps); 16527 } 16528 res.name = pkgName; 16529 res.uid = newPackage.applicationInfo.uid; 16530 res.pkg = newPackage; 16531 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16532 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16533 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16534 //to update install status 16535 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16536 mSettings.writeLPr(); 16537 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16538 } 16539 16540 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16541 } 16542 16543 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16544 try { 16545 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16546 installPackageLI(args, res); 16547 } finally { 16548 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16549 } 16550 } 16551 16552 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16553 final int installFlags = args.installFlags; 16554 final String installerPackageName = args.installerPackageName; 16555 final String volumeUuid = args.volumeUuid; 16556 final File tmpPackageFile = new File(args.getCodePath()); 16557 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16558 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16559 || (args.volumeUuid != null)); 16560 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16561 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16562 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16563 boolean replace = false; 16564 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16565 if (args.move != null) { 16566 // moving a complete application; perform an initial scan on the new install location 16567 scanFlags |= SCAN_INITIAL; 16568 } 16569 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16570 scanFlags |= SCAN_DONT_KILL_APP; 16571 } 16572 if (instantApp) { 16573 scanFlags |= SCAN_AS_INSTANT_APP; 16574 } 16575 if (fullApp) { 16576 scanFlags |= SCAN_AS_FULL_APP; 16577 } 16578 16579 // Result object to be returned 16580 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16581 16582 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16583 16584 // Sanity check 16585 if (instantApp && (forwardLocked || onExternal)) { 16586 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16587 + " external=" + onExternal); 16588 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16589 return; 16590 } 16591 16592 // Retrieve PackageSettings and parse package 16593 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16594 | PackageParser.PARSE_ENFORCE_CODE 16595 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16596 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16597 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16598 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16599 PackageParser pp = new PackageParser(); 16600 pp.setSeparateProcesses(mSeparateProcesses); 16601 pp.setDisplayMetrics(mMetrics); 16602 16603 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16604 final PackageParser.Package pkg; 16605 try { 16606 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16607 } catch (PackageParserException e) { 16608 res.setError("Failed parse during installPackageLI", e); 16609 return; 16610 } finally { 16611 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16612 } 16613 16614// // Ephemeral apps must have target SDK >= O. 16615// // TODO: Update conditional and error message when O gets locked down 16616// if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16617// res.setError(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID, 16618// "Ephemeral apps must have target SDK version of at least O"); 16619// return; 16620// } 16621 16622 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16623 // Static shared libraries have synthetic package names 16624 renameStaticSharedLibraryPackage(pkg); 16625 16626 // No static shared libs on external storage 16627 if (onExternal) { 16628 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16629 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16630 "Packages declaring static-shared libs cannot be updated"); 16631 return; 16632 } 16633 } 16634 16635 // If we are installing a clustered package add results for the children 16636 if (pkg.childPackages != null) { 16637 synchronized (mPackages) { 16638 final int childCount = pkg.childPackages.size(); 16639 for (int i = 0; i < childCount; i++) { 16640 PackageParser.Package childPkg = pkg.childPackages.get(i); 16641 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16642 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16643 childRes.pkg = childPkg; 16644 childRes.name = childPkg.packageName; 16645 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16646 if (childPs != null) { 16647 childRes.origUsers = childPs.queryInstalledUsers( 16648 sUserManager.getUserIds(), true); 16649 } 16650 if ((mPackages.containsKey(childPkg.packageName))) { 16651 childRes.removedInfo = new PackageRemovedInfo(); 16652 childRes.removedInfo.removedPackage = childPkg.packageName; 16653 } 16654 if (res.addedChildPackages == null) { 16655 res.addedChildPackages = new ArrayMap<>(); 16656 } 16657 res.addedChildPackages.put(childPkg.packageName, childRes); 16658 } 16659 } 16660 } 16661 16662 // If package doesn't declare API override, mark that we have an install 16663 // time CPU ABI override. 16664 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16665 pkg.cpuAbiOverride = args.abiOverride; 16666 } 16667 16668 String pkgName = res.name = pkg.packageName; 16669 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16670 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16671 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16672 return; 16673 } 16674 } 16675 16676 try { 16677 // either use what we've been given or parse directly from the APK 16678 if (args.certificates != null) { 16679 try { 16680 PackageParser.populateCertificates(pkg, args.certificates); 16681 } catch (PackageParserException e) { 16682 // there was something wrong with the certificates we were given; 16683 // try to pull them from the APK 16684 PackageParser.collectCertificates(pkg, parseFlags); 16685 } 16686 } else { 16687 PackageParser.collectCertificates(pkg, parseFlags); 16688 } 16689 } catch (PackageParserException e) { 16690 res.setError("Failed collect during installPackageLI", e); 16691 return; 16692 } 16693 16694 // Get rid of all references to package scan path via parser. 16695 pp = null; 16696 String oldCodePath = null; 16697 boolean systemApp = false; 16698 synchronized (mPackages) { 16699 // Check if installing already existing package 16700 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16701 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16702 if (pkg.mOriginalPackages != null 16703 && pkg.mOriginalPackages.contains(oldName) 16704 && mPackages.containsKey(oldName)) { 16705 // This package is derived from an original package, 16706 // and this device has been updating from that original 16707 // name. We must continue using the original name, so 16708 // rename the new package here. 16709 pkg.setPackageName(oldName); 16710 pkgName = pkg.packageName; 16711 replace = true; 16712 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16713 + oldName + " pkgName=" + pkgName); 16714 } else if (mPackages.containsKey(pkgName)) { 16715 // This package, under its official name, already exists 16716 // on the device; we should replace it. 16717 replace = true; 16718 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16719 } 16720 16721 // Child packages are installed through the parent package 16722 if (pkg.parentPackage != null) { 16723 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16724 "Package " + pkg.packageName + " is child of package " 16725 + pkg.parentPackage.parentPackage + ". Child packages " 16726 + "can be updated only through the parent package."); 16727 return; 16728 } 16729 16730 if (replace) { 16731 // Prevent apps opting out from runtime permissions 16732 PackageParser.Package oldPackage = mPackages.get(pkgName); 16733 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16734 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16735 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16736 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16737 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16738 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16739 + " doesn't support runtime permissions but the old" 16740 + " target SDK " + oldTargetSdk + " does."); 16741 return; 16742 } 16743 16744 // Prevent installing of child packages 16745 if (oldPackage.parentPackage != null) { 16746 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16747 "Package " + pkg.packageName + " is child of package " 16748 + oldPackage.parentPackage + ". Child packages " 16749 + "can be updated only through the parent package."); 16750 return; 16751 } 16752 } 16753 } 16754 16755 PackageSetting ps = mSettings.mPackages.get(pkgName); 16756 if (ps != null) { 16757 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16758 16759 // Static shared libs have same package with different versions where 16760 // we internally use a synthetic package name to allow multiple versions 16761 // of the same package, therefore we need to compare signatures against 16762 // the package setting for the latest library version. 16763 PackageSetting signatureCheckPs = ps; 16764 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16765 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16766 if (libraryEntry != null) { 16767 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16768 } 16769 } 16770 16771 // Quick sanity check that we're signed correctly if updating; 16772 // we'll check this again later when scanning, but we want to 16773 // bail early here before tripping over redefined permissions. 16774 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16775 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16776 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16777 + pkg.packageName + " upgrade keys do not match the " 16778 + "previously installed version"); 16779 return; 16780 } 16781 } else { 16782 try { 16783 verifySignaturesLP(signatureCheckPs, pkg); 16784 } catch (PackageManagerException e) { 16785 res.setError(e.error, e.getMessage()); 16786 return; 16787 } 16788 } 16789 16790 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16791 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16792 systemApp = (ps.pkg.applicationInfo.flags & 16793 ApplicationInfo.FLAG_SYSTEM) != 0; 16794 } 16795 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16796 } 16797 16798 // Check whether the newly-scanned package wants to define an already-defined perm 16799 int N = pkg.permissions.size(); 16800 for (int i = N-1; i >= 0; i--) { 16801 PackageParser.Permission perm = pkg.permissions.get(i); 16802 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16803 if (bp != null) { 16804 // If the defining package is signed with our cert, it's okay. This 16805 // also includes the "updating the same package" case, of course. 16806 // "updating same package" could also involve key-rotation. 16807 final boolean sigsOk; 16808 if (bp.sourcePackage.equals(pkg.packageName) 16809 && (bp.packageSetting instanceof PackageSetting) 16810 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16811 scanFlags))) { 16812 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16813 } else { 16814 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16815 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16816 } 16817 if (!sigsOk) { 16818 // If the owning package is the system itself, we log but allow 16819 // install to proceed; we fail the install on all other permission 16820 // redefinitions. 16821 if (!bp.sourcePackage.equals("android")) { 16822 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16823 + pkg.packageName + " attempting to redeclare permission " 16824 + perm.info.name + " already owned by " + bp.sourcePackage); 16825 res.origPermission = perm.info.name; 16826 res.origPackage = bp.sourcePackage; 16827 return; 16828 } else { 16829 Slog.w(TAG, "Package " + pkg.packageName 16830 + " attempting to redeclare system permission " 16831 + perm.info.name + "; ignoring new declaration"); 16832 pkg.permissions.remove(i); 16833 } 16834 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16835 // Prevent apps to change protection level to dangerous from any other 16836 // type as this would allow a privilege escalation where an app adds a 16837 // normal/signature permission in other app's group and later redefines 16838 // it as dangerous leading to the group auto-grant. 16839 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16840 == PermissionInfo.PROTECTION_DANGEROUS) { 16841 if (bp != null && !bp.isRuntime()) { 16842 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16843 + "non-runtime permission " + perm.info.name 16844 + " to runtime; keeping old protection level"); 16845 perm.info.protectionLevel = bp.protectionLevel; 16846 } 16847 } 16848 } 16849 } 16850 } 16851 } 16852 16853 if (systemApp) { 16854 if (onExternal) { 16855 // Abort update; system app can't be replaced with app on sdcard 16856 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16857 "Cannot install updates to system apps on sdcard"); 16858 return; 16859 } else if (instantApp) { 16860 // Abort update; system app can't be replaced with an instant app 16861 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16862 "Cannot update a system app with an instant app"); 16863 return; 16864 } 16865 } 16866 16867 if (args.move != null) { 16868 // We did an in-place move, so dex is ready to roll 16869 scanFlags |= SCAN_NO_DEX; 16870 scanFlags |= SCAN_MOVE; 16871 16872 synchronized (mPackages) { 16873 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16874 if (ps == null) { 16875 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16876 "Missing settings for moved package " + pkgName); 16877 } 16878 16879 // We moved the entire application as-is, so bring over the 16880 // previously derived ABI information. 16881 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16882 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16883 } 16884 16885 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16886 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16887 scanFlags |= SCAN_NO_DEX; 16888 16889 try { 16890 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16891 args.abiOverride : pkg.cpuAbiOverride); 16892 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16893 true /*extractLibs*/, mAppLib32InstallDir); 16894 } catch (PackageManagerException pme) { 16895 Slog.e(TAG, "Error deriving application ABI", pme); 16896 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16897 return; 16898 } 16899 16900 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16901 // Do not run PackageDexOptimizer through the local performDexOpt 16902 // method because `pkg` may not be in `mPackages` yet. 16903 // 16904 // Also, don't fail application installs if the dexopt step fails. 16905 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16906 null /* instructionSets */, false /* checkProfiles */, 16907 getCompilerFilterForReason(REASON_INSTALL), 16908 getOrCreateCompilerPackageStats(pkg)); 16909 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16910 16911 // Notify BackgroundDexOptJobService that the package has been changed. 16912 // If this is an update of a package which used to fail to compile, 16913 // BDOS will remove it from its blacklist. 16914 // TODO: Layering violation 16915 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16916 } 16917 16918 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16919 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16920 return; 16921 } 16922 16923 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16924 16925 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16926 "installPackageLI")) { 16927 if (replace) { 16928 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16929 // Static libs have a synthetic package name containing the version 16930 // and cannot be updated as an update would get a new package name, 16931 // unless this is the exact same version code which is useful for 16932 // development. 16933 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16934 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16935 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16936 + "static-shared libs cannot be updated"); 16937 return; 16938 } 16939 } 16940 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16941 installerPackageName, res, args.installReason); 16942 } else { 16943 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16944 args.user, installerPackageName, volumeUuid, res, args.installReason); 16945 } 16946 } 16947 synchronized (mPackages) { 16948 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16949 if (ps != null) { 16950 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16951 } 16952 16953 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16954 for (int i = 0; i < childCount; i++) { 16955 PackageParser.Package childPkg = pkg.childPackages.get(i); 16956 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16957 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16958 if (childPs != null) { 16959 childRes.newUsers = childPs.queryInstalledUsers( 16960 sUserManager.getUserIds(), true); 16961 } 16962 } 16963 16964 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16965 updateSequenceNumberLP(pkgName, res.newUsers); 16966 } 16967 } 16968 } 16969 16970 private void startIntentFilterVerifications(int userId, boolean replacing, 16971 PackageParser.Package pkg) { 16972 if (mIntentFilterVerifierComponent == null) { 16973 Slog.w(TAG, "No IntentFilter verification will not be done as " 16974 + "there is no IntentFilterVerifier available!"); 16975 return; 16976 } 16977 16978 final int verifierUid = getPackageUid( 16979 mIntentFilterVerifierComponent.getPackageName(), 16980 MATCH_DEBUG_TRIAGED_MISSING, 16981 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16982 16983 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16984 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16985 mHandler.sendMessage(msg); 16986 16987 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16988 for (int i = 0; i < childCount; i++) { 16989 PackageParser.Package childPkg = pkg.childPackages.get(i); 16990 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16991 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16992 mHandler.sendMessage(msg); 16993 } 16994 } 16995 16996 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16997 PackageParser.Package pkg) { 16998 int size = pkg.activities.size(); 16999 if (size == 0) { 17000 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17001 "No activity, so no need to verify any IntentFilter!"); 17002 return; 17003 } 17004 17005 final boolean hasDomainURLs = hasDomainURLs(pkg); 17006 if (!hasDomainURLs) { 17007 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17008 "No domain URLs, so no need to verify any IntentFilter!"); 17009 return; 17010 } 17011 17012 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17013 + " if any IntentFilter from the " + size 17014 + " Activities needs verification ..."); 17015 17016 int count = 0; 17017 final String packageName = pkg.packageName; 17018 17019 synchronized (mPackages) { 17020 // If this is a new install and we see that we've already run verification for this 17021 // package, we have nothing to do: it means the state was restored from backup. 17022 if (!replacing) { 17023 IntentFilterVerificationInfo ivi = 17024 mSettings.getIntentFilterVerificationLPr(packageName); 17025 if (ivi != null) { 17026 if (DEBUG_DOMAIN_VERIFICATION) { 17027 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17028 + ivi.getStatusString()); 17029 } 17030 return; 17031 } 17032 } 17033 17034 // If any filters need to be verified, then all need to be. 17035 boolean needToVerify = false; 17036 for (PackageParser.Activity a : pkg.activities) { 17037 for (ActivityIntentInfo filter : a.intents) { 17038 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17039 if (DEBUG_DOMAIN_VERIFICATION) { 17040 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17041 } 17042 needToVerify = true; 17043 break; 17044 } 17045 } 17046 } 17047 17048 if (needToVerify) { 17049 final int verificationId = mIntentFilterVerificationToken++; 17050 for (PackageParser.Activity a : pkg.activities) { 17051 for (ActivityIntentInfo filter : a.intents) { 17052 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17053 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17054 "Verification needed for IntentFilter:" + filter.toString()); 17055 mIntentFilterVerifier.addOneIntentFilterVerification( 17056 verifierUid, userId, verificationId, filter, packageName); 17057 count++; 17058 } 17059 } 17060 } 17061 } 17062 } 17063 17064 if (count > 0) { 17065 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17066 + " IntentFilter verification" + (count > 1 ? "s" : "") 17067 + " for userId:" + userId); 17068 mIntentFilterVerifier.startVerifications(userId); 17069 } else { 17070 if (DEBUG_DOMAIN_VERIFICATION) { 17071 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17072 } 17073 } 17074 } 17075 17076 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17077 final ComponentName cn = filter.activity.getComponentName(); 17078 final String packageName = cn.getPackageName(); 17079 17080 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17081 packageName); 17082 if (ivi == null) { 17083 return true; 17084 } 17085 int status = ivi.getStatus(); 17086 switch (status) { 17087 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17088 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17089 return true; 17090 17091 default: 17092 // Nothing to do 17093 return false; 17094 } 17095 } 17096 17097 private static boolean isMultiArch(ApplicationInfo info) { 17098 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17099 } 17100 17101 private static boolean isExternal(PackageParser.Package pkg) { 17102 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17103 } 17104 17105 private static boolean isExternal(PackageSetting ps) { 17106 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17107 } 17108 17109 private static boolean isSystemApp(PackageParser.Package pkg) { 17110 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17111 } 17112 17113 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17114 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17115 } 17116 17117 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17118 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17119 } 17120 17121 private static boolean isSystemApp(PackageSetting ps) { 17122 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17123 } 17124 17125 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17126 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17127 } 17128 17129 private int packageFlagsToInstallFlags(PackageSetting ps) { 17130 int installFlags = 0; 17131 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17132 // This existing package was an external ASEC install when we have 17133 // the external flag without a UUID 17134 installFlags |= PackageManager.INSTALL_EXTERNAL; 17135 } 17136 if (ps.isForwardLocked()) { 17137 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17138 } 17139 return installFlags; 17140 } 17141 17142 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17143 if (isExternal(pkg)) { 17144 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17145 return StorageManager.UUID_PRIMARY_PHYSICAL; 17146 } else { 17147 return pkg.volumeUuid; 17148 } 17149 } else { 17150 return StorageManager.UUID_PRIVATE_INTERNAL; 17151 } 17152 } 17153 17154 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17155 if (isExternal(pkg)) { 17156 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17157 return mSettings.getExternalVersion(); 17158 } else { 17159 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17160 } 17161 } else { 17162 return mSettings.getInternalVersion(); 17163 } 17164 } 17165 17166 private void deleteTempPackageFiles() { 17167 final FilenameFilter filter = new FilenameFilter() { 17168 public boolean accept(File dir, String name) { 17169 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17170 } 17171 }; 17172 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17173 file.delete(); 17174 } 17175 } 17176 17177 @Override 17178 public void deletePackageAsUser(String packageName, int versionCode, 17179 IPackageDeleteObserver observer, int userId, int flags) { 17180 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17181 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17182 } 17183 17184 @Override 17185 public void deletePackageVersioned(VersionedPackage versionedPackage, 17186 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17187 mContext.enforceCallingOrSelfPermission( 17188 android.Manifest.permission.DELETE_PACKAGES, null); 17189 Preconditions.checkNotNull(versionedPackage); 17190 Preconditions.checkNotNull(observer); 17191 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17192 PackageManager.VERSION_CODE_HIGHEST, 17193 Integer.MAX_VALUE, "versionCode must be >= -1"); 17194 17195 final String packageName = versionedPackage.getPackageName(); 17196 // TODO: We will change version code to long, so in the new API it is long 17197 final int versionCode = (int) versionedPackage.getVersionCode(); 17198 final String internalPackageName; 17199 synchronized (mPackages) { 17200 // Normalize package name to handle renamed packages and static libs 17201 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17202 // TODO: We will change version code to long, so in the new API it is long 17203 (int) versionedPackage.getVersionCode()); 17204 } 17205 17206 final int uid = Binder.getCallingUid(); 17207 if (!isOrphaned(internalPackageName) 17208 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17209 try { 17210 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17211 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17212 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17213 observer.onUserActionRequired(intent); 17214 } catch (RemoteException re) { 17215 } 17216 return; 17217 } 17218 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17219 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17220 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17221 mContext.enforceCallingOrSelfPermission( 17222 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17223 "deletePackage for user " + userId); 17224 } 17225 17226 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17227 try { 17228 observer.onPackageDeleted(packageName, 17229 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17230 } catch (RemoteException re) { 17231 } 17232 return; 17233 } 17234 17235 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17236 try { 17237 observer.onPackageDeleted(packageName, 17238 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17239 } catch (RemoteException re) { 17240 } 17241 return; 17242 } 17243 17244 if (DEBUG_REMOVE) { 17245 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17246 + " deleteAllUsers: " + deleteAllUsers + " version=" 17247 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17248 ? "VERSION_CODE_HIGHEST" : versionCode)); 17249 } 17250 // Queue up an async operation since the package deletion may take a little while. 17251 mHandler.post(new Runnable() { 17252 public void run() { 17253 mHandler.removeCallbacks(this); 17254 int returnCode; 17255 if (!deleteAllUsers) { 17256 returnCode = deletePackageX(internalPackageName, versionCode, 17257 userId, deleteFlags); 17258 } else { 17259 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17260 internalPackageName, users); 17261 // If nobody is blocking uninstall, proceed with delete for all users 17262 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17263 returnCode = deletePackageX(internalPackageName, versionCode, 17264 userId, deleteFlags); 17265 } else { 17266 // Otherwise uninstall individually for users with blockUninstalls=false 17267 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17268 for (int userId : users) { 17269 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17270 returnCode = deletePackageX(internalPackageName, versionCode, 17271 userId, userFlags); 17272 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17273 Slog.w(TAG, "Package delete failed for user " + userId 17274 + ", returnCode " + returnCode); 17275 } 17276 } 17277 } 17278 // The app has only been marked uninstalled for certain users. 17279 // We still need to report that delete was blocked 17280 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17281 } 17282 } 17283 try { 17284 observer.onPackageDeleted(packageName, returnCode, null); 17285 } catch (RemoteException e) { 17286 Log.i(TAG, "Observer no longer exists."); 17287 } //end catch 17288 } //end run 17289 }); 17290 } 17291 17292 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17293 if (pkg.staticSharedLibName != null) { 17294 return pkg.manifestPackageName; 17295 } 17296 return pkg.packageName; 17297 } 17298 17299 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17300 // Handle renamed packages 17301 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17302 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17303 17304 // Is this a static library? 17305 SparseArray<SharedLibraryEntry> versionedLib = 17306 mStaticLibsByDeclaringPackage.get(packageName); 17307 if (versionedLib == null || versionedLib.size() <= 0) { 17308 return packageName; 17309 } 17310 17311 // Figure out which lib versions the caller can see 17312 SparseIntArray versionsCallerCanSee = null; 17313 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17314 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17315 && callingAppId != Process.ROOT_UID) { 17316 versionsCallerCanSee = new SparseIntArray(); 17317 String libName = versionedLib.valueAt(0).info.getName(); 17318 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17319 if (uidPackages != null) { 17320 for (String uidPackage : uidPackages) { 17321 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17322 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17323 if (libIdx >= 0) { 17324 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17325 versionsCallerCanSee.append(libVersion, libVersion); 17326 } 17327 } 17328 } 17329 } 17330 17331 // Caller can see nothing - done 17332 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17333 return packageName; 17334 } 17335 17336 // Find the version the caller can see and the app version code 17337 SharedLibraryEntry highestVersion = null; 17338 final int versionCount = versionedLib.size(); 17339 for (int i = 0; i < versionCount; i++) { 17340 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17341 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17342 libEntry.info.getVersion()) < 0) { 17343 continue; 17344 } 17345 // TODO: We will change version code to long, so in the new API it is long 17346 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17347 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17348 if (libVersionCode == versionCode) { 17349 return libEntry.apk; 17350 } 17351 } else if (highestVersion == null) { 17352 highestVersion = libEntry; 17353 } else if (libVersionCode > highestVersion.info 17354 .getDeclaringPackage().getVersionCode()) { 17355 highestVersion = libEntry; 17356 } 17357 } 17358 17359 if (highestVersion != null) { 17360 return highestVersion.apk; 17361 } 17362 17363 return packageName; 17364 } 17365 17366 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17367 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17368 || callingUid == Process.SYSTEM_UID) { 17369 return true; 17370 } 17371 final int callingUserId = UserHandle.getUserId(callingUid); 17372 // If the caller installed the pkgName, then allow it to silently uninstall. 17373 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17374 return true; 17375 } 17376 17377 // Allow package verifier to silently uninstall. 17378 if (mRequiredVerifierPackage != null && 17379 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17380 return true; 17381 } 17382 17383 // Allow package uninstaller to silently uninstall. 17384 if (mRequiredUninstallerPackage != null && 17385 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17386 return true; 17387 } 17388 17389 // Allow storage manager to silently uninstall. 17390 if (mStorageManagerPackage != null && 17391 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17392 return true; 17393 } 17394 return false; 17395 } 17396 17397 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17398 int[] result = EMPTY_INT_ARRAY; 17399 for (int userId : userIds) { 17400 if (getBlockUninstallForUser(packageName, userId)) { 17401 result = ArrayUtils.appendInt(result, userId); 17402 } 17403 } 17404 return result; 17405 } 17406 17407 @Override 17408 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17409 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17410 } 17411 17412 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17413 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17414 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17415 try { 17416 if (dpm != null) { 17417 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17418 /* callingUserOnly =*/ false); 17419 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17420 : deviceOwnerComponentName.getPackageName(); 17421 // Does the package contains the device owner? 17422 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17423 // this check is probably not needed, since DO should be registered as a device 17424 // admin on some user too. (Original bug for this: b/17657954) 17425 if (packageName.equals(deviceOwnerPackageName)) { 17426 return true; 17427 } 17428 // Does it contain a device admin for any user? 17429 int[] users; 17430 if (userId == UserHandle.USER_ALL) { 17431 users = sUserManager.getUserIds(); 17432 } else { 17433 users = new int[]{userId}; 17434 } 17435 for (int i = 0; i < users.length; ++i) { 17436 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17437 return true; 17438 } 17439 } 17440 } 17441 } catch (RemoteException e) { 17442 } 17443 return false; 17444 } 17445 17446 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17447 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17448 } 17449 17450 /** 17451 * This method is an internal method that could be get invoked either 17452 * to delete an installed package or to clean up a failed installation. 17453 * After deleting an installed package, a broadcast is sent to notify any 17454 * listeners that the package has been removed. For cleaning up a failed 17455 * installation, the broadcast is not necessary since the package's 17456 * installation wouldn't have sent the initial broadcast either 17457 * The key steps in deleting a package are 17458 * deleting the package information in internal structures like mPackages, 17459 * deleting the packages base directories through installd 17460 * updating mSettings to reflect current status 17461 * persisting settings for later use 17462 * sending a broadcast if necessary 17463 */ 17464 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17465 final PackageRemovedInfo info = new PackageRemovedInfo(); 17466 final boolean res; 17467 17468 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17469 ? UserHandle.USER_ALL : userId; 17470 17471 if (isPackageDeviceAdmin(packageName, removeUser)) { 17472 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17473 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17474 } 17475 17476 PackageSetting uninstalledPs = null; 17477 17478 // for the uninstall-updates case and restricted profiles, remember the per- 17479 // user handle installed state 17480 int[] allUsers; 17481 synchronized (mPackages) { 17482 uninstalledPs = mSettings.mPackages.get(packageName); 17483 if (uninstalledPs == null) { 17484 Slog.w(TAG, "Not removing non-existent package " + packageName); 17485 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17486 } 17487 17488 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17489 && uninstalledPs.versionCode != versionCode) { 17490 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17491 + uninstalledPs.versionCode + " != " + versionCode); 17492 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17493 } 17494 17495 // Static shared libs can be declared by any package, so let us not 17496 // allow removing a package if it provides a lib others depend on. 17497 PackageParser.Package pkg = mPackages.get(packageName); 17498 if (pkg != null && pkg.staticSharedLibName != null) { 17499 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17500 pkg.staticSharedLibVersion); 17501 if (libEntry != null) { 17502 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17503 libEntry.info, 0, userId); 17504 if (!ArrayUtils.isEmpty(libClientPackages)) { 17505 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17506 + " hosting lib " + libEntry.info.getName() + " version " 17507 + libEntry.info.getVersion() + " used by " + libClientPackages); 17508 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17509 } 17510 } 17511 } 17512 17513 allUsers = sUserManager.getUserIds(); 17514 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17515 } 17516 17517 final int freezeUser; 17518 if (isUpdatedSystemApp(uninstalledPs) 17519 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17520 // We're downgrading a system app, which will apply to all users, so 17521 // freeze them all during the downgrade 17522 freezeUser = UserHandle.USER_ALL; 17523 } else { 17524 freezeUser = removeUser; 17525 } 17526 17527 synchronized (mInstallLock) { 17528 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17529 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17530 deleteFlags, "deletePackageX")) { 17531 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17532 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17533 } 17534 synchronized (mPackages) { 17535 if (res) { 17536 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17537 info.removedUsers); 17538 updateSequenceNumberLP(packageName, info.removedUsers); 17539 } 17540 } 17541 } 17542 17543 if (res) { 17544 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17545 info.sendPackageRemovedBroadcasts(killApp); 17546 info.sendSystemPackageUpdatedBroadcasts(); 17547 info.sendSystemPackageAppearedBroadcasts(); 17548 } 17549 // Force a gc here. 17550 Runtime.getRuntime().gc(); 17551 // Delete the resources here after sending the broadcast to let 17552 // other processes clean up before deleting resources. 17553 if (info.args != null) { 17554 synchronized (mInstallLock) { 17555 info.args.doPostDeleteLI(true); 17556 } 17557 } 17558 17559 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17560 } 17561 17562 class PackageRemovedInfo { 17563 String removedPackage; 17564 int uid = -1; 17565 int removedAppId = -1; 17566 int[] origUsers; 17567 int[] removedUsers = null; 17568 SparseArray<Integer> installReasons; 17569 boolean isRemovedPackageSystemUpdate = false; 17570 boolean isUpdate; 17571 boolean dataRemoved; 17572 boolean removedForAllUsers; 17573 boolean isStaticSharedLib; 17574 // Clean up resources deleted packages. 17575 InstallArgs args = null; 17576 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17577 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17578 17579 void sendPackageRemovedBroadcasts(boolean killApp) { 17580 sendPackageRemovedBroadcastInternal(killApp); 17581 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17582 for (int i = 0; i < childCount; i++) { 17583 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17584 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17585 } 17586 } 17587 17588 void sendSystemPackageUpdatedBroadcasts() { 17589 if (isRemovedPackageSystemUpdate) { 17590 sendSystemPackageUpdatedBroadcastsInternal(); 17591 final int childCount = (removedChildPackages != null) 17592 ? removedChildPackages.size() : 0; 17593 for (int i = 0; i < childCount; i++) { 17594 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17595 if (childInfo.isRemovedPackageSystemUpdate) { 17596 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17597 } 17598 } 17599 } 17600 } 17601 17602 void sendSystemPackageAppearedBroadcasts() { 17603 final int packageCount = (appearedChildPackages != null) 17604 ? appearedChildPackages.size() : 0; 17605 for (int i = 0; i < packageCount; i++) { 17606 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17607 sendPackageAddedForNewUsers(installedInfo.name, true, 17608 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17609 } 17610 } 17611 17612 private void sendSystemPackageUpdatedBroadcastsInternal() { 17613 Bundle extras = new Bundle(2); 17614 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17615 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17616 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17617 extras, 0, null, null, null); 17618 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17619 extras, 0, null, null, null); 17620 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17621 null, 0, removedPackage, null, null); 17622 } 17623 17624 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17625 // Don't send static shared library removal broadcasts as these 17626 // libs are visible only the the apps that depend on them an one 17627 // cannot remove the library if it has a dependency. 17628 if (isStaticSharedLib) { 17629 return; 17630 } 17631 Bundle extras = new Bundle(2); 17632 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17633 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17634 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17635 if (isUpdate || isRemovedPackageSystemUpdate) { 17636 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17637 } 17638 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17639 if (removedPackage != null) { 17640 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17641 extras, 0, null, null, removedUsers); 17642 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17643 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17644 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17645 null, null, removedUsers); 17646 } 17647 } 17648 if (removedAppId >= 0) { 17649 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17650 removedUsers); 17651 } 17652 } 17653 } 17654 17655 /* 17656 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17657 * flag is not set, the data directory is removed as well. 17658 * make sure this flag is set for partially installed apps. If not its meaningless to 17659 * delete a partially installed application. 17660 */ 17661 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17662 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17663 String packageName = ps.name; 17664 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17665 // Retrieve object to delete permissions for shared user later on 17666 final PackageParser.Package deletedPkg; 17667 final PackageSetting deletedPs; 17668 // reader 17669 synchronized (mPackages) { 17670 deletedPkg = mPackages.get(packageName); 17671 deletedPs = mSettings.mPackages.get(packageName); 17672 if (outInfo != null) { 17673 outInfo.removedPackage = packageName; 17674 outInfo.isStaticSharedLib = deletedPkg != null 17675 && deletedPkg.staticSharedLibName != null; 17676 outInfo.removedUsers = deletedPs != null 17677 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17678 : null; 17679 } 17680 } 17681 17682 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17683 17684 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17685 final PackageParser.Package resolvedPkg; 17686 if (deletedPkg != null) { 17687 resolvedPkg = deletedPkg; 17688 } else { 17689 // We don't have a parsed package when it lives on an ejected 17690 // adopted storage device, so fake something together 17691 resolvedPkg = new PackageParser.Package(ps.name); 17692 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17693 } 17694 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17695 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17696 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17697 if (outInfo != null) { 17698 outInfo.dataRemoved = true; 17699 } 17700 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17701 } 17702 17703 int removedAppId = -1; 17704 17705 // writer 17706 synchronized (mPackages) { 17707 boolean installedStateChanged = false; 17708 if (deletedPs != null) { 17709 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17710 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17711 clearDefaultBrowserIfNeeded(packageName); 17712 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17713 removedAppId = mSettings.removePackageLPw(packageName); 17714 if (outInfo != null) { 17715 outInfo.removedAppId = removedAppId; 17716 } 17717 updatePermissionsLPw(deletedPs.name, null, 0); 17718 if (deletedPs.sharedUser != null) { 17719 // Remove permissions associated with package. Since runtime 17720 // permissions are per user we have to kill the removed package 17721 // or packages running under the shared user of the removed 17722 // package if revoking the permissions requested only by the removed 17723 // package is successful and this causes a change in gids. 17724 for (int userId : UserManagerService.getInstance().getUserIds()) { 17725 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17726 userId); 17727 if (userIdToKill == UserHandle.USER_ALL 17728 || userIdToKill >= UserHandle.USER_SYSTEM) { 17729 // If gids changed for this user, kill all affected packages. 17730 mHandler.post(new Runnable() { 17731 @Override 17732 public void run() { 17733 // This has to happen with no lock held. 17734 killApplication(deletedPs.name, deletedPs.appId, 17735 KILL_APP_REASON_GIDS_CHANGED); 17736 } 17737 }); 17738 break; 17739 } 17740 } 17741 } 17742 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17743 } 17744 // make sure to preserve per-user disabled state if this removal was just 17745 // a downgrade of a system app to the factory package 17746 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17747 if (DEBUG_REMOVE) { 17748 Slog.d(TAG, "Propagating install state across downgrade"); 17749 } 17750 for (int userId : allUserHandles) { 17751 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17752 if (DEBUG_REMOVE) { 17753 Slog.d(TAG, " user " + userId + " => " + installed); 17754 } 17755 if (installed != ps.getInstalled(userId)) { 17756 installedStateChanged = true; 17757 } 17758 ps.setInstalled(installed, userId); 17759 } 17760 } 17761 } 17762 // can downgrade to reader 17763 if (writeSettings) { 17764 // Save settings now 17765 mSettings.writeLPr(); 17766 } 17767 if (installedStateChanged) { 17768 mSettings.writeKernelMappingLPr(ps); 17769 } 17770 } 17771 if (removedAppId != -1) { 17772 // A user ID was deleted here. Go through all users and remove it 17773 // from KeyStore. 17774 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17775 } 17776 } 17777 17778 static boolean locationIsPrivileged(File path) { 17779 try { 17780 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17781 .getCanonicalPath(); 17782 return path.getCanonicalPath().startsWith(privilegedAppDir); 17783 } catch (IOException e) { 17784 Slog.e(TAG, "Unable to access code path " + path); 17785 } 17786 return false; 17787 } 17788 17789 /* 17790 * Tries to delete system package. 17791 */ 17792 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17793 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17794 boolean writeSettings) { 17795 if (deletedPs.parentPackageName != null) { 17796 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17797 return false; 17798 } 17799 17800 final boolean applyUserRestrictions 17801 = (allUserHandles != null) && (outInfo.origUsers != null); 17802 final PackageSetting disabledPs; 17803 // Confirm if the system package has been updated 17804 // An updated system app can be deleted. This will also have to restore 17805 // the system pkg from system partition 17806 // reader 17807 synchronized (mPackages) { 17808 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17809 } 17810 17811 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17812 + " disabledPs=" + disabledPs); 17813 17814 if (disabledPs == null) { 17815 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17816 return false; 17817 } else if (DEBUG_REMOVE) { 17818 Slog.d(TAG, "Deleting system pkg from data partition"); 17819 } 17820 17821 if (DEBUG_REMOVE) { 17822 if (applyUserRestrictions) { 17823 Slog.d(TAG, "Remembering install states:"); 17824 for (int userId : allUserHandles) { 17825 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17826 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17827 } 17828 } 17829 } 17830 17831 // Delete the updated package 17832 outInfo.isRemovedPackageSystemUpdate = true; 17833 if (outInfo.removedChildPackages != null) { 17834 final int childCount = (deletedPs.childPackageNames != null) 17835 ? deletedPs.childPackageNames.size() : 0; 17836 for (int i = 0; i < childCount; i++) { 17837 String childPackageName = deletedPs.childPackageNames.get(i); 17838 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17839 .contains(childPackageName)) { 17840 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17841 childPackageName); 17842 if (childInfo != null) { 17843 childInfo.isRemovedPackageSystemUpdate = true; 17844 } 17845 } 17846 } 17847 } 17848 17849 if (disabledPs.versionCode < deletedPs.versionCode) { 17850 // Delete data for downgrades 17851 flags &= ~PackageManager.DELETE_KEEP_DATA; 17852 } else { 17853 // Preserve data by setting flag 17854 flags |= PackageManager.DELETE_KEEP_DATA; 17855 } 17856 17857 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17858 outInfo, writeSettings, disabledPs.pkg); 17859 if (!ret) { 17860 return false; 17861 } 17862 17863 // writer 17864 synchronized (mPackages) { 17865 // Reinstate the old system package 17866 enableSystemPackageLPw(disabledPs.pkg); 17867 // Remove any native libraries from the upgraded package. 17868 removeNativeBinariesLI(deletedPs); 17869 } 17870 17871 // Install the system package 17872 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17873 int parseFlags = mDefParseFlags 17874 | PackageParser.PARSE_MUST_BE_APK 17875 | PackageParser.PARSE_IS_SYSTEM 17876 | PackageParser.PARSE_IS_SYSTEM_DIR; 17877 if (locationIsPrivileged(disabledPs.codePath)) { 17878 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17879 } 17880 17881 final PackageParser.Package newPkg; 17882 try { 17883 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17884 0 /* currentTime */, null); 17885 } catch (PackageManagerException e) { 17886 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17887 + e.getMessage()); 17888 return false; 17889 } 17890 17891 try { 17892 // update shared libraries for the newly re-installed system package 17893 updateSharedLibrariesLPr(newPkg, null); 17894 } catch (PackageManagerException e) { 17895 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17896 } 17897 17898 prepareAppDataAfterInstallLIF(newPkg); 17899 17900 // writer 17901 synchronized (mPackages) { 17902 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17903 17904 // Propagate the permissions state as we do not want to drop on the floor 17905 // runtime permissions. The update permissions method below will take 17906 // care of removing obsolete permissions and grant install permissions. 17907 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17908 updatePermissionsLPw(newPkg.packageName, newPkg, 17909 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17910 17911 if (applyUserRestrictions) { 17912 boolean installedStateChanged = false; 17913 if (DEBUG_REMOVE) { 17914 Slog.d(TAG, "Propagating install state across reinstall"); 17915 } 17916 for (int userId : allUserHandles) { 17917 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17918 if (DEBUG_REMOVE) { 17919 Slog.d(TAG, " user " + userId + " => " + installed); 17920 } 17921 if (installed != ps.getInstalled(userId)) { 17922 installedStateChanged = true; 17923 } 17924 ps.setInstalled(installed, userId); 17925 17926 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17927 } 17928 // Regardless of writeSettings we need to ensure that this restriction 17929 // state propagation is persisted 17930 mSettings.writeAllUsersPackageRestrictionsLPr(); 17931 if (installedStateChanged) { 17932 mSettings.writeKernelMappingLPr(ps); 17933 } 17934 } 17935 // can downgrade to reader here 17936 if (writeSettings) { 17937 mSettings.writeLPr(); 17938 } 17939 } 17940 return true; 17941 } 17942 17943 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17944 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17945 PackageRemovedInfo outInfo, boolean writeSettings, 17946 PackageParser.Package replacingPackage) { 17947 synchronized (mPackages) { 17948 if (outInfo != null) { 17949 outInfo.uid = ps.appId; 17950 } 17951 17952 if (outInfo != null && outInfo.removedChildPackages != null) { 17953 final int childCount = (ps.childPackageNames != null) 17954 ? ps.childPackageNames.size() : 0; 17955 for (int i = 0; i < childCount; i++) { 17956 String childPackageName = ps.childPackageNames.get(i); 17957 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17958 if (childPs == null) { 17959 return false; 17960 } 17961 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17962 childPackageName); 17963 if (childInfo != null) { 17964 childInfo.uid = childPs.appId; 17965 } 17966 } 17967 } 17968 } 17969 17970 // Delete package data from internal structures and also remove data if flag is set 17971 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17972 17973 // Delete the child packages data 17974 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17975 for (int i = 0; i < childCount; i++) { 17976 PackageSetting childPs; 17977 synchronized (mPackages) { 17978 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17979 } 17980 if (childPs != null) { 17981 PackageRemovedInfo childOutInfo = (outInfo != null 17982 && outInfo.removedChildPackages != null) 17983 ? outInfo.removedChildPackages.get(childPs.name) : null; 17984 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17985 && (replacingPackage != null 17986 && !replacingPackage.hasChildPackage(childPs.name)) 17987 ? flags & ~DELETE_KEEP_DATA : flags; 17988 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17989 deleteFlags, writeSettings); 17990 } 17991 } 17992 17993 // Delete application code and resources only for parent packages 17994 if (ps.parentPackageName == null) { 17995 if (deleteCodeAndResources && (outInfo != null)) { 17996 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17997 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17998 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17999 } 18000 } 18001 18002 return true; 18003 } 18004 18005 @Override 18006 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18007 int userId) { 18008 mContext.enforceCallingOrSelfPermission( 18009 android.Manifest.permission.DELETE_PACKAGES, null); 18010 synchronized (mPackages) { 18011 PackageSetting ps = mSettings.mPackages.get(packageName); 18012 if (ps == null) { 18013 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18014 return false; 18015 } 18016 // Cannot block uninstall of static shared libs as they are 18017 // considered a part of the using app (emulating static linking). 18018 // Also static libs are installed always on internal storage. 18019 PackageParser.Package pkg = mPackages.get(packageName); 18020 if (pkg != null && pkg.staticSharedLibName != null) { 18021 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18022 + " providing static shared library: " + pkg.staticSharedLibName); 18023 return false; 18024 } 18025 if (!ps.getInstalled(userId)) { 18026 // Can't block uninstall for an app that is not installed or enabled. 18027 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18028 return false; 18029 } 18030 ps.setBlockUninstall(blockUninstall, userId); 18031 mSettings.writePackageRestrictionsLPr(userId); 18032 } 18033 return true; 18034 } 18035 18036 @Override 18037 public boolean getBlockUninstallForUser(String packageName, int userId) { 18038 synchronized (mPackages) { 18039 PackageSetting ps = mSettings.mPackages.get(packageName); 18040 if (ps == null) { 18041 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18042 return false; 18043 } 18044 return ps.getBlockUninstall(userId); 18045 } 18046 } 18047 18048 @Override 18049 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18050 int callingUid = Binder.getCallingUid(); 18051 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18052 throw new SecurityException( 18053 "setRequiredForSystemUser can only be run by the system or root"); 18054 } 18055 synchronized (mPackages) { 18056 PackageSetting ps = mSettings.mPackages.get(packageName); 18057 if (ps == null) { 18058 Log.w(TAG, "Package doesn't exist: " + packageName); 18059 return false; 18060 } 18061 if (systemUserApp) { 18062 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18063 } else { 18064 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18065 } 18066 mSettings.writeLPr(); 18067 } 18068 return true; 18069 } 18070 18071 /* 18072 * This method handles package deletion in general 18073 */ 18074 private boolean deletePackageLIF(String packageName, UserHandle user, 18075 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18076 PackageRemovedInfo outInfo, boolean writeSettings, 18077 PackageParser.Package replacingPackage) { 18078 if (packageName == null) { 18079 Slog.w(TAG, "Attempt to delete null packageName."); 18080 return false; 18081 } 18082 18083 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18084 18085 PackageSetting ps; 18086 synchronized (mPackages) { 18087 ps = mSettings.mPackages.get(packageName); 18088 if (ps == null) { 18089 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18090 return false; 18091 } 18092 18093 if (ps.parentPackageName != null && (!isSystemApp(ps) 18094 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18095 if (DEBUG_REMOVE) { 18096 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18097 + ((user == null) ? UserHandle.USER_ALL : user)); 18098 } 18099 final int removedUserId = (user != null) ? user.getIdentifier() 18100 : UserHandle.USER_ALL; 18101 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18102 return false; 18103 } 18104 markPackageUninstalledForUserLPw(ps, user); 18105 scheduleWritePackageRestrictionsLocked(user); 18106 return true; 18107 } 18108 } 18109 18110 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18111 && user.getIdentifier() != UserHandle.USER_ALL)) { 18112 // The caller is asking that the package only be deleted for a single 18113 // user. To do this, we just mark its uninstalled state and delete 18114 // its data. If this is a system app, we only allow this to happen if 18115 // they have set the special DELETE_SYSTEM_APP which requests different 18116 // semantics than normal for uninstalling system apps. 18117 markPackageUninstalledForUserLPw(ps, user); 18118 18119 if (!isSystemApp(ps)) { 18120 // Do not uninstall the APK if an app should be cached 18121 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18122 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18123 // Other user still have this package installed, so all 18124 // we need to do is clear this user's data and save that 18125 // it is uninstalled. 18126 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18127 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18128 return false; 18129 } 18130 scheduleWritePackageRestrictionsLocked(user); 18131 return true; 18132 } else { 18133 // We need to set it back to 'installed' so the uninstall 18134 // broadcasts will be sent correctly. 18135 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18136 ps.setInstalled(true, user.getIdentifier()); 18137 mSettings.writeKernelMappingLPr(ps); 18138 } 18139 } else { 18140 // This is a system app, so we assume that the 18141 // other users still have this package installed, so all 18142 // we need to do is clear this user's data and save that 18143 // it is uninstalled. 18144 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18145 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18146 return false; 18147 } 18148 scheduleWritePackageRestrictionsLocked(user); 18149 return true; 18150 } 18151 } 18152 18153 // If we are deleting a composite package for all users, keep track 18154 // of result for each child. 18155 if (ps.childPackageNames != null && outInfo != null) { 18156 synchronized (mPackages) { 18157 final int childCount = ps.childPackageNames.size(); 18158 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18159 for (int i = 0; i < childCount; i++) { 18160 String childPackageName = ps.childPackageNames.get(i); 18161 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18162 childInfo.removedPackage = childPackageName; 18163 outInfo.removedChildPackages.put(childPackageName, childInfo); 18164 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18165 if (childPs != null) { 18166 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18167 } 18168 } 18169 } 18170 } 18171 18172 boolean ret = false; 18173 if (isSystemApp(ps)) { 18174 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18175 // When an updated system application is deleted we delete the existing resources 18176 // as well and fall back to existing code in system partition 18177 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18178 } else { 18179 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18180 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18181 outInfo, writeSettings, replacingPackage); 18182 } 18183 18184 // Take a note whether we deleted the package for all users 18185 if (outInfo != null) { 18186 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18187 if (outInfo.removedChildPackages != null) { 18188 synchronized (mPackages) { 18189 final int childCount = outInfo.removedChildPackages.size(); 18190 for (int i = 0; i < childCount; i++) { 18191 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18192 if (childInfo != null) { 18193 childInfo.removedForAllUsers = mPackages.get( 18194 childInfo.removedPackage) == null; 18195 } 18196 } 18197 } 18198 } 18199 // If we uninstalled an update to a system app there may be some 18200 // child packages that appeared as they are declared in the system 18201 // app but were not declared in the update. 18202 if (isSystemApp(ps)) { 18203 synchronized (mPackages) { 18204 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18205 final int childCount = (updatedPs.childPackageNames != null) 18206 ? updatedPs.childPackageNames.size() : 0; 18207 for (int i = 0; i < childCount; i++) { 18208 String childPackageName = updatedPs.childPackageNames.get(i); 18209 if (outInfo.removedChildPackages == null 18210 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18211 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18212 if (childPs == null) { 18213 continue; 18214 } 18215 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18216 installRes.name = childPackageName; 18217 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18218 installRes.pkg = mPackages.get(childPackageName); 18219 installRes.uid = childPs.pkg.applicationInfo.uid; 18220 if (outInfo.appearedChildPackages == null) { 18221 outInfo.appearedChildPackages = new ArrayMap<>(); 18222 } 18223 outInfo.appearedChildPackages.put(childPackageName, installRes); 18224 } 18225 } 18226 } 18227 } 18228 } 18229 18230 return ret; 18231 } 18232 18233 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18234 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18235 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18236 for (int nextUserId : userIds) { 18237 if (DEBUG_REMOVE) { 18238 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18239 } 18240 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18241 false /*installed*/, 18242 true /*stopped*/, 18243 true /*notLaunched*/, 18244 false /*hidden*/, 18245 false /*suspended*/, 18246 false /*instantApp*/, 18247 null /*lastDisableAppCaller*/, 18248 null /*enabledComponents*/, 18249 null /*disabledComponents*/, 18250 false /*blockUninstall*/, 18251 ps.readUserState(nextUserId).domainVerificationStatus, 18252 0, PackageManager.INSTALL_REASON_UNKNOWN); 18253 } 18254 mSettings.writeKernelMappingLPr(ps); 18255 } 18256 18257 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18258 PackageRemovedInfo outInfo) { 18259 final PackageParser.Package pkg; 18260 synchronized (mPackages) { 18261 pkg = mPackages.get(ps.name); 18262 } 18263 18264 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18265 : new int[] {userId}; 18266 for (int nextUserId : userIds) { 18267 if (DEBUG_REMOVE) { 18268 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18269 + nextUserId); 18270 } 18271 18272 destroyAppDataLIF(pkg, userId, 18273 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18274 destroyAppProfilesLIF(pkg, userId); 18275 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18276 schedulePackageCleaning(ps.name, nextUserId, false); 18277 synchronized (mPackages) { 18278 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18279 scheduleWritePackageRestrictionsLocked(nextUserId); 18280 } 18281 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18282 } 18283 } 18284 18285 if (outInfo != null) { 18286 outInfo.removedPackage = ps.name; 18287 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18288 outInfo.removedAppId = ps.appId; 18289 outInfo.removedUsers = userIds; 18290 } 18291 18292 return true; 18293 } 18294 18295 private final class ClearStorageConnection implements ServiceConnection { 18296 IMediaContainerService mContainerService; 18297 18298 @Override 18299 public void onServiceConnected(ComponentName name, IBinder service) { 18300 synchronized (this) { 18301 mContainerService = IMediaContainerService.Stub 18302 .asInterface(Binder.allowBlocking(service)); 18303 notifyAll(); 18304 } 18305 } 18306 18307 @Override 18308 public void onServiceDisconnected(ComponentName name) { 18309 } 18310 } 18311 18312 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18313 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18314 18315 final boolean mounted; 18316 if (Environment.isExternalStorageEmulated()) { 18317 mounted = true; 18318 } else { 18319 final String status = Environment.getExternalStorageState(); 18320 18321 mounted = status.equals(Environment.MEDIA_MOUNTED) 18322 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18323 } 18324 18325 if (!mounted) { 18326 return; 18327 } 18328 18329 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18330 int[] users; 18331 if (userId == UserHandle.USER_ALL) { 18332 users = sUserManager.getUserIds(); 18333 } else { 18334 users = new int[] { userId }; 18335 } 18336 final ClearStorageConnection conn = new ClearStorageConnection(); 18337 if (mContext.bindServiceAsUser( 18338 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18339 try { 18340 for (int curUser : users) { 18341 long timeout = SystemClock.uptimeMillis() + 5000; 18342 synchronized (conn) { 18343 long now; 18344 while (conn.mContainerService == null && 18345 (now = SystemClock.uptimeMillis()) < timeout) { 18346 try { 18347 conn.wait(timeout - now); 18348 } catch (InterruptedException e) { 18349 } 18350 } 18351 } 18352 if (conn.mContainerService == null) { 18353 return; 18354 } 18355 18356 final UserEnvironment userEnv = new UserEnvironment(curUser); 18357 clearDirectory(conn.mContainerService, 18358 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18359 if (allData) { 18360 clearDirectory(conn.mContainerService, 18361 userEnv.buildExternalStorageAppDataDirs(packageName)); 18362 clearDirectory(conn.mContainerService, 18363 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18364 } 18365 } 18366 } finally { 18367 mContext.unbindService(conn); 18368 } 18369 } 18370 } 18371 18372 @Override 18373 public void clearApplicationProfileData(String packageName) { 18374 enforceSystemOrRoot("Only the system can clear all profile data"); 18375 18376 final PackageParser.Package pkg; 18377 synchronized (mPackages) { 18378 pkg = mPackages.get(packageName); 18379 } 18380 18381 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18382 synchronized (mInstallLock) { 18383 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18384 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18385 true /* removeBaseMarker */); 18386 } 18387 } 18388 } 18389 18390 @Override 18391 public void clearApplicationUserData(final String packageName, 18392 final IPackageDataObserver observer, final int userId) { 18393 mContext.enforceCallingOrSelfPermission( 18394 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18395 18396 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18397 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18398 18399 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18400 throw new SecurityException("Cannot clear data for a protected package: " 18401 + packageName); 18402 } 18403 // Queue up an async operation since the package deletion may take a little while. 18404 mHandler.post(new Runnable() { 18405 public void run() { 18406 mHandler.removeCallbacks(this); 18407 final boolean succeeded; 18408 try (PackageFreezer freezer = freezePackage(packageName, 18409 "clearApplicationUserData")) { 18410 synchronized (mInstallLock) { 18411 succeeded = clearApplicationUserDataLIF(packageName, userId); 18412 } 18413 clearExternalStorageDataSync(packageName, userId, true); 18414 synchronized (mPackages) { 18415 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18416 packageName, userId); 18417 } 18418 } 18419 if (succeeded) { 18420 // invoke DeviceStorageMonitor's update method to clear any notifications 18421 DeviceStorageMonitorInternal dsm = LocalServices 18422 .getService(DeviceStorageMonitorInternal.class); 18423 if (dsm != null) { 18424 dsm.checkMemory(); 18425 } 18426 } 18427 if(observer != null) { 18428 try { 18429 observer.onRemoveCompleted(packageName, succeeded); 18430 } catch (RemoteException e) { 18431 Log.i(TAG, "Observer no longer exists."); 18432 } 18433 } //end if observer 18434 } //end run 18435 }); 18436 } 18437 18438 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18439 if (packageName == null) { 18440 Slog.w(TAG, "Attempt to delete null packageName."); 18441 return false; 18442 } 18443 18444 // Try finding details about the requested package 18445 PackageParser.Package pkg; 18446 synchronized (mPackages) { 18447 pkg = mPackages.get(packageName); 18448 if (pkg == null) { 18449 final PackageSetting ps = mSettings.mPackages.get(packageName); 18450 if (ps != null) { 18451 pkg = ps.pkg; 18452 } 18453 } 18454 18455 if (pkg == null) { 18456 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18457 return false; 18458 } 18459 18460 PackageSetting ps = (PackageSetting) pkg.mExtras; 18461 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18462 } 18463 18464 clearAppDataLIF(pkg, userId, 18465 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18466 18467 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18468 removeKeystoreDataIfNeeded(userId, appId); 18469 18470 UserManagerInternal umInternal = getUserManagerInternal(); 18471 final int flags; 18472 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18473 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18474 } else if (umInternal.isUserRunning(userId)) { 18475 flags = StorageManager.FLAG_STORAGE_DE; 18476 } else { 18477 flags = 0; 18478 } 18479 prepareAppDataContentsLIF(pkg, userId, flags); 18480 18481 return true; 18482 } 18483 18484 /** 18485 * Reverts user permission state changes (permissions and flags) in 18486 * all packages for a given user. 18487 * 18488 * @param userId The device user for which to do a reset. 18489 */ 18490 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18491 final int packageCount = mPackages.size(); 18492 for (int i = 0; i < packageCount; i++) { 18493 PackageParser.Package pkg = mPackages.valueAt(i); 18494 PackageSetting ps = (PackageSetting) pkg.mExtras; 18495 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18496 } 18497 } 18498 18499 private void resetNetworkPolicies(int userId) { 18500 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18501 } 18502 18503 /** 18504 * Reverts user permission state changes (permissions and flags). 18505 * 18506 * @param ps The package for which to reset. 18507 * @param userId The device user for which to do a reset. 18508 */ 18509 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18510 final PackageSetting ps, final int userId) { 18511 if (ps.pkg == null) { 18512 return; 18513 } 18514 18515 // These are flags that can change base on user actions. 18516 final int userSettableMask = FLAG_PERMISSION_USER_SET 18517 | FLAG_PERMISSION_USER_FIXED 18518 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18519 | FLAG_PERMISSION_REVIEW_REQUIRED; 18520 18521 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18522 | FLAG_PERMISSION_POLICY_FIXED; 18523 18524 boolean writeInstallPermissions = false; 18525 boolean writeRuntimePermissions = false; 18526 18527 final int permissionCount = ps.pkg.requestedPermissions.size(); 18528 for (int i = 0; i < permissionCount; i++) { 18529 String permission = ps.pkg.requestedPermissions.get(i); 18530 18531 BasePermission bp = mSettings.mPermissions.get(permission); 18532 if (bp == null) { 18533 continue; 18534 } 18535 18536 // If shared user we just reset the state to which only this app contributed. 18537 if (ps.sharedUser != null) { 18538 boolean used = false; 18539 final int packageCount = ps.sharedUser.packages.size(); 18540 for (int j = 0; j < packageCount; j++) { 18541 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18542 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18543 && pkg.pkg.requestedPermissions.contains(permission)) { 18544 used = true; 18545 break; 18546 } 18547 } 18548 if (used) { 18549 continue; 18550 } 18551 } 18552 18553 PermissionsState permissionsState = ps.getPermissionsState(); 18554 18555 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18556 18557 // Always clear the user settable flags. 18558 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18559 bp.name) != null; 18560 // If permission review is enabled and this is a legacy app, mark the 18561 // permission as requiring a review as this is the initial state. 18562 int flags = 0; 18563 if (mPermissionReviewRequired 18564 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18565 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18566 } 18567 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18568 if (hasInstallState) { 18569 writeInstallPermissions = true; 18570 } else { 18571 writeRuntimePermissions = true; 18572 } 18573 } 18574 18575 // Below is only runtime permission handling. 18576 if (!bp.isRuntime()) { 18577 continue; 18578 } 18579 18580 // Never clobber system or policy. 18581 if ((oldFlags & policyOrSystemFlags) != 0) { 18582 continue; 18583 } 18584 18585 // If this permission was granted by default, make sure it is. 18586 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18587 if (permissionsState.grantRuntimePermission(bp, userId) 18588 != PERMISSION_OPERATION_FAILURE) { 18589 writeRuntimePermissions = true; 18590 } 18591 // If permission review is enabled the permissions for a legacy apps 18592 // are represented as constantly granted runtime ones, so don't revoke. 18593 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18594 // Otherwise, reset the permission. 18595 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18596 switch (revokeResult) { 18597 case PERMISSION_OPERATION_SUCCESS: 18598 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18599 writeRuntimePermissions = true; 18600 final int appId = ps.appId; 18601 mHandler.post(new Runnable() { 18602 @Override 18603 public void run() { 18604 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18605 } 18606 }); 18607 } break; 18608 } 18609 } 18610 } 18611 18612 // Synchronously write as we are taking permissions away. 18613 if (writeRuntimePermissions) { 18614 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18615 } 18616 18617 // Synchronously write as we are taking permissions away. 18618 if (writeInstallPermissions) { 18619 mSettings.writeLPr(); 18620 } 18621 } 18622 18623 /** 18624 * Remove entries from the keystore daemon. Will only remove it if the 18625 * {@code appId} is valid. 18626 */ 18627 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18628 if (appId < 0) { 18629 return; 18630 } 18631 18632 final KeyStore keyStore = KeyStore.getInstance(); 18633 if (keyStore != null) { 18634 if (userId == UserHandle.USER_ALL) { 18635 for (final int individual : sUserManager.getUserIds()) { 18636 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18637 } 18638 } else { 18639 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18640 } 18641 } else { 18642 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18643 } 18644 } 18645 18646 @Override 18647 public void deleteApplicationCacheFiles(final String packageName, 18648 final IPackageDataObserver observer) { 18649 final int userId = UserHandle.getCallingUserId(); 18650 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18651 } 18652 18653 @Override 18654 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18655 final IPackageDataObserver observer) { 18656 mContext.enforceCallingOrSelfPermission( 18657 android.Manifest.permission.DELETE_CACHE_FILES, null); 18658 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18659 /* requireFullPermission= */ true, /* checkShell= */ false, 18660 "delete application cache files"); 18661 18662 final PackageParser.Package pkg; 18663 synchronized (mPackages) { 18664 pkg = mPackages.get(packageName); 18665 } 18666 18667 // Queue up an async operation since the package deletion may take a little while. 18668 mHandler.post(new Runnable() { 18669 public void run() { 18670 synchronized (mInstallLock) { 18671 final int flags = StorageManager.FLAG_STORAGE_DE 18672 | StorageManager.FLAG_STORAGE_CE; 18673 // We're only clearing cache files, so we don't care if the 18674 // app is unfrozen and still able to run 18675 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18676 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18677 } 18678 clearExternalStorageDataSync(packageName, userId, false); 18679 if (observer != null) { 18680 try { 18681 observer.onRemoveCompleted(packageName, true); 18682 } catch (RemoteException e) { 18683 Log.i(TAG, "Observer no longer exists."); 18684 } 18685 } 18686 } 18687 }); 18688 } 18689 18690 @Override 18691 public void getPackageSizeInfo(final String packageName, int userHandle, 18692 final IPackageStatsObserver observer) { 18693 mContext.enforceCallingOrSelfPermission( 18694 android.Manifest.permission.GET_PACKAGE_SIZE, null); 18695 if (packageName == null) { 18696 throw new IllegalArgumentException("Attempt to get size of null packageName"); 18697 } 18698 18699 PackageStats stats = new PackageStats(packageName, userHandle); 18700 18701 /* 18702 * Queue up an async operation since the package measurement may take a 18703 * little while. 18704 */ 18705 Message msg = mHandler.obtainMessage(INIT_COPY); 18706 msg.obj = new MeasureParams(stats, observer); 18707 mHandler.sendMessage(msg); 18708 } 18709 18710 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18711 final PackageSetting ps; 18712 synchronized (mPackages) { 18713 ps = mSettings.mPackages.get(packageName); 18714 if (ps == null) { 18715 Slog.w(TAG, "Failed to find settings for " + packageName); 18716 return false; 18717 } 18718 } 18719 18720 final String[] packageNames = { packageName }; 18721 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18722 final String[] codePaths = { ps.codePathString }; 18723 18724 try { 18725 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18726 ps.appId, ceDataInodes, codePaths, stats); 18727 18728 // For now, ignore code size of packages on system partition 18729 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18730 stats.codeSize = 0; 18731 } 18732 18733 // External clients expect these to be tracked separately 18734 stats.dataSize -= stats.cacheSize; 18735 18736 } catch (InstallerException e) { 18737 Slog.w(TAG, String.valueOf(e)); 18738 return false; 18739 } 18740 18741 return true; 18742 } 18743 18744 private int getUidTargetSdkVersionLockedLPr(int uid) { 18745 Object obj = mSettings.getUserIdLPr(uid); 18746 if (obj instanceof SharedUserSetting) { 18747 final SharedUserSetting sus = (SharedUserSetting) obj; 18748 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18749 final Iterator<PackageSetting> it = sus.packages.iterator(); 18750 while (it.hasNext()) { 18751 final PackageSetting ps = it.next(); 18752 if (ps.pkg != null) { 18753 int v = ps.pkg.applicationInfo.targetSdkVersion; 18754 if (v < vers) vers = v; 18755 } 18756 } 18757 return vers; 18758 } else if (obj instanceof PackageSetting) { 18759 final PackageSetting ps = (PackageSetting) obj; 18760 if (ps.pkg != null) { 18761 return ps.pkg.applicationInfo.targetSdkVersion; 18762 } 18763 } 18764 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18765 } 18766 18767 @Override 18768 public void addPreferredActivity(IntentFilter filter, int match, 18769 ComponentName[] set, ComponentName activity, int userId) { 18770 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18771 "Adding preferred"); 18772 } 18773 18774 private void addPreferredActivityInternal(IntentFilter filter, int match, 18775 ComponentName[] set, ComponentName activity, boolean always, int userId, 18776 String opname) { 18777 // writer 18778 int callingUid = Binder.getCallingUid(); 18779 enforceCrossUserPermission(callingUid, userId, 18780 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18781 if (filter.countActions() == 0) { 18782 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18783 return; 18784 } 18785 synchronized (mPackages) { 18786 if (mContext.checkCallingOrSelfPermission( 18787 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18788 != PackageManager.PERMISSION_GRANTED) { 18789 if (getUidTargetSdkVersionLockedLPr(callingUid) 18790 < Build.VERSION_CODES.FROYO) { 18791 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18792 + callingUid); 18793 return; 18794 } 18795 mContext.enforceCallingOrSelfPermission( 18796 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18797 } 18798 18799 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18800 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18801 + userId + ":"); 18802 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18803 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18804 scheduleWritePackageRestrictionsLocked(userId); 18805 postPreferredActivityChangedBroadcast(userId); 18806 } 18807 } 18808 18809 private void postPreferredActivityChangedBroadcast(int userId) { 18810 mHandler.post(() -> { 18811 final IActivityManager am = ActivityManager.getService(); 18812 if (am == null) { 18813 return; 18814 } 18815 18816 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18817 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18818 try { 18819 am.broadcastIntent(null, intent, null, null, 18820 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18821 null, false, false, userId); 18822 } catch (RemoteException e) { 18823 } 18824 }); 18825 } 18826 18827 @Override 18828 public void replacePreferredActivity(IntentFilter filter, int match, 18829 ComponentName[] set, ComponentName activity, int userId) { 18830 if (filter.countActions() != 1) { 18831 throw new IllegalArgumentException( 18832 "replacePreferredActivity expects filter to have only 1 action."); 18833 } 18834 if (filter.countDataAuthorities() != 0 18835 || filter.countDataPaths() != 0 18836 || filter.countDataSchemes() > 1 18837 || filter.countDataTypes() != 0) { 18838 throw new IllegalArgumentException( 18839 "replacePreferredActivity expects filter to have no data authorities, " + 18840 "paths, or types; and at most one scheme."); 18841 } 18842 18843 final int callingUid = Binder.getCallingUid(); 18844 enforceCrossUserPermission(callingUid, userId, 18845 true /* requireFullPermission */, false /* checkShell */, 18846 "replace preferred activity"); 18847 synchronized (mPackages) { 18848 if (mContext.checkCallingOrSelfPermission( 18849 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18850 != PackageManager.PERMISSION_GRANTED) { 18851 if (getUidTargetSdkVersionLockedLPr(callingUid) 18852 < Build.VERSION_CODES.FROYO) { 18853 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18854 + Binder.getCallingUid()); 18855 return; 18856 } 18857 mContext.enforceCallingOrSelfPermission( 18858 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18859 } 18860 18861 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18862 if (pir != null) { 18863 // Get all of the existing entries that exactly match this filter. 18864 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18865 if (existing != null && existing.size() == 1) { 18866 PreferredActivity cur = existing.get(0); 18867 if (DEBUG_PREFERRED) { 18868 Slog.i(TAG, "Checking replace of preferred:"); 18869 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18870 if (!cur.mPref.mAlways) { 18871 Slog.i(TAG, " -- CUR; not mAlways!"); 18872 } else { 18873 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18874 Slog.i(TAG, " -- CUR: mSet=" 18875 + Arrays.toString(cur.mPref.mSetComponents)); 18876 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18877 Slog.i(TAG, " -- NEW: mMatch=" 18878 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18879 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18880 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18881 } 18882 } 18883 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18884 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18885 && cur.mPref.sameSet(set)) { 18886 // Setting the preferred activity to what it happens to be already 18887 if (DEBUG_PREFERRED) { 18888 Slog.i(TAG, "Replacing with same preferred activity " 18889 + cur.mPref.mShortComponent + " for user " 18890 + userId + ":"); 18891 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18892 } 18893 return; 18894 } 18895 } 18896 18897 if (existing != null) { 18898 if (DEBUG_PREFERRED) { 18899 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18900 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18901 } 18902 for (int i = 0; i < existing.size(); i++) { 18903 PreferredActivity pa = existing.get(i); 18904 if (DEBUG_PREFERRED) { 18905 Slog.i(TAG, "Removing existing preferred activity " 18906 + pa.mPref.mComponent + ":"); 18907 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18908 } 18909 pir.removeFilter(pa); 18910 } 18911 } 18912 } 18913 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18914 "Replacing preferred"); 18915 } 18916 } 18917 18918 @Override 18919 public void clearPackagePreferredActivities(String packageName) { 18920 final int uid = Binder.getCallingUid(); 18921 // writer 18922 synchronized (mPackages) { 18923 PackageParser.Package pkg = mPackages.get(packageName); 18924 if (pkg == null || pkg.applicationInfo.uid != uid) { 18925 if (mContext.checkCallingOrSelfPermission( 18926 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18927 != PackageManager.PERMISSION_GRANTED) { 18928 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18929 < Build.VERSION_CODES.FROYO) { 18930 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18931 + Binder.getCallingUid()); 18932 return; 18933 } 18934 mContext.enforceCallingOrSelfPermission( 18935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18936 } 18937 } 18938 18939 int user = UserHandle.getCallingUserId(); 18940 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18941 scheduleWritePackageRestrictionsLocked(user); 18942 } 18943 } 18944 } 18945 18946 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18947 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18948 ArrayList<PreferredActivity> removed = null; 18949 boolean changed = false; 18950 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18951 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18952 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18953 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18954 continue; 18955 } 18956 Iterator<PreferredActivity> it = pir.filterIterator(); 18957 while (it.hasNext()) { 18958 PreferredActivity pa = it.next(); 18959 // Mark entry for removal only if it matches the package name 18960 // and the entry is of type "always". 18961 if (packageName == null || 18962 (pa.mPref.mComponent.getPackageName().equals(packageName) 18963 && pa.mPref.mAlways)) { 18964 if (removed == null) { 18965 removed = new ArrayList<PreferredActivity>(); 18966 } 18967 removed.add(pa); 18968 } 18969 } 18970 if (removed != null) { 18971 for (int j=0; j<removed.size(); j++) { 18972 PreferredActivity pa = removed.get(j); 18973 pir.removeFilter(pa); 18974 } 18975 changed = true; 18976 } 18977 } 18978 if (changed) { 18979 postPreferredActivityChangedBroadcast(userId); 18980 } 18981 return changed; 18982 } 18983 18984 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18985 private void clearIntentFilterVerificationsLPw(int userId) { 18986 final int packageCount = mPackages.size(); 18987 for (int i = 0; i < packageCount; i++) { 18988 PackageParser.Package pkg = mPackages.valueAt(i); 18989 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18990 } 18991 } 18992 18993 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18994 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18995 if (userId == UserHandle.USER_ALL) { 18996 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18997 sUserManager.getUserIds())) { 18998 for (int oneUserId : sUserManager.getUserIds()) { 18999 scheduleWritePackageRestrictionsLocked(oneUserId); 19000 } 19001 } 19002 } else { 19003 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19004 scheduleWritePackageRestrictionsLocked(userId); 19005 } 19006 } 19007 } 19008 19009 void clearDefaultBrowserIfNeeded(String packageName) { 19010 for (int oneUserId : sUserManager.getUserIds()) { 19011 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19012 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19013 if (packageName.equals(defaultBrowserPackageName)) { 19014 setDefaultBrowserPackageName(null, oneUserId); 19015 } 19016 } 19017 } 19018 19019 @Override 19020 public void resetApplicationPreferences(int userId) { 19021 mContext.enforceCallingOrSelfPermission( 19022 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19023 final long identity = Binder.clearCallingIdentity(); 19024 // writer 19025 try { 19026 synchronized (mPackages) { 19027 clearPackagePreferredActivitiesLPw(null, userId); 19028 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19029 // TODO: We have to reset the default SMS and Phone. This requires 19030 // significant refactoring to keep all default apps in the package 19031 // manager (cleaner but more work) or have the services provide 19032 // callbacks to the package manager to request a default app reset. 19033 applyFactoryDefaultBrowserLPw(userId); 19034 clearIntentFilterVerificationsLPw(userId); 19035 primeDomainVerificationsLPw(userId); 19036 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19037 scheduleWritePackageRestrictionsLocked(userId); 19038 } 19039 resetNetworkPolicies(userId); 19040 } finally { 19041 Binder.restoreCallingIdentity(identity); 19042 } 19043 } 19044 19045 @Override 19046 public int getPreferredActivities(List<IntentFilter> outFilters, 19047 List<ComponentName> outActivities, String packageName) { 19048 19049 int num = 0; 19050 final int userId = UserHandle.getCallingUserId(); 19051 // reader 19052 synchronized (mPackages) { 19053 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19054 if (pir != null) { 19055 final Iterator<PreferredActivity> it = pir.filterIterator(); 19056 while (it.hasNext()) { 19057 final PreferredActivity pa = it.next(); 19058 if (packageName == null 19059 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19060 && pa.mPref.mAlways)) { 19061 if (outFilters != null) { 19062 outFilters.add(new IntentFilter(pa)); 19063 } 19064 if (outActivities != null) { 19065 outActivities.add(pa.mPref.mComponent); 19066 } 19067 } 19068 } 19069 } 19070 } 19071 19072 return num; 19073 } 19074 19075 @Override 19076 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19077 int userId) { 19078 int callingUid = Binder.getCallingUid(); 19079 if (callingUid != Process.SYSTEM_UID) { 19080 throw new SecurityException( 19081 "addPersistentPreferredActivity can only be run by the system"); 19082 } 19083 if (filter.countActions() == 0) { 19084 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19085 return; 19086 } 19087 synchronized (mPackages) { 19088 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19089 ":"); 19090 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19091 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19092 new PersistentPreferredActivity(filter, activity)); 19093 scheduleWritePackageRestrictionsLocked(userId); 19094 postPreferredActivityChangedBroadcast(userId); 19095 } 19096 } 19097 19098 @Override 19099 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19100 int callingUid = Binder.getCallingUid(); 19101 if (callingUid != Process.SYSTEM_UID) { 19102 throw new SecurityException( 19103 "clearPackagePersistentPreferredActivities can only be run by the system"); 19104 } 19105 ArrayList<PersistentPreferredActivity> removed = null; 19106 boolean changed = false; 19107 synchronized (mPackages) { 19108 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19109 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19110 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19111 .valueAt(i); 19112 if (userId != thisUserId) { 19113 continue; 19114 } 19115 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19116 while (it.hasNext()) { 19117 PersistentPreferredActivity ppa = it.next(); 19118 // Mark entry for removal only if it matches the package name. 19119 if (ppa.mComponent.getPackageName().equals(packageName)) { 19120 if (removed == null) { 19121 removed = new ArrayList<PersistentPreferredActivity>(); 19122 } 19123 removed.add(ppa); 19124 } 19125 } 19126 if (removed != null) { 19127 for (int j=0; j<removed.size(); j++) { 19128 PersistentPreferredActivity ppa = removed.get(j); 19129 ppir.removeFilter(ppa); 19130 } 19131 changed = true; 19132 } 19133 } 19134 19135 if (changed) { 19136 scheduleWritePackageRestrictionsLocked(userId); 19137 postPreferredActivityChangedBroadcast(userId); 19138 } 19139 } 19140 } 19141 19142 /** 19143 * Common machinery for picking apart a restored XML blob and passing 19144 * it to a caller-supplied functor to be applied to the running system. 19145 */ 19146 private void restoreFromXml(XmlPullParser parser, int userId, 19147 String expectedStartTag, BlobXmlRestorer functor) 19148 throws IOException, XmlPullParserException { 19149 int type; 19150 while ((type = parser.next()) != XmlPullParser.START_TAG 19151 && type != XmlPullParser.END_DOCUMENT) { 19152 } 19153 if (type != XmlPullParser.START_TAG) { 19154 // oops didn't find a start tag?! 19155 if (DEBUG_BACKUP) { 19156 Slog.e(TAG, "Didn't find start tag during restore"); 19157 } 19158 return; 19159 } 19160Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19161 // this is supposed to be TAG_PREFERRED_BACKUP 19162 if (!expectedStartTag.equals(parser.getName())) { 19163 if (DEBUG_BACKUP) { 19164 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19165 } 19166 return; 19167 } 19168 19169 // skip interfering stuff, then we're aligned with the backing implementation 19170 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19171Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19172 functor.apply(parser, userId); 19173 } 19174 19175 private interface BlobXmlRestorer { 19176 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19177 } 19178 19179 /** 19180 * Non-Binder method, support for the backup/restore mechanism: write the 19181 * full set of preferred activities in its canonical XML format. Returns the 19182 * XML output as a byte array, or null if there is none. 19183 */ 19184 @Override 19185 public byte[] getPreferredActivityBackup(int userId) { 19186 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19187 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19188 } 19189 19190 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19191 try { 19192 final XmlSerializer serializer = new FastXmlSerializer(); 19193 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19194 serializer.startDocument(null, true); 19195 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19196 19197 synchronized (mPackages) { 19198 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19199 } 19200 19201 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19202 serializer.endDocument(); 19203 serializer.flush(); 19204 } catch (Exception e) { 19205 if (DEBUG_BACKUP) { 19206 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19207 } 19208 return null; 19209 } 19210 19211 return dataStream.toByteArray(); 19212 } 19213 19214 @Override 19215 public void restorePreferredActivities(byte[] backup, int userId) { 19216 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19217 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19218 } 19219 19220 try { 19221 final XmlPullParser parser = Xml.newPullParser(); 19222 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19223 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19224 new BlobXmlRestorer() { 19225 @Override 19226 public void apply(XmlPullParser parser, int userId) 19227 throws XmlPullParserException, IOException { 19228 synchronized (mPackages) { 19229 mSettings.readPreferredActivitiesLPw(parser, userId); 19230 } 19231 } 19232 } ); 19233 } catch (Exception e) { 19234 if (DEBUG_BACKUP) { 19235 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19236 } 19237 } 19238 } 19239 19240 /** 19241 * Non-Binder method, support for the backup/restore mechanism: write the 19242 * default browser (etc) settings in its canonical XML format. Returns the default 19243 * browser XML representation as a byte array, or null if there is none. 19244 */ 19245 @Override 19246 public byte[] getDefaultAppsBackup(int userId) { 19247 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19248 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19249 } 19250 19251 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19252 try { 19253 final XmlSerializer serializer = new FastXmlSerializer(); 19254 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19255 serializer.startDocument(null, true); 19256 serializer.startTag(null, TAG_DEFAULT_APPS); 19257 19258 synchronized (mPackages) { 19259 mSettings.writeDefaultAppsLPr(serializer, userId); 19260 } 19261 19262 serializer.endTag(null, TAG_DEFAULT_APPS); 19263 serializer.endDocument(); 19264 serializer.flush(); 19265 } catch (Exception e) { 19266 if (DEBUG_BACKUP) { 19267 Slog.e(TAG, "Unable to write default apps for backup", e); 19268 } 19269 return null; 19270 } 19271 19272 return dataStream.toByteArray(); 19273 } 19274 19275 @Override 19276 public void restoreDefaultApps(byte[] backup, int userId) { 19277 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19278 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19279 } 19280 19281 try { 19282 final XmlPullParser parser = Xml.newPullParser(); 19283 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19284 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19285 new BlobXmlRestorer() { 19286 @Override 19287 public void apply(XmlPullParser parser, int userId) 19288 throws XmlPullParserException, IOException { 19289 synchronized (mPackages) { 19290 mSettings.readDefaultAppsLPw(parser, userId); 19291 } 19292 } 19293 } ); 19294 } catch (Exception e) { 19295 if (DEBUG_BACKUP) { 19296 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19297 } 19298 } 19299 } 19300 19301 @Override 19302 public byte[] getIntentFilterVerificationBackup(int userId) { 19303 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19304 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19305 } 19306 19307 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19308 try { 19309 final XmlSerializer serializer = new FastXmlSerializer(); 19310 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19311 serializer.startDocument(null, true); 19312 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19313 19314 synchronized (mPackages) { 19315 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19316 } 19317 19318 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19319 serializer.endDocument(); 19320 serializer.flush(); 19321 } catch (Exception e) { 19322 if (DEBUG_BACKUP) { 19323 Slog.e(TAG, "Unable to write default apps for backup", e); 19324 } 19325 return null; 19326 } 19327 19328 return dataStream.toByteArray(); 19329 } 19330 19331 @Override 19332 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19333 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19334 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19335 } 19336 19337 try { 19338 final XmlPullParser parser = Xml.newPullParser(); 19339 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19340 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19341 new BlobXmlRestorer() { 19342 @Override 19343 public void apply(XmlPullParser parser, int userId) 19344 throws XmlPullParserException, IOException { 19345 synchronized (mPackages) { 19346 mSettings.readAllDomainVerificationsLPr(parser, userId); 19347 mSettings.writeLPr(); 19348 } 19349 } 19350 } ); 19351 } catch (Exception e) { 19352 if (DEBUG_BACKUP) { 19353 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19354 } 19355 } 19356 } 19357 19358 @Override 19359 public byte[] getPermissionGrantBackup(int userId) { 19360 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19361 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19362 } 19363 19364 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19365 try { 19366 final XmlSerializer serializer = new FastXmlSerializer(); 19367 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19368 serializer.startDocument(null, true); 19369 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19370 19371 synchronized (mPackages) { 19372 serializeRuntimePermissionGrantsLPr(serializer, userId); 19373 } 19374 19375 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19376 serializer.endDocument(); 19377 serializer.flush(); 19378 } catch (Exception e) { 19379 if (DEBUG_BACKUP) { 19380 Slog.e(TAG, "Unable to write default apps for backup", e); 19381 } 19382 return null; 19383 } 19384 19385 return dataStream.toByteArray(); 19386 } 19387 19388 @Override 19389 public void restorePermissionGrants(byte[] backup, int userId) { 19390 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19391 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19392 } 19393 19394 try { 19395 final XmlPullParser parser = Xml.newPullParser(); 19396 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19397 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19398 new BlobXmlRestorer() { 19399 @Override 19400 public void apply(XmlPullParser parser, int userId) 19401 throws XmlPullParserException, IOException { 19402 synchronized (mPackages) { 19403 processRestoredPermissionGrantsLPr(parser, userId); 19404 } 19405 } 19406 } ); 19407 } catch (Exception e) { 19408 if (DEBUG_BACKUP) { 19409 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19410 } 19411 } 19412 } 19413 19414 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19415 throws IOException { 19416 serializer.startTag(null, TAG_ALL_GRANTS); 19417 19418 final int N = mSettings.mPackages.size(); 19419 for (int i = 0; i < N; i++) { 19420 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19421 boolean pkgGrantsKnown = false; 19422 19423 PermissionsState packagePerms = ps.getPermissionsState(); 19424 19425 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19426 final int grantFlags = state.getFlags(); 19427 // only look at grants that are not system/policy fixed 19428 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19429 final boolean isGranted = state.isGranted(); 19430 // And only back up the user-twiddled state bits 19431 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19432 final String packageName = mSettings.mPackages.keyAt(i); 19433 if (!pkgGrantsKnown) { 19434 serializer.startTag(null, TAG_GRANT); 19435 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19436 pkgGrantsKnown = true; 19437 } 19438 19439 final boolean userSet = 19440 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19441 final boolean userFixed = 19442 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19443 final boolean revoke = 19444 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19445 19446 serializer.startTag(null, TAG_PERMISSION); 19447 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19448 if (isGranted) { 19449 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19450 } 19451 if (userSet) { 19452 serializer.attribute(null, ATTR_USER_SET, "true"); 19453 } 19454 if (userFixed) { 19455 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19456 } 19457 if (revoke) { 19458 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19459 } 19460 serializer.endTag(null, TAG_PERMISSION); 19461 } 19462 } 19463 } 19464 19465 if (pkgGrantsKnown) { 19466 serializer.endTag(null, TAG_GRANT); 19467 } 19468 } 19469 19470 serializer.endTag(null, TAG_ALL_GRANTS); 19471 } 19472 19473 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19474 throws XmlPullParserException, IOException { 19475 String pkgName = null; 19476 int outerDepth = parser.getDepth(); 19477 int type; 19478 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19479 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19480 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19481 continue; 19482 } 19483 19484 final String tagName = parser.getName(); 19485 if (tagName.equals(TAG_GRANT)) { 19486 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19487 if (DEBUG_BACKUP) { 19488 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19489 } 19490 } else if (tagName.equals(TAG_PERMISSION)) { 19491 19492 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19493 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19494 19495 int newFlagSet = 0; 19496 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19497 newFlagSet |= FLAG_PERMISSION_USER_SET; 19498 } 19499 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19500 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19501 } 19502 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19503 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19504 } 19505 if (DEBUG_BACKUP) { 19506 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19507 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19508 } 19509 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19510 if (ps != null) { 19511 // Already installed so we apply the grant immediately 19512 if (DEBUG_BACKUP) { 19513 Slog.v(TAG, " + already installed; applying"); 19514 } 19515 PermissionsState perms = ps.getPermissionsState(); 19516 BasePermission bp = mSettings.mPermissions.get(permName); 19517 if (bp != null) { 19518 if (isGranted) { 19519 perms.grantRuntimePermission(bp, userId); 19520 } 19521 if (newFlagSet != 0) { 19522 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19523 } 19524 } 19525 } else { 19526 // Need to wait for post-restore install to apply the grant 19527 if (DEBUG_BACKUP) { 19528 Slog.v(TAG, " - not yet installed; saving for later"); 19529 } 19530 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19531 isGranted, newFlagSet, userId); 19532 } 19533 } else { 19534 PackageManagerService.reportSettingsProblem(Log.WARN, 19535 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19536 XmlUtils.skipCurrentTag(parser); 19537 } 19538 } 19539 19540 scheduleWriteSettingsLocked(); 19541 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19542 } 19543 19544 @Override 19545 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19546 int sourceUserId, int targetUserId, int flags) { 19547 mContext.enforceCallingOrSelfPermission( 19548 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19549 int callingUid = Binder.getCallingUid(); 19550 enforceOwnerRights(ownerPackage, callingUid); 19551 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19552 if (intentFilter.countActions() == 0) { 19553 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19554 return; 19555 } 19556 synchronized (mPackages) { 19557 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19558 ownerPackage, targetUserId, flags); 19559 CrossProfileIntentResolver resolver = 19560 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19561 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19562 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19563 if (existing != null) { 19564 int size = existing.size(); 19565 for (int i = 0; i < size; i++) { 19566 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19567 return; 19568 } 19569 } 19570 } 19571 resolver.addFilter(newFilter); 19572 scheduleWritePackageRestrictionsLocked(sourceUserId); 19573 } 19574 } 19575 19576 @Override 19577 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19578 mContext.enforceCallingOrSelfPermission( 19579 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19580 int callingUid = Binder.getCallingUid(); 19581 enforceOwnerRights(ownerPackage, callingUid); 19582 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19583 synchronized (mPackages) { 19584 CrossProfileIntentResolver resolver = 19585 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19586 ArraySet<CrossProfileIntentFilter> set = 19587 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19588 for (CrossProfileIntentFilter filter : set) { 19589 if (filter.getOwnerPackage().equals(ownerPackage)) { 19590 resolver.removeFilter(filter); 19591 } 19592 } 19593 scheduleWritePackageRestrictionsLocked(sourceUserId); 19594 } 19595 } 19596 19597 // Enforcing that callingUid is owning pkg on userId 19598 private void enforceOwnerRights(String pkg, int callingUid) { 19599 // The system owns everything. 19600 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19601 return; 19602 } 19603 int callingUserId = UserHandle.getUserId(callingUid); 19604 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19605 if (pi == null) { 19606 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19607 + callingUserId); 19608 } 19609 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19610 throw new SecurityException("Calling uid " + callingUid 19611 + " does not own package " + pkg); 19612 } 19613 } 19614 19615 @Override 19616 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19617 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19618 } 19619 19620 private Intent getHomeIntent() { 19621 Intent intent = new Intent(Intent.ACTION_MAIN); 19622 intent.addCategory(Intent.CATEGORY_HOME); 19623 intent.addCategory(Intent.CATEGORY_DEFAULT); 19624 return intent; 19625 } 19626 19627 private IntentFilter getHomeFilter() { 19628 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19629 filter.addCategory(Intent.CATEGORY_HOME); 19630 filter.addCategory(Intent.CATEGORY_DEFAULT); 19631 return filter; 19632 } 19633 19634 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19635 int userId) { 19636 Intent intent = getHomeIntent(); 19637 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19638 PackageManager.GET_META_DATA, userId); 19639 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19640 true, false, false, userId); 19641 19642 allHomeCandidates.clear(); 19643 if (list != null) { 19644 for (ResolveInfo ri : list) { 19645 allHomeCandidates.add(ri); 19646 } 19647 } 19648 return (preferred == null || preferred.activityInfo == null) 19649 ? null 19650 : new ComponentName(preferred.activityInfo.packageName, 19651 preferred.activityInfo.name); 19652 } 19653 19654 @Override 19655 public void setHomeActivity(ComponentName comp, int userId) { 19656 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19657 getHomeActivitiesAsUser(homeActivities, userId); 19658 19659 boolean found = false; 19660 19661 final int size = homeActivities.size(); 19662 final ComponentName[] set = new ComponentName[size]; 19663 for (int i = 0; i < size; i++) { 19664 final ResolveInfo candidate = homeActivities.get(i); 19665 final ActivityInfo info = candidate.activityInfo; 19666 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19667 set[i] = activityName; 19668 if (!found && activityName.equals(comp)) { 19669 found = true; 19670 } 19671 } 19672 if (!found) { 19673 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19674 + userId); 19675 } 19676 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19677 set, comp, userId); 19678 } 19679 19680 private @Nullable String getSetupWizardPackageName() { 19681 final Intent intent = new Intent(Intent.ACTION_MAIN); 19682 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19683 19684 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19685 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19686 | MATCH_DISABLED_COMPONENTS, 19687 UserHandle.myUserId()); 19688 if (matches.size() == 1) { 19689 return matches.get(0).getComponentInfo().packageName; 19690 } else { 19691 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19692 + ": matches=" + matches); 19693 return null; 19694 } 19695 } 19696 19697 private @Nullable String getStorageManagerPackageName() { 19698 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19699 19700 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19701 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19702 | MATCH_DISABLED_COMPONENTS, 19703 UserHandle.myUserId()); 19704 if (matches.size() == 1) { 19705 return matches.get(0).getComponentInfo().packageName; 19706 } else { 19707 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19708 + matches.size() + ": matches=" + matches); 19709 return null; 19710 } 19711 } 19712 19713 @Override 19714 public void setApplicationEnabledSetting(String appPackageName, 19715 int newState, int flags, int userId, String callingPackage) { 19716 if (!sUserManager.exists(userId)) return; 19717 if (callingPackage == null) { 19718 callingPackage = Integer.toString(Binder.getCallingUid()); 19719 } 19720 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19721 } 19722 19723 @Override 19724 public void setComponentEnabledSetting(ComponentName componentName, 19725 int newState, int flags, int userId) { 19726 if (!sUserManager.exists(userId)) return; 19727 setEnabledSetting(componentName.getPackageName(), 19728 componentName.getClassName(), newState, flags, userId, null); 19729 } 19730 19731 private void setEnabledSetting(final String packageName, String className, int newState, 19732 final int flags, int userId, String callingPackage) { 19733 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19734 || newState == COMPONENT_ENABLED_STATE_ENABLED 19735 || newState == COMPONENT_ENABLED_STATE_DISABLED 19736 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19737 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19738 throw new IllegalArgumentException("Invalid new component state: " 19739 + newState); 19740 } 19741 PackageSetting pkgSetting; 19742 final int uid = Binder.getCallingUid(); 19743 final int permission; 19744 if (uid == Process.SYSTEM_UID) { 19745 permission = PackageManager.PERMISSION_GRANTED; 19746 } else { 19747 permission = mContext.checkCallingOrSelfPermission( 19748 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19749 } 19750 enforceCrossUserPermission(uid, userId, 19751 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19752 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19753 boolean sendNow = false; 19754 boolean isApp = (className == null); 19755 String componentName = isApp ? packageName : className; 19756 int packageUid = -1; 19757 ArrayList<String> components; 19758 19759 // writer 19760 synchronized (mPackages) { 19761 pkgSetting = mSettings.mPackages.get(packageName); 19762 if (pkgSetting == null) { 19763 if (className == null) { 19764 throw new IllegalArgumentException("Unknown package: " + packageName); 19765 } 19766 throw new IllegalArgumentException( 19767 "Unknown component: " + packageName + "/" + className); 19768 } 19769 } 19770 19771 // Limit who can change which apps 19772 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19773 // Don't allow apps that don't have permission to modify other apps 19774 if (!allowedByPermission) { 19775 throw new SecurityException( 19776 "Permission Denial: attempt to change component state from pid=" 19777 + Binder.getCallingPid() 19778 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19779 } 19780 // Don't allow changing protected packages. 19781 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19782 throw new SecurityException("Cannot disable a protected package: " + packageName); 19783 } 19784 } 19785 19786 synchronized (mPackages) { 19787 if (uid == Process.SHELL_UID 19788 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19789 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19790 // unless it is a test package. 19791 int oldState = pkgSetting.getEnabled(userId); 19792 if (className == null 19793 && 19794 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19795 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19796 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19797 && 19798 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19799 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19800 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19801 // ok 19802 } else { 19803 throw new SecurityException( 19804 "Shell cannot change component state for " + packageName + "/" 19805 + className + " to " + newState); 19806 } 19807 } 19808 if (className == null) { 19809 // We're dealing with an application/package level state change 19810 if (pkgSetting.getEnabled(userId) == newState) { 19811 // Nothing to do 19812 return; 19813 } 19814 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19815 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19816 // Don't care about who enables an app. 19817 callingPackage = null; 19818 } 19819 pkgSetting.setEnabled(newState, userId, callingPackage); 19820 // pkgSetting.pkg.mSetEnabled = newState; 19821 } else { 19822 // We're dealing with a component level state change 19823 // First, verify that this is a valid class name. 19824 PackageParser.Package pkg = pkgSetting.pkg; 19825 if (pkg == null || !pkg.hasComponentClassName(className)) { 19826 if (pkg != null && 19827 pkg.applicationInfo.targetSdkVersion >= 19828 Build.VERSION_CODES.JELLY_BEAN) { 19829 throw new IllegalArgumentException("Component class " + className 19830 + " does not exist in " + packageName); 19831 } else { 19832 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19833 + className + " does not exist in " + packageName); 19834 } 19835 } 19836 switch (newState) { 19837 case COMPONENT_ENABLED_STATE_ENABLED: 19838 if (!pkgSetting.enableComponentLPw(className, userId)) { 19839 return; 19840 } 19841 break; 19842 case COMPONENT_ENABLED_STATE_DISABLED: 19843 if (!pkgSetting.disableComponentLPw(className, userId)) { 19844 return; 19845 } 19846 break; 19847 case COMPONENT_ENABLED_STATE_DEFAULT: 19848 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19849 return; 19850 } 19851 break; 19852 default: 19853 Slog.e(TAG, "Invalid new component state: " + newState); 19854 return; 19855 } 19856 } 19857 scheduleWritePackageRestrictionsLocked(userId); 19858 updateSequenceNumberLP(packageName, new int[] { userId }); 19859 components = mPendingBroadcasts.get(userId, packageName); 19860 final boolean newPackage = components == null; 19861 if (newPackage) { 19862 components = new ArrayList<String>(); 19863 } 19864 if (!components.contains(componentName)) { 19865 components.add(componentName); 19866 } 19867 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19868 sendNow = true; 19869 // Purge entry from pending broadcast list if another one exists already 19870 // since we are sending one right away. 19871 mPendingBroadcasts.remove(userId, packageName); 19872 } else { 19873 if (newPackage) { 19874 mPendingBroadcasts.put(userId, packageName, components); 19875 } 19876 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19877 // Schedule a message 19878 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19879 } 19880 } 19881 } 19882 19883 long callingId = Binder.clearCallingIdentity(); 19884 try { 19885 if (sendNow) { 19886 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19887 sendPackageChangedBroadcast(packageName, 19888 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19889 } 19890 } finally { 19891 Binder.restoreCallingIdentity(callingId); 19892 } 19893 } 19894 19895 @Override 19896 public void flushPackageRestrictionsAsUser(int userId) { 19897 if (!sUserManager.exists(userId)) { 19898 return; 19899 } 19900 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19901 false /* checkShell */, "flushPackageRestrictions"); 19902 synchronized (mPackages) { 19903 mSettings.writePackageRestrictionsLPr(userId); 19904 mDirtyUsers.remove(userId); 19905 if (mDirtyUsers.isEmpty()) { 19906 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19907 } 19908 } 19909 } 19910 19911 private void sendPackageChangedBroadcast(String packageName, 19912 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19913 if (DEBUG_INSTALL) 19914 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19915 + componentNames); 19916 Bundle extras = new Bundle(4); 19917 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19918 String nameList[] = new String[componentNames.size()]; 19919 componentNames.toArray(nameList); 19920 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19921 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19922 extras.putInt(Intent.EXTRA_UID, packageUid); 19923 // If this is not reporting a change of the overall package, then only send it 19924 // to registered receivers. We don't want to launch a swath of apps for every 19925 // little component state change. 19926 final int flags = !componentNames.contains(packageName) 19927 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19928 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19929 new int[] {UserHandle.getUserId(packageUid)}); 19930 } 19931 19932 @Override 19933 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19934 if (!sUserManager.exists(userId)) return; 19935 final int uid = Binder.getCallingUid(); 19936 final int permission = mContext.checkCallingOrSelfPermission( 19937 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19938 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19939 enforceCrossUserPermission(uid, userId, 19940 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19941 // writer 19942 synchronized (mPackages) { 19943 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19944 allowedByPermission, uid, userId)) { 19945 scheduleWritePackageRestrictionsLocked(userId); 19946 } 19947 } 19948 } 19949 19950 @Override 19951 public String getInstallerPackageName(String packageName) { 19952 // reader 19953 synchronized (mPackages) { 19954 return mSettings.getInstallerPackageNameLPr(packageName); 19955 } 19956 } 19957 19958 public boolean isOrphaned(String packageName) { 19959 // reader 19960 synchronized (mPackages) { 19961 return mSettings.isOrphaned(packageName); 19962 } 19963 } 19964 19965 @Override 19966 public int getApplicationEnabledSetting(String packageName, int userId) { 19967 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19968 int uid = Binder.getCallingUid(); 19969 enforceCrossUserPermission(uid, userId, 19970 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19971 // reader 19972 synchronized (mPackages) { 19973 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19974 } 19975 } 19976 19977 @Override 19978 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19979 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19980 int uid = Binder.getCallingUid(); 19981 enforceCrossUserPermission(uid, userId, 19982 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19983 // reader 19984 synchronized (mPackages) { 19985 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19986 } 19987 } 19988 19989 @Override 19990 public void enterSafeMode() { 19991 enforceSystemOrRoot("Only the system can request entering safe mode"); 19992 19993 if (!mSystemReady) { 19994 mSafeMode = true; 19995 } 19996 } 19997 19998 @Override 19999 public void systemReady() { 20000 mSystemReady = true; 20001 20002 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20003 // disabled after already being started. 20004 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20005 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20006 20007 // Read the compatibilty setting when the system is ready. 20008 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20009 mContext.getContentResolver(), 20010 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20011 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20012 if (DEBUG_SETTINGS) { 20013 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20014 } 20015 20016 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20017 20018 synchronized (mPackages) { 20019 // Verify that all of the preferred activity components actually 20020 // exist. It is possible for applications to be updated and at 20021 // that point remove a previously declared activity component that 20022 // had been set as a preferred activity. We try to clean this up 20023 // the next time we encounter that preferred activity, but it is 20024 // possible for the user flow to never be able to return to that 20025 // situation so here we do a sanity check to make sure we haven't 20026 // left any junk around. 20027 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20028 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20029 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20030 removed.clear(); 20031 for (PreferredActivity pa : pir.filterSet()) { 20032 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20033 removed.add(pa); 20034 } 20035 } 20036 if (removed.size() > 0) { 20037 for (int r=0; r<removed.size(); r++) { 20038 PreferredActivity pa = removed.get(r); 20039 Slog.w(TAG, "Removing dangling preferred activity: " 20040 + pa.mPref.mComponent); 20041 pir.removeFilter(pa); 20042 } 20043 mSettings.writePackageRestrictionsLPr( 20044 mSettings.mPreferredActivities.keyAt(i)); 20045 } 20046 } 20047 20048 for (int userId : UserManagerService.getInstance().getUserIds()) { 20049 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20050 grantPermissionsUserIds = ArrayUtils.appendInt( 20051 grantPermissionsUserIds, userId); 20052 } 20053 } 20054 } 20055 sUserManager.systemReady(); 20056 20057 // If we upgraded grant all default permissions before kicking off. 20058 for (int userId : grantPermissionsUserIds) { 20059 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20060 } 20061 20062 // If we did not grant default permissions, we preload from this the 20063 // default permission exceptions lazily to ensure we don't hit the 20064 // disk on a new user creation. 20065 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20066 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20067 } 20068 20069 // Kick off any messages waiting for system ready 20070 if (mPostSystemReadyMessages != null) { 20071 for (Message msg : mPostSystemReadyMessages) { 20072 msg.sendToTarget(); 20073 } 20074 mPostSystemReadyMessages = null; 20075 } 20076 20077 // Watch for external volumes that come and go over time 20078 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20079 storage.registerListener(mStorageListener); 20080 20081 mInstallerService.systemReady(); 20082 mPackageDexOptimizer.systemReady(); 20083 20084 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20085 StorageManagerInternal.class); 20086 StorageManagerInternal.addExternalStoragePolicy( 20087 new StorageManagerInternal.ExternalStorageMountPolicy() { 20088 @Override 20089 public int getMountMode(int uid, String packageName) { 20090 if (Process.isIsolated(uid)) { 20091 return Zygote.MOUNT_EXTERNAL_NONE; 20092 } 20093 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20094 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20095 } 20096 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20097 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20098 } 20099 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20100 return Zygote.MOUNT_EXTERNAL_READ; 20101 } 20102 return Zygote.MOUNT_EXTERNAL_WRITE; 20103 } 20104 20105 @Override 20106 public boolean hasExternalStorage(int uid, String packageName) { 20107 return true; 20108 } 20109 }); 20110 20111 // Now that we're mostly running, clean up stale users and apps 20112 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20113 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20114 20115 if (mPrivappPermissionsViolations != null) { 20116 Slog.wtf(TAG,"Signature|privileged permissions not in " 20117 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20118 mPrivappPermissionsViolations = null; 20119 } 20120 } 20121 20122 @Override 20123 public boolean isSafeMode() { 20124 return mSafeMode; 20125 } 20126 20127 @Override 20128 public boolean hasSystemUidErrors() { 20129 return mHasSystemUidErrors; 20130 } 20131 20132 static String arrayToString(int[] array) { 20133 StringBuffer buf = new StringBuffer(128); 20134 buf.append('['); 20135 if (array != null) { 20136 for (int i=0; i<array.length; i++) { 20137 if (i > 0) buf.append(", "); 20138 buf.append(array[i]); 20139 } 20140 } 20141 buf.append(']'); 20142 return buf.toString(); 20143 } 20144 20145 static class DumpState { 20146 public static final int DUMP_LIBS = 1 << 0; 20147 public static final int DUMP_FEATURES = 1 << 1; 20148 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20149 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20150 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20151 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20152 public static final int DUMP_PERMISSIONS = 1 << 6; 20153 public static final int DUMP_PACKAGES = 1 << 7; 20154 public static final int DUMP_SHARED_USERS = 1 << 8; 20155 public static final int DUMP_MESSAGES = 1 << 9; 20156 public static final int DUMP_PROVIDERS = 1 << 10; 20157 public static final int DUMP_VERIFIERS = 1 << 11; 20158 public static final int DUMP_PREFERRED = 1 << 12; 20159 public static final int DUMP_PREFERRED_XML = 1 << 13; 20160 public static final int DUMP_KEYSETS = 1 << 14; 20161 public static final int DUMP_VERSION = 1 << 15; 20162 public static final int DUMP_INSTALLS = 1 << 16; 20163 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20164 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20165 public static final int DUMP_FROZEN = 1 << 19; 20166 public static final int DUMP_DEXOPT = 1 << 20; 20167 public static final int DUMP_COMPILER_STATS = 1 << 21; 20168 20169 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20170 20171 private int mTypes; 20172 20173 private int mOptions; 20174 20175 private boolean mTitlePrinted; 20176 20177 private SharedUserSetting mSharedUser; 20178 20179 public boolean isDumping(int type) { 20180 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20181 return true; 20182 } 20183 20184 return (mTypes & type) != 0; 20185 } 20186 20187 public void setDump(int type) { 20188 mTypes |= type; 20189 } 20190 20191 public boolean isOptionEnabled(int option) { 20192 return (mOptions & option) != 0; 20193 } 20194 20195 public void setOptionEnabled(int option) { 20196 mOptions |= option; 20197 } 20198 20199 public boolean onTitlePrinted() { 20200 final boolean printed = mTitlePrinted; 20201 mTitlePrinted = true; 20202 return printed; 20203 } 20204 20205 public boolean getTitlePrinted() { 20206 return mTitlePrinted; 20207 } 20208 20209 public void setTitlePrinted(boolean enabled) { 20210 mTitlePrinted = enabled; 20211 } 20212 20213 public SharedUserSetting getSharedUser() { 20214 return mSharedUser; 20215 } 20216 20217 public void setSharedUser(SharedUserSetting user) { 20218 mSharedUser = user; 20219 } 20220 } 20221 20222 @Override 20223 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20224 FileDescriptor err, String[] args, ShellCallback callback, 20225 ResultReceiver resultReceiver) { 20226 (new PackageManagerShellCommand(this)).exec( 20227 this, in, out, err, args, callback, resultReceiver); 20228 } 20229 20230 @Override 20231 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20232 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20233 != PackageManager.PERMISSION_GRANTED) { 20234 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20235 + Binder.getCallingPid() 20236 + ", uid=" + Binder.getCallingUid() 20237 + " without permission " 20238 + android.Manifest.permission.DUMP); 20239 return; 20240 } 20241 20242 DumpState dumpState = new DumpState(); 20243 boolean fullPreferred = false; 20244 boolean checkin = false; 20245 20246 String packageName = null; 20247 ArraySet<String> permissionNames = null; 20248 20249 int opti = 0; 20250 while (opti < args.length) { 20251 String opt = args[opti]; 20252 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20253 break; 20254 } 20255 opti++; 20256 20257 if ("-a".equals(opt)) { 20258 // Right now we only know how to print all. 20259 } else if ("-h".equals(opt)) { 20260 pw.println("Package manager dump options:"); 20261 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20262 pw.println(" --checkin: dump for a checkin"); 20263 pw.println(" -f: print details of intent filters"); 20264 pw.println(" -h: print this help"); 20265 pw.println(" cmd may be one of:"); 20266 pw.println(" l[ibraries]: list known shared libraries"); 20267 pw.println(" f[eatures]: list device features"); 20268 pw.println(" k[eysets]: print known keysets"); 20269 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20270 pw.println(" perm[issions]: dump permissions"); 20271 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20272 pw.println(" pref[erred]: print preferred package settings"); 20273 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20274 pw.println(" prov[iders]: dump content providers"); 20275 pw.println(" p[ackages]: dump installed packages"); 20276 pw.println(" s[hared-users]: dump shared user IDs"); 20277 pw.println(" m[essages]: print collected runtime messages"); 20278 pw.println(" v[erifiers]: print package verifier info"); 20279 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20280 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20281 pw.println(" version: print database version info"); 20282 pw.println(" write: write current settings now"); 20283 pw.println(" installs: details about install sessions"); 20284 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20285 pw.println(" dexopt: dump dexopt state"); 20286 pw.println(" compiler-stats: dump compiler statistics"); 20287 pw.println(" <package.name>: info about given package"); 20288 return; 20289 } else if ("--checkin".equals(opt)) { 20290 checkin = true; 20291 } else if ("-f".equals(opt)) { 20292 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20293 } else { 20294 pw.println("Unknown argument: " + opt + "; use -h for help"); 20295 } 20296 } 20297 20298 // Is the caller requesting to dump a particular piece of data? 20299 if (opti < args.length) { 20300 String cmd = args[opti]; 20301 opti++; 20302 // Is this a package name? 20303 if ("android".equals(cmd) || cmd.contains(".")) { 20304 packageName = cmd; 20305 // When dumping a single package, we always dump all of its 20306 // filter information since the amount of data will be reasonable. 20307 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20308 } else if ("check-permission".equals(cmd)) { 20309 if (opti >= args.length) { 20310 pw.println("Error: check-permission missing permission argument"); 20311 return; 20312 } 20313 String perm = args[opti]; 20314 opti++; 20315 if (opti >= args.length) { 20316 pw.println("Error: check-permission missing package argument"); 20317 return; 20318 } 20319 20320 String pkg = args[opti]; 20321 opti++; 20322 int user = UserHandle.getUserId(Binder.getCallingUid()); 20323 if (opti < args.length) { 20324 try { 20325 user = Integer.parseInt(args[opti]); 20326 } catch (NumberFormatException e) { 20327 pw.println("Error: check-permission user argument is not a number: " 20328 + args[opti]); 20329 return; 20330 } 20331 } 20332 20333 // Normalize package name to handle renamed packages and static libs 20334 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20335 20336 pw.println(checkPermission(perm, pkg, user)); 20337 return; 20338 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20339 dumpState.setDump(DumpState.DUMP_LIBS); 20340 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20341 dumpState.setDump(DumpState.DUMP_FEATURES); 20342 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20343 if (opti >= args.length) { 20344 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20345 | DumpState.DUMP_SERVICE_RESOLVERS 20346 | DumpState.DUMP_RECEIVER_RESOLVERS 20347 | DumpState.DUMP_CONTENT_RESOLVERS); 20348 } else { 20349 while (opti < args.length) { 20350 String name = args[opti]; 20351 if ("a".equals(name) || "activity".equals(name)) { 20352 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20353 } else if ("s".equals(name) || "service".equals(name)) { 20354 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20355 } else if ("r".equals(name) || "receiver".equals(name)) { 20356 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20357 } else if ("c".equals(name) || "content".equals(name)) { 20358 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20359 } else { 20360 pw.println("Error: unknown resolver table type: " + name); 20361 return; 20362 } 20363 opti++; 20364 } 20365 } 20366 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20367 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20368 } else if ("permission".equals(cmd)) { 20369 if (opti >= args.length) { 20370 pw.println("Error: permission requires permission name"); 20371 return; 20372 } 20373 permissionNames = new ArraySet<>(); 20374 while (opti < args.length) { 20375 permissionNames.add(args[opti]); 20376 opti++; 20377 } 20378 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20379 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20380 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20381 dumpState.setDump(DumpState.DUMP_PREFERRED); 20382 } else if ("preferred-xml".equals(cmd)) { 20383 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20384 if (opti < args.length && "--full".equals(args[opti])) { 20385 fullPreferred = true; 20386 opti++; 20387 } 20388 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20389 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20390 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20391 dumpState.setDump(DumpState.DUMP_PACKAGES); 20392 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20393 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20394 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20395 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20396 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20397 dumpState.setDump(DumpState.DUMP_MESSAGES); 20398 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20399 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20400 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20401 || "intent-filter-verifiers".equals(cmd)) { 20402 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20403 } else if ("version".equals(cmd)) { 20404 dumpState.setDump(DumpState.DUMP_VERSION); 20405 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20406 dumpState.setDump(DumpState.DUMP_KEYSETS); 20407 } else if ("installs".equals(cmd)) { 20408 dumpState.setDump(DumpState.DUMP_INSTALLS); 20409 } else if ("frozen".equals(cmd)) { 20410 dumpState.setDump(DumpState.DUMP_FROZEN); 20411 } else if ("dexopt".equals(cmd)) { 20412 dumpState.setDump(DumpState.DUMP_DEXOPT); 20413 } else if ("compiler-stats".equals(cmd)) { 20414 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20415 } else if ("write".equals(cmd)) { 20416 synchronized (mPackages) { 20417 mSettings.writeLPr(); 20418 pw.println("Settings written."); 20419 return; 20420 } 20421 } 20422 } 20423 20424 if (checkin) { 20425 pw.println("vers,1"); 20426 } 20427 20428 // reader 20429 synchronized (mPackages) { 20430 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20431 if (!checkin) { 20432 if (dumpState.onTitlePrinted()) 20433 pw.println(); 20434 pw.println("Database versions:"); 20435 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20436 } 20437 } 20438 20439 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20440 if (!checkin) { 20441 if (dumpState.onTitlePrinted()) 20442 pw.println(); 20443 pw.println("Verifiers:"); 20444 pw.print(" Required: "); 20445 pw.print(mRequiredVerifierPackage); 20446 pw.print(" (uid="); 20447 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20448 UserHandle.USER_SYSTEM)); 20449 pw.println(")"); 20450 } else if (mRequiredVerifierPackage != null) { 20451 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20452 pw.print(","); 20453 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20454 UserHandle.USER_SYSTEM)); 20455 } 20456 } 20457 20458 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20459 packageName == null) { 20460 if (mIntentFilterVerifierComponent != null) { 20461 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20462 if (!checkin) { 20463 if (dumpState.onTitlePrinted()) 20464 pw.println(); 20465 pw.println("Intent Filter Verifier:"); 20466 pw.print(" Using: "); 20467 pw.print(verifierPackageName); 20468 pw.print(" (uid="); 20469 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20470 UserHandle.USER_SYSTEM)); 20471 pw.println(")"); 20472 } else if (verifierPackageName != null) { 20473 pw.print("ifv,"); pw.print(verifierPackageName); 20474 pw.print(","); 20475 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20476 UserHandle.USER_SYSTEM)); 20477 } 20478 } else { 20479 pw.println(); 20480 pw.println("No Intent Filter Verifier available!"); 20481 } 20482 } 20483 20484 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20485 boolean printedHeader = false; 20486 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20487 while (it.hasNext()) { 20488 String libName = it.next(); 20489 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20490 if (versionedLib == null) { 20491 continue; 20492 } 20493 final int versionCount = versionedLib.size(); 20494 for (int i = 0; i < versionCount; i++) { 20495 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20496 if (!checkin) { 20497 if (!printedHeader) { 20498 if (dumpState.onTitlePrinted()) 20499 pw.println(); 20500 pw.println("Libraries:"); 20501 printedHeader = true; 20502 } 20503 pw.print(" "); 20504 } else { 20505 pw.print("lib,"); 20506 } 20507 pw.print(libEntry.info.getName()); 20508 if (libEntry.info.isStatic()) { 20509 pw.print(" version=" + libEntry.info.getVersion()); 20510 } 20511 if (!checkin) { 20512 pw.print(" -> "); 20513 } 20514 if (libEntry.path != null) { 20515 pw.print(" (jar) "); 20516 pw.print(libEntry.path); 20517 } else { 20518 pw.print(" (apk) "); 20519 pw.print(libEntry.apk); 20520 } 20521 pw.println(); 20522 } 20523 } 20524 } 20525 20526 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20527 if (dumpState.onTitlePrinted()) 20528 pw.println(); 20529 if (!checkin) { 20530 pw.println("Features:"); 20531 } 20532 20533 synchronized (mAvailableFeatures) { 20534 for (FeatureInfo feat : mAvailableFeatures.values()) { 20535 if (checkin) { 20536 pw.print("feat,"); 20537 pw.print(feat.name); 20538 pw.print(","); 20539 pw.println(feat.version); 20540 } else { 20541 pw.print(" "); 20542 pw.print(feat.name); 20543 if (feat.version > 0) { 20544 pw.print(" version="); 20545 pw.print(feat.version); 20546 } 20547 pw.println(); 20548 } 20549 } 20550 } 20551 } 20552 20553 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20554 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20555 : "Activity Resolver Table:", " ", packageName, 20556 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20557 dumpState.setTitlePrinted(true); 20558 } 20559 } 20560 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20561 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20562 : "Receiver Resolver Table:", " ", packageName, 20563 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20564 dumpState.setTitlePrinted(true); 20565 } 20566 } 20567 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20568 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20569 : "Service Resolver Table:", " ", packageName, 20570 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20571 dumpState.setTitlePrinted(true); 20572 } 20573 } 20574 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20575 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20576 : "Provider Resolver Table:", " ", packageName, 20577 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20578 dumpState.setTitlePrinted(true); 20579 } 20580 } 20581 20582 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20583 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20584 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20585 int user = mSettings.mPreferredActivities.keyAt(i); 20586 if (pir.dump(pw, 20587 dumpState.getTitlePrinted() 20588 ? "\nPreferred Activities User " + user + ":" 20589 : "Preferred Activities User " + user + ":", " ", 20590 packageName, true, false)) { 20591 dumpState.setTitlePrinted(true); 20592 } 20593 } 20594 } 20595 20596 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20597 pw.flush(); 20598 FileOutputStream fout = new FileOutputStream(fd); 20599 BufferedOutputStream str = new BufferedOutputStream(fout); 20600 XmlSerializer serializer = new FastXmlSerializer(); 20601 try { 20602 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20603 serializer.startDocument(null, true); 20604 serializer.setFeature( 20605 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20606 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20607 serializer.endDocument(); 20608 serializer.flush(); 20609 } catch (IllegalArgumentException e) { 20610 pw.println("Failed writing: " + e); 20611 } catch (IllegalStateException e) { 20612 pw.println("Failed writing: " + e); 20613 } catch (IOException e) { 20614 pw.println("Failed writing: " + e); 20615 } 20616 } 20617 20618 if (!checkin 20619 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20620 && packageName == null) { 20621 pw.println(); 20622 int count = mSettings.mPackages.size(); 20623 if (count == 0) { 20624 pw.println("No applications!"); 20625 pw.println(); 20626 } else { 20627 final String prefix = " "; 20628 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20629 if (allPackageSettings.size() == 0) { 20630 pw.println("No domain preferred apps!"); 20631 pw.println(); 20632 } else { 20633 pw.println("App verification status:"); 20634 pw.println(); 20635 count = 0; 20636 for (PackageSetting ps : allPackageSettings) { 20637 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20638 if (ivi == null || ivi.getPackageName() == null) continue; 20639 pw.println(prefix + "Package: " + ivi.getPackageName()); 20640 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20641 pw.println(prefix + "Status: " + ivi.getStatusString()); 20642 pw.println(); 20643 count++; 20644 } 20645 if (count == 0) { 20646 pw.println(prefix + "No app verification established."); 20647 pw.println(); 20648 } 20649 for (int userId : sUserManager.getUserIds()) { 20650 pw.println("App linkages for user " + userId + ":"); 20651 pw.println(); 20652 count = 0; 20653 for (PackageSetting ps : allPackageSettings) { 20654 final long status = ps.getDomainVerificationStatusForUser(userId); 20655 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20656 && !DEBUG_DOMAIN_VERIFICATION) { 20657 continue; 20658 } 20659 pw.println(prefix + "Package: " + ps.name); 20660 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20661 String statusStr = IntentFilterVerificationInfo. 20662 getStatusStringFromValue(status); 20663 pw.println(prefix + "Status: " + statusStr); 20664 pw.println(); 20665 count++; 20666 } 20667 if (count == 0) { 20668 pw.println(prefix + "No configured app linkages."); 20669 pw.println(); 20670 } 20671 } 20672 } 20673 } 20674 } 20675 20676 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20677 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20678 if (packageName == null && permissionNames == null) { 20679 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20680 if (iperm == 0) { 20681 if (dumpState.onTitlePrinted()) 20682 pw.println(); 20683 pw.println("AppOp Permissions:"); 20684 } 20685 pw.print(" AppOp Permission "); 20686 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20687 pw.println(":"); 20688 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20689 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20690 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20691 } 20692 } 20693 } 20694 } 20695 20696 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20697 boolean printedSomething = false; 20698 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20699 if (packageName != null && !packageName.equals(p.info.packageName)) { 20700 continue; 20701 } 20702 if (!printedSomething) { 20703 if (dumpState.onTitlePrinted()) 20704 pw.println(); 20705 pw.println("Registered ContentProviders:"); 20706 printedSomething = true; 20707 } 20708 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20709 pw.print(" "); pw.println(p.toString()); 20710 } 20711 printedSomething = false; 20712 for (Map.Entry<String, PackageParser.Provider> entry : 20713 mProvidersByAuthority.entrySet()) { 20714 PackageParser.Provider p = entry.getValue(); 20715 if (packageName != null && !packageName.equals(p.info.packageName)) { 20716 continue; 20717 } 20718 if (!printedSomething) { 20719 if (dumpState.onTitlePrinted()) 20720 pw.println(); 20721 pw.println("ContentProvider Authorities:"); 20722 printedSomething = true; 20723 } 20724 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20725 pw.print(" "); pw.println(p.toString()); 20726 if (p.info != null && p.info.applicationInfo != null) { 20727 final String appInfo = p.info.applicationInfo.toString(); 20728 pw.print(" applicationInfo="); pw.println(appInfo); 20729 } 20730 } 20731 } 20732 20733 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20734 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20735 } 20736 20737 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20738 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20739 } 20740 20741 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20742 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20743 } 20744 20745 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20746 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20747 } 20748 20749 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20750 // XXX should handle packageName != null by dumping only install data that 20751 // the given package is involved with. 20752 if (dumpState.onTitlePrinted()) pw.println(); 20753 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20754 } 20755 20756 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20757 // XXX should handle packageName != null by dumping only install data that 20758 // the given package is involved with. 20759 if (dumpState.onTitlePrinted()) pw.println(); 20760 20761 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20762 ipw.println(); 20763 ipw.println("Frozen packages:"); 20764 ipw.increaseIndent(); 20765 if (mFrozenPackages.size() == 0) { 20766 ipw.println("(none)"); 20767 } else { 20768 for (int i = 0; i < mFrozenPackages.size(); i++) { 20769 ipw.println(mFrozenPackages.valueAt(i)); 20770 } 20771 } 20772 ipw.decreaseIndent(); 20773 } 20774 20775 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20776 if (dumpState.onTitlePrinted()) pw.println(); 20777 dumpDexoptStateLPr(pw, packageName); 20778 } 20779 20780 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20781 if (dumpState.onTitlePrinted()) pw.println(); 20782 dumpCompilerStatsLPr(pw, packageName); 20783 } 20784 20785 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20786 if (dumpState.onTitlePrinted()) pw.println(); 20787 mSettings.dumpReadMessagesLPr(pw, dumpState); 20788 20789 pw.println(); 20790 pw.println("Package warning messages:"); 20791 BufferedReader in = null; 20792 String line = null; 20793 try { 20794 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20795 while ((line = in.readLine()) != null) { 20796 if (line.contains("ignored: updated version")) continue; 20797 pw.println(line); 20798 } 20799 } catch (IOException ignored) { 20800 } finally { 20801 IoUtils.closeQuietly(in); 20802 } 20803 } 20804 20805 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20806 BufferedReader in = null; 20807 String line = null; 20808 try { 20809 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20810 while ((line = in.readLine()) != null) { 20811 if (line.contains("ignored: updated version")) continue; 20812 pw.print("msg,"); 20813 pw.println(line); 20814 } 20815 } catch (IOException ignored) { 20816 } finally { 20817 IoUtils.closeQuietly(in); 20818 } 20819 } 20820 } 20821 } 20822 20823 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20824 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20825 ipw.println(); 20826 ipw.println("Dexopt state:"); 20827 ipw.increaseIndent(); 20828 Collection<PackageParser.Package> packages = null; 20829 if (packageName != null) { 20830 PackageParser.Package targetPackage = mPackages.get(packageName); 20831 if (targetPackage != null) { 20832 packages = Collections.singletonList(targetPackage); 20833 } else { 20834 ipw.println("Unable to find package: " + packageName); 20835 return; 20836 } 20837 } else { 20838 packages = mPackages.values(); 20839 } 20840 20841 for (PackageParser.Package pkg : packages) { 20842 ipw.println("[" + pkg.packageName + "]"); 20843 ipw.increaseIndent(); 20844 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20845 ipw.decreaseIndent(); 20846 } 20847 } 20848 20849 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20850 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20851 ipw.println(); 20852 ipw.println("Compiler stats:"); 20853 ipw.increaseIndent(); 20854 Collection<PackageParser.Package> packages = null; 20855 if (packageName != null) { 20856 PackageParser.Package targetPackage = mPackages.get(packageName); 20857 if (targetPackage != null) { 20858 packages = Collections.singletonList(targetPackage); 20859 } else { 20860 ipw.println("Unable to find package: " + packageName); 20861 return; 20862 } 20863 } else { 20864 packages = mPackages.values(); 20865 } 20866 20867 for (PackageParser.Package pkg : packages) { 20868 ipw.println("[" + pkg.packageName + "]"); 20869 ipw.increaseIndent(); 20870 20871 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20872 if (stats == null) { 20873 ipw.println("(No recorded stats)"); 20874 } else { 20875 stats.dump(ipw); 20876 } 20877 ipw.decreaseIndent(); 20878 } 20879 } 20880 20881 private String dumpDomainString(String packageName) { 20882 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20883 .getList(); 20884 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20885 20886 ArraySet<String> result = new ArraySet<>(); 20887 if (iviList.size() > 0) { 20888 for (IntentFilterVerificationInfo ivi : iviList) { 20889 for (String host : ivi.getDomains()) { 20890 result.add(host); 20891 } 20892 } 20893 } 20894 if (filters != null && filters.size() > 0) { 20895 for (IntentFilter filter : filters) { 20896 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20897 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20898 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20899 result.addAll(filter.getHostsList()); 20900 } 20901 } 20902 } 20903 20904 StringBuilder sb = new StringBuilder(result.size() * 16); 20905 for (String domain : result) { 20906 if (sb.length() > 0) sb.append(" "); 20907 sb.append(domain); 20908 } 20909 return sb.toString(); 20910 } 20911 20912 // ------- apps on sdcard specific code ------- 20913 static final boolean DEBUG_SD_INSTALL = false; 20914 20915 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20916 20917 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20918 20919 private boolean mMediaMounted = false; 20920 20921 static String getEncryptKey() { 20922 try { 20923 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20924 SD_ENCRYPTION_KEYSTORE_NAME); 20925 if (sdEncKey == null) { 20926 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20927 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20928 if (sdEncKey == null) { 20929 Slog.e(TAG, "Failed to create encryption keys"); 20930 return null; 20931 } 20932 } 20933 return sdEncKey; 20934 } catch (NoSuchAlgorithmException nsae) { 20935 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20936 return null; 20937 } catch (IOException ioe) { 20938 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20939 return null; 20940 } 20941 } 20942 20943 /* 20944 * Update media status on PackageManager. 20945 */ 20946 @Override 20947 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 20948 int callingUid = Binder.getCallingUid(); 20949 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 20950 throw new SecurityException("Media status can only be updated by the system"); 20951 } 20952 // reader; this apparently protects mMediaMounted, but should probably 20953 // be a different lock in that case. 20954 synchronized (mPackages) { 20955 Log.i(TAG, "Updating external media status from " 20956 + (mMediaMounted ? "mounted" : "unmounted") + " to " 20957 + (mediaStatus ? "mounted" : "unmounted")); 20958 if (DEBUG_SD_INSTALL) 20959 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 20960 + ", mMediaMounted=" + mMediaMounted); 20961 if (mediaStatus == mMediaMounted) { 20962 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 20963 : 0, -1); 20964 mHandler.sendMessage(msg); 20965 return; 20966 } 20967 mMediaMounted = mediaStatus; 20968 } 20969 // Queue up an async operation since the package installation may take a 20970 // little while. 20971 mHandler.post(new Runnable() { 20972 public void run() { 20973 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 20974 } 20975 }); 20976 } 20977 20978 /** 20979 * Called by StorageManagerService when the initial ASECs to scan are available. 20980 * Should block until all the ASEC containers are finished being scanned. 20981 */ 20982 public void scanAvailableAsecs() { 20983 updateExternalMediaStatusInner(true, false, false); 20984 } 20985 20986 /* 20987 * Collect information of applications on external media, map them against 20988 * existing containers and update information based on current mount status. 20989 * Please note that we always have to report status if reportStatus has been 20990 * set to true especially when unloading packages. 20991 */ 20992 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 20993 boolean externalStorage) { 20994 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 20995 int[] uidArr = EmptyArray.INT; 20996 20997 final String[] list = PackageHelper.getSecureContainerList(); 20998 if (ArrayUtils.isEmpty(list)) { 20999 Log.i(TAG, "No secure containers found"); 21000 } else { 21001 // Process list of secure containers and categorize them 21002 // as active or stale based on their package internal state. 21003 21004 // reader 21005 synchronized (mPackages) { 21006 for (String cid : list) { 21007 // Leave stages untouched for now; installer service owns them 21008 if (PackageInstallerService.isStageName(cid)) continue; 21009 21010 if (DEBUG_SD_INSTALL) 21011 Log.i(TAG, "Processing container " + cid); 21012 String pkgName = getAsecPackageName(cid); 21013 if (pkgName == null) { 21014 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21015 continue; 21016 } 21017 if (DEBUG_SD_INSTALL) 21018 Log.i(TAG, "Looking for pkg : " + pkgName); 21019 21020 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21021 if (ps == null) { 21022 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21023 continue; 21024 } 21025 21026 /* 21027 * Skip packages that are not external if we're unmounting 21028 * external storage. 21029 */ 21030 if (externalStorage && !isMounted && !isExternal(ps)) { 21031 continue; 21032 } 21033 21034 final AsecInstallArgs args = new AsecInstallArgs(cid, 21035 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21036 // The package status is changed only if the code path 21037 // matches between settings and the container id. 21038 if (ps.codePathString != null 21039 && ps.codePathString.startsWith(args.getCodePath())) { 21040 if (DEBUG_SD_INSTALL) { 21041 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21042 + " at code path: " + ps.codePathString); 21043 } 21044 21045 // We do have a valid package installed on sdcard 21046 processCids.put(args, ps.codePathString); 21047 final int uid = ps.appId; 21048 if (uid != -1) { 21049 uidArr = ArrayUtils.appendInt(uidArr, uid); 21050 } 21051 } else { 21052 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21053 + ps.codePathString); 21054 } 21055 } 21056 } 21057 21058 Arrays.sort(uidArr); 21059 } 21060 21061 // Process packages with valid entries. 21062 if (isMounted) { 21063 if (DEBUG_SD_INSTALL) 21064 Log.i(TAG, "Loading packages"); 21065 loadMediaPackages(processCids, uidArr, externalStorage); 21066 startCleaningPackages(); 21067 mInstallerService.onSecureContainersAvailable(); 21068 } else { 21069 if (DEBUG_SD_INSTALL) 21070 Log.i(TAG, "Unloading packages"); 21071 unloadMediaPackages(processCids, uidArr, reportStatus); 21072 } 21073 } 21074 21075 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21076 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21077 final int size = infos.size(); 21078 final String[] packageNames = new String[size]; 21079 final int[] packageUids = new int[size]; 21080 for (int i = 0; i < size; i++) { 21081 final ApplicationInfo info = infos.get(i); 21082 packageNames[i] = info.packageName; 21083 packageUids[i] = info.uid; 21084 } 21085 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21086 finishedReceiver); 21087 } 21088 21089 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21090 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21091 sendResourcesChangedBroadcast(mediaStatus, replacing, 21092 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21093 } 21094 21095 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21096 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21097 int size = pkgList.length; 21098 if (size > 0) { 21099 // Send broadcasts here 21100 Bundle extras = new Bundle(); 21101 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21102 if (uidArr != null) { 21103 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21104 } 21105 if (replacing) { 21106 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21107 } 21108 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21109 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21110 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21111 } 21112 } 21113 21114 /* 21115 * Look at potentially valid container ids from processCids If package 21116 * information doesn't match the one on record or package scanning fails, 21117 * the cid is added to list of removeCids. We currently don't delete stale 21118 * containers. 21119 */ 21120 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21121 boolean externalStorage) { 21122 ArrayList<String> pkgList = new ArrayList<String>(); 21123 Set<AsecInstallArgs> keys = processCids.keySet(); 21124 21125 for (AsecInstallArgs args : keys) { 21126 String codePath = processCids.get(args); 21127 if (DEBUG_SD_INSTALL) 21128 Log.i(TAG, "Loading container : " + args.cid); 21129 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21130 try { 21131 // Make sure there are no container errors first. 21132 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21133 Slog.e(TAG, "Failed to mount cid : " + args.cid 21134 + " when installing from sdcard"); 21135 continue; 21136 } 21137 // Check code path here. 21138 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21139 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21140 + " does not match one in settings " + codePath); 21141 continue; 21142 } 21143 // Parse package 21144 int parseFlags = mDefParseFlags; 21145 if (args.isExternalAsec()) { 21146 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21147 } 21148 if (args.isFwdLocked()) { 21149 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21150 } 21151 21152 synchronized (mInstallLock) { 21153 PackageParser.Package pkg = null; 21154 try { 21155 // Sadly we don't know the package name yet to freeze it 21156 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21157 SCAN_IGNORE_FROZEN, 0, null); 21158 } catch (PackageManagerException e) { 21159 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21160 } 21161 // Scan the package 21162 if (pkg != null) { 21163 /* 21164 * TODO why is the lock being held? doPostInstall is 21165 * called in other places without the lock. This needs 21166 * to be straightened out. 21167 */ 21168 // writer 21169 synchronized (mPackages) { 21170 retCode = PackageManager.INSTALL_SUCCEEDED; 21171 pkgList.add(pkg.packageName); 21172 // Post process args 21173 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21174 pkg.applicationInfo.uid); 21175 } 21176 } else { 21177 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21178 } 21179 } 21180 21181 } finally { 21182 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21183 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21184 } 21185 } 21186 } 21187 // writer 21188 synchronized (mPackages) { 21189 // If the platform SDK has changed since the last time we booted, 21190 // we need to re-grant app permission to catch any new ones that 21191 // appear. This is really a hack, and means that apps can in some 21192 // cases get permissions that the user didn't initially explicitly 21193 // allow... it would be nice to have some better way to handle 21194 // this situation. 21195 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21196 : mSettings.getInternalVersion(); 21197 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21198 : StorageManager.UUID_PRIVATE_INTERNAL; 21199 21200 int updateFlags = UPDATE_PERMISSIONS_ALL; 21201 if (ver.sdkVersion != mSdkVersion) { 21202 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21203 + mSdkVersion + "; regranting permissions for external"); 21204 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21205 } 21206 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21207 21208 // Yay, everything is now upgraded 21209 ver.forceCurrent(); 21210 21211 // can downgrade to reader 21212 // Persist settings 21213 mSettings.writeLPr(); 21214 } 21215 // Send a broadcast to let everyone know we are done processing 21216 if (pkgList.size() > 0) { 21217 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21218 } 21219 } 21220 21221 /* 21222 * Utility method to unload a list of specified containers 21223 */ 21224 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21225 // Just unmount all valid containers. 21226 for (AsecInstallArgs arg : cidArgs) { 21227 synchronized (mInstallLock) { 21228 arg.doPostDeleteLI(false); 21229 } 21230 } 21231 } 21232 21233 /* 21234 * Unload packages mounted on external media. This involves deleting package 21235 * data from internal structures, sending broadcasts about disabled packages, 21236 * gc'ing to free up references, unmounting all secure containers 21237 * corresponding to packages on external media, and posting a 21238 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21239 * that we always have to post this message if status has been requested no 21240 * matter what. 21241 */ 21242 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21243 final boolean reportStatus) { 21244 if (DEBUG_SD_INSTALL) 21245 Log.i(TAG, "unloading media packages"); 21246 ArrayList<String> pkgList = new ArrayList<String>(); 21247 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21248 final Set<AsecInstallArgs> keys = processCids.keySet(); 21249 for (AsecInstallArgs args : keys) { 21250 String pkgName = args.getPackageName(); 21251 if (DEBUG_SD_INSTALL) 21252 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21253 // Delete package internally 21254 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21255 synchronized (mInstallLock) { 21256 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21257 final boolean res; 21258 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21259 "unloadMediaPackages")) { 21260 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21261 null); 21262 } 21263 if (res) { 21264 pkgList.add(pkgName); 21265 } else { 21266 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21267 failedList.add(args); 21268 } 21269 } 21270 } 21271 21272 // reader 21273 synchronized (mPackages) { 21274 // We didn't update the settings after removing each package; 21275 // write them now for all packages. 21276 mSettings.writeLPr(); 21277 } 21278 21279 // We have to absolutely send UPDATED_MEDIA_STATUS only 21280 // after confirming that all the receivers processed the ordered 21281 // broadcast when packages get disabled, force a gc to clean things up. 21282 // and unload all the containers. 21283 if (pkgList.size() > 0) { 21284 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21285 new IIntentReceiver.Stub() { 21286 public void performReceive(Intent intent, int resultCode, String data, 21287 Bundle extras, boolean ordered, boolean sticky, 21288 int sendingUser) throws RemoteException { 21289 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21290 reportStatus ? 1 : 0, 1, keys); 21291 mHandler.sendMessage(msg); 21292 } 21293 }); 21294 } else { 21295 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21296 keys); 21297 mHandler.sendMessage(msg); 21298 } 21299 } 21300 21301 private void loadPrivatePackages(final VolumeInfo vol) { 21302 mHandler.post(new Runnable() { 21303 @Override 21304 public void run() { 21305 loadPrivatePackagesInner(vol); 21306 } 21307 }); 21308 } 21309 21310 private void loadPrivatePackagesInner(VolumeInfo vol) { 21311 final String volumeUuid = vol.fsUuid; 21312 if (TextUtils.isEmpty(volumeUuid)) { 21313 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21314 return; 21315 } 21316 21317 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21318 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21319 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21320 21321 final VersionInfo ver; 21322 final List<PackageSetting> packages; 21323 synchronized (mPackages) { 21324 ver = mSettings.findOrCreateVersion(volumeUuid); 21325 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21326 } 21327 21328 for (PackageSetting ps : packages) { 21329 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21330 synchronized (mInstallLock) { 21331 final PackageParser.Package pkg; 21332 try { 21333 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21334 loaded.add(pkg.applicationInfo); 21335 21336 } catch (PackageManagerException e) { 21337 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21338 } 21339 21340 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21341 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21342 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21343 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21344 } 21345 } 21346 } 21347 21348 // Reconcile app data for all started/unlocked users 21349 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21350 final UserManager um = mContext.getSystemService(UserManager.class); 21351 UserManagerInternal umInternal = getUserManagerInternal(); 21352 for (UserInfo user : um.getUsers()) { 21353 final int flags; 21354 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21355 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21356 } else if (umInternal.isUserRunning(user.id)) { 21357 flags = StorageManager.FLAG_STORAGE_DE; 21358 } else { 21359 continue; 21360 } 21361 21362 try { 21363 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21364 synchronized (mInstallLock) { 21365 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21366 } 21367 } catch (IllegalStateException e) { 21368 // Device was probably ejected, and we'll process that event momentarily 21369 Slog.w(TAG, "Failed to prepare storage: " + e); 21370 } 21371 } 21372 21373 synchronized (mPackages) { 21374 int updateFlags = UPDATE_PERMISSIONS_ALL; 21375 if (ver.sdkVersion != mSdkVersion) { 21376 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21377 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21378 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21379 } 21380 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21381 21382 // Yay, everything is now upgraded 21383 ver.forceCurrent(); 21384 21385 mSettings.writeLPr(); 21386 } 21387 21388 for (PackageFreezer freezer : freezers) { 21389 freezer.close(); 21390 } 21391 21392 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21393 sendResourcesChangedBroadcast(true, false, loaded, null); 21394 } 21395 21396 private void unloadPrivatePackages(final VolumeInfo vol) { 21397 mHandler.post(new Runnable() { 21398 @Override 21399 public void run() { 21400 unloadPrivatePackagesInner(vol); 21401 } 21402 }); 21403 } 21404 21405 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21406 final String volumeUuid = vol.fsUuid; 21407 if (TextUtils.isEmpty(volumeUuid)) { 21408 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21409 return; 21410 } 21411 21412 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21413 synchronized (mInstallLock) { 21414 synchronized (mPackages) { 21415 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21416 for (PackageSetting ps : packages) { 21417 if (ps.pkg == null) continue; 21418 21419 final ApplicationInfo info = ps.pkg.applicationInfo; 21420 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21421 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21422 21423 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21424 "unloadPrivatePackagesInner")) { 21425 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21426 false, null)) { 21427 unloaded.add(info); 21428 } else { 21429 Slog.w(TAG, "Failed to unload " + ps.codePath); 21430 } 21431 } 21432 21433 // Try very hard to release any references to this package 21434 // so we don't risk the system server being killed due to 21435 // open FDs 21436 AttributeCache.instance().removePackage(ps.name); 21437 } 21438 21439 mSettings.writeLPr(); 21440 } 21441 } 21442 21443 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21444 sendResourcesChangedBroadcast(false, false, unloaded, null); 21445 21446 // Try very hard to release any references to this path so we don't risk 21447 // the system server being killed due to open FDs 21448 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21449 21450 for (int i = 0; i < 3; i++) { 21451 System.gc(); 21452 System.runFinalization(); 21453 } 21454 } 21455 21456 private void assertPackageKnown(String volumeUuid, String packageName) 21457 throws PackageManagerException { 21458 synchronized (mPackages) { 21459 // Normalize package name to handle renamed packages 21460 packageName = normalizePackageNameLPr(packageName); 21461 21462 final PackageSetting ps = mSettings.mPackages.get(packageName); 21463 if (ps == null) { 21464 throw new PackageManagerException("Package " + packageName + " is unknown"); 21465 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21466 throw new PackageManagerException( 21467 "Package " + packageName + " found on unknown volume " + volumeUuid 21468 + "; expected volume " + ps.volumeUuid); 21469 } 21470 } 21471 } 21472 21473 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21474 throws PackageManagerException { 21475 synchronized (mPackages) { 21476 // Normalize package name to handle renamed packages 21477 packageName = normalizePackageNameLPr(packageName); 21478 21479 final PackageSetting ps = mSettings.mPackages.get(packageName); 21480 if (ps == null) { 21481 throw new PackageManagerException("Package " + packageName + " is unknown"); 21482 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21483 throw new PackageManagerException( 21484 "Package " + packageName + " found on unknown volume " + volumeUuid 21485 + "; expected volume " + ps.volumeUuid); 21486 } else if (!ps.getInstalled(userId)) { 21487 throw new PackageManagerException( 21488 "Package " + packageName + " not installed for user " + userId); 21489 } 21490 } 21491 } 21492 21493 private List<String> collectAbsoluteCodePaths() { 21494 synchronized (mPackages) { 21495 List<String> codePaths = new ArrayList<>(); 21496 final int packageCount = mSettings.mPackages.size(); 21497 for (int i = 0; i < packageCount; i++) { 21498 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21499 codePaths.add(ps.codePath.getAbsolutePath()); 21500 } 21501 return codePaths; 21502 } 21503 } 21504 21505 /** 21506 * Examine all apps present on given mounted volume, and destroy apps that 21507 * aren't expected, either due to uninstallation or reinstallation on 21508 * another volume. 21509 */ 21510 private void reconcileApps(String volumeUuid) { 21511 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21512 List<File> filesToDelete = null; 21513 21514 final File[] files = FileUtils.listFilesOrEmpty( 21515 Environment.getDataAppDirectory(volumeUuid)); 21516 for (File file : files) { 21517 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21518 && !PackageInstallerService.isStageName(file.getName()); 21519 if (!isPackage) { 21520 // Ignore entries which are not packages 21521 continue; 21522 } 21523 21524 String absolutePath = file.getAbsolutePath(); 21525 21526 boolean pathValid = false; 21527 final int absoluteCodePathCount = absoluteCodePaths.size(); 21528 for (int i = 0; i < absoluteCodePathCount; i++) { 21529 String absoluteCodePath = absoluteCodePaths.get(i); 21530 if (absolutePath.startsWith(absoluteCodePath)) { 21531 pathValid = true; 21532 break; 21533 } 21534 } 21535 21536 if (!pathValid) { 21537 if (filesToDelete == null) { 21538 filesToDelete = new ArrayList<>(); 21539 } 21540 filesToDelete.add(file); 21541 } 21542 } 21543 21544 if (filesToDelete != null) { 21545 final int fileToDeleteCount = filesToDelete.size(); 21546 for (int i = 0; i < fileToDeleteCount; i++) { 21547 File fileToDelete = filesToDelete.get(i); 21548 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21549 synchronized (mInstallLock) { 21550 removeCodePathLI(fileToDelete); 21551 } 21552 } 21553 } 21554 } 21555 21556 /** 21557 * Reconcile all app data for the given user. 21558 * <p> 21559 * Verifies that directories exist and that ownership and labeling is 21560 * correct for all installed apps on all mounted volumes. 21561 */ 21562 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21563 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21564 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21565 final String volumeUuid = vol.getFsUuid(); 21566 synchronized (mInstallLock) { 21567 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21568 } 21569 } 21570 } 21571 21572 /** 21573 * Reconcile all app data on given mounted volume. 21574 * <p> 21575 * Destroys app data that isn't expected, either due to uninstallation or 21576 * reinstallation on another volume. 21577 * <p> 21578 * Verifies that directories exist and that ownership and labeling is 21579 * correct for all installed apps. 21580 */ 21581 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21582 boolean migrateAppData) { 21583 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21584 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21585 21586 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21587 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21588 21589 // First look for stale data that doesn't belong, and check if things 21590 // have changed since we did our last restorecon 21591 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21592 if (StorageManager.isFileEncryptedNativeOrEmulated() 21593 && !StorageManager.isUserKeyUnlocked(userId)) { 21594 throw new RuntimeException( 21595 "Yikes, someone asked us to reconcile CE storage while " + userId 21596 + " was still locked; this would have caused massive data loss!"); 21597 } 21598 21599 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21600 for (File file : files) { 21601 final String packageName = file.getName(); 21602 try { 21603 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21604 } catch (PackageManagerException e) { 21605 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21606 try { 21607 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21608 StorageManager.FLAG_STORAGE_CE, 0); 21609 } catch (InstallerException e2) { 21610 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21611 } 21612 } 21613 } 21614 } 21615 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21616 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21617 for (File file : files) { 21618 final String packageName = file.getName(); 21619 try { 21620 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21621 } catch (PackageManagerException e) { 21622 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21623 try { 21624 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21625 StorageManager.FLAG_STORAGE_DE, 0); 21626 } catch (InstallerException e2) { 21627 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21628 } 21629 } 21630 } 21631 } 21632 21633 // Ensure that data directories are ready to roll for all packages 21634 // installed for this volume and user 21635 final List<PackageSetting> packages; 21636 synchronized (mPackages) { 21637 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21638 } 21639 int preparedCount = 0; 21640 for (PackageSetting ps : packages) { 21641 final String packageName = ps.name; 21642 if (ps.pkg == null) { 21643 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21644 // TODO: might be due to legacy ASEC apps; we should circle back 21645 // and reconcile again once they're scanned 21646 continue; 21647 } 21648 21649 if (ps.getInstalled(userId)) { 21650 prepareAppDataLIF(ps.pkg, userId, flags); 21651 21652 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 21653 // We may have just shuffled around app data directories, so 21654 // prepare them one more time 21655 prepareAppDataLIF(ps.pkg, userId, flags); 21656 } 21657 21658 preparedCount++; 21659 } 21660 } 21661 21662 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21663 } 21664 21665 /** 21666 * Prepare app data for the given app just after it was installed or 21667 * upgraded. This method carefully only touches users that it's installed 21668 * for, and it forces a restorecon to handle any seinfo changes. 21669 * <p> 21670 * Verifies that directories exist and that ownership and labeling is 21671 * correct for all installed apps. If there is an ownership mismatch, it 21672 * will try recovering system apps by wiping data; third-party app data is 21673 * left intact. 21674 * <p> 21675 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21676 */ 21677 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21678 final PackageSetting ps; 21679 synchronized (mPackages) { 21680 ps = mSettings.mPackages.get(pkg.packageName); 21681 mSettings.writeKernelMappingLPr(ps); 21682 } 21683 21684 final UserManager um = mContext.getSystemService(UserManager.class); 21685 UserManagerInternal umInternal = getUserManagerInternal(); 21686 for (UserInfo user : um.getUsers()) { 21687 final int flags; 21688 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21689 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21690 } else if (umInternal.isUserRunning(user.id)) { 21691 flags = StorageManager.FLAG_STORAGE_DE; 21692 } else { 21693 continue; 21694 } 21695 21696 if (ps.getInstalled(user.id)) { 21697 // TODO: when user data is locked, mark that we're still dirty 21698 prepareAppDataLIF(pkg, user.id, flags); 21699 } 21700 } 21701 } 21702 21703 /** 21704 * Prepare app data for the given app. 21705 * <p> 21706 * Verifies that directories exist and that ownership and labeling is 21707 * correct for all installed apps. If there is an ownership mismatch, this 21708 * will try recovering system apps by wiping data; third-party app data is 21709 * left intact. 21710 */ 21711 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21712 if (pkg == null) { 21713 Slog.wtf(TAG, "Package was null!", new Throwable()); 21714 return; 21715 } 21716 prepareAppDataLeafLIF(pkg, userId, flags); 21717 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21718 for (int i = 0; i < childCount; i++) { 21719 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21720 } 21721 } 21722 21723 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21724 if (DEBUG_APP_DATA) { 21725 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21726 + Integer.toHexString(flags)); 21727 } 21728 21729 final String volumeUuid = pkg.volumeUuid; 21730 final String packageName = pkg.packageName; 21731 final ApplicationInfo app = pkg.applicationInfo; 21732 final int appId = UserHandle.getAppId(app.uid); 21733 21734 Preconditions.checkNotNull(app.seInfo); 21735 21736 long ceDataInode = -1; 21737 try { 21738 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21739 appId, app.seInfo, app.targetSdkVersion); 21740 } catch (InstallerException e) { 21741 if (app.isSystemApp()) { 21742 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21743 + ", but trying to recover: " + e); 21744 destroyAppDataLeafLIF(pkg, userId, flags); 21745 try { 21746 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21747 appId, app.seInfo, app.targetSdkVersion); 21748 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21749 } catch (InstallerException e2) { 21750 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21751 } 21752 } else { 21753 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21754 } 21755 } 21756 21757 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21758 // TODO: mark this structure as dirty so we persist it! 21759 synchronized (mPackages) { 21760 final PackageSetting ps = mSettings.mPackages.get(packageName); 21761 if (ps != null) { 21762 ps.setCeDataInode(ceDataInode, userId); 21763 } 21764 } 21765 } 21766 21767 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21768 } 21769 21770 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21771 if (pkg == null) { 21772 Slog.wtf(TAG, "Package was null!", new Throwable()); 21773 return; 21774 } 21775 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21776 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21777 for (int i = 0; i < childCount; i++) { 21778 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21779 } 21780 } 21781 21782 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21783 final String volumeUuid = pkg.volumeUuid; 21784 final String packageName = pkg.packageName; 21785 final ApplicationInfo app = pkg.applicationInfo; 21786 21787 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21788 // Create a native library symlink only if we have native libraries 21789 // and if the native libraries are 32 bit libraries. We do not provide 21790 // this symlink for 64 bit libraries. 21791 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21792 final String nativeLibPath = app.nativeLibraryDir; 21793 try { 21794 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21795 nativeLibPath, userId); 21796 } catch (InstallerException e) { 21797 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21798 } 21799 } 21800 } 21801 } 21802 21803 /** 21804 * For system apps on non-FBE devices, this method migrates any existing 21805 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21806 * requested by the app. 21807 */ 21808 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21809 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21810 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21811 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21812 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21813 try { 21814 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21815 storageTarget); 21816 } catch (InstallerException e) { 21817 logCriticalInfo(Log.WARN, 21818 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21819 } 21820 return true; 21821 } else { 21822 return false; 21823 } 21824 } 21825 21826 public PackageFreezer freezePackage(String packageName, String killReason) { 21827 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21828 } 21829 21830 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21831 return new PackageFreezer(packageName, userId, killReason); 21832 } 21833 21834 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21835 String killReason) { 21836 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21837 } 21838 21839 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21840 String killReason) { 21841 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21842 return new PackageFreezer(); 21843 } else { 21844 return freezePackage(packageName, userId, killReason); 21845 } 21846 } 21847 21848 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21849 String killReason) { 21850 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21851 } 21852 21853 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21854 String killReason) { 21855 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21856 return new PackageFreezer(); 21857 } else { 21858 return freezePackage(packageName, userId, killReason); 21859 } 21860 } 21861 21862 /** 21863 * Class that freezes and kills the given package upon creation, and 21864 * unfreezes it upon closing. This is typically used when doing surgery on 21865 * app code/data to prevent the app from running while you're working. 21866 */ 21867 private class PackageFreezer implements AutoCloseable { 21868 private final String mPackageName; 21869 private final PackageFreezer[] mChildren; 21870 21871 private final boolean mWeFroze; 21872 21873 private final AtomicBoolean mClosed = new AtomicBoolean(); 21874 private final CloseGuard mCloseGuard = CloseGuard.get(); 21875 21876 /** 21877 * Create and return a stub freezer that doesn't actually do anything, 21878 * typically used when someone requested 21879 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21880 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21881 */ 21882 public PackageFreezer() { 21883 mPackageName = null; 21884 mChildren = null; 21885 mWeFroze = false; 21886 mCloseGuard.open("close"); 21887 } 21888 21889 public PackageFreezer(String packageName, int userId, String killReason) { 21890 synchronized (mPackages) { 21891 mPackageName = packageName; 21892 mWeFroze = mFrozenPackages.add(mPackageName); 21893 21894 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21895 if (ps != null) { 21896 killApplication(ps.name, ps.appId, userId, killReason); 21897 } 21898 21899 final PackageParser.Package p = mPackages.get(packageName); 21900 if (p != null && p.childPackages != null) { 21901 final int N = p.childPackages.size(); 21902 mChildren = new PackageFreezer[N]; 21903 for (int i = 0; i < N; i++) { 21904 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21905 userId, killReason); 21906 } 21907 } else { 21908 mChildren = null; 21909 } 21910 } 21911 mCloseGuard.open("close"); 21912 } 21913 21914 @Override 21915 protected void finalize() throws Throwable { 21916 try { 21917 mCloseGuard.warnIfOpen(); 21918 close(); 21919 } finally { 21920 super.finalize(); 21921 } 21922 } 21923 21924 @Override 21925 public void close() { 21926 mCloseGuard.close(); 21927 if (mClosed.compareAndSet(false, true)) { 21928 synchronized (mPackages) { 21929 if (mWeFroze) { 21930 mFrozenPackages.remove(mPackageName); 21931 } 21932 21933 if (mChildren != null) { 21934 for (PackageFreezer freezer : mChildren) { 21935 freezer.close(); 21936 } 21937 } 21938 } 21939 } 21940 } 21941 } 21942 21943 /** 21944 * Verify that given package is currently frozen. 21945 */ 21946 private void checkPackageFrozen(String packageName) { 21947 synchronized (mPackages) { 21948 if (!mFrozenPackages.contains(packageName)) { 21949 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21950 } 21951 } 21952 } 21953 21954 @Override 21955 public int movePackage(final String packageName, final String volumeUuid) { 21956 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 21957 21958 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 21959 final int moveId = mNextMoveId.getAndIncrement(); 21960 mHandler.post(new Runnable() { 21961 @Override 21962 public void run() { 21963 try { 21964 movePackageInternal(packageName, volumeUuid, moveId, user); 21965 } catch (PackageManagerException e) { 21966 Slog.w(TAG, "Failed to move " + packageName, e); 21967 mMoveCallbacks.notifyStatusChanged(moveId, 21968 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 21969 } 21970 } 21971 }); 21972 return moveId; 21973 } 21974 21975 private void movePackageInternal(final String packageName, final String volumeUuid, 21976 final int moveId, UserHandle user) throws PackageManagerException { 21977 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21978 final PackageManager pm = mContext.getPackageManager(); 21979 21980 final boolean currentAsec; 21981 final String currentVolumeUuid; 21982 final File codeFile; 21983 final String installerPackageName; 21984 final String packageAbiOverride; 21985 final int appId; 21986 final String seinfo; 21987 final String label; 21988 final int targetSdkVersion; 21989 final PackageFreezer freezer; 21990 final int[] installedUserIds; 21991 21992 // reader 21993 synchronized (mPackages) { 21994 final PackageParser.Package pkg = mPackages.get(packageName); 21995 final PackageSetting ps = mSettings.mPackages.get(packageName); 21996 if (pkg == null || ps == null) { 21997 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 21998 } 21999 22000 if (pkg.applicationInfo.isSystemApp()) { 22001 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22002 "Cannot move system application"); 22003 } 22004 22005 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22006 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22007 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22008 if (isInternalStorage && !allow3rdPartyOnInternal) { 22009 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22010 "3rd party apps are not allowed on internal storage"); 22011 } 22012 22013 if (pkg.applicationInfo.isExternalAsec()) { 22014 currentAsec = true; 22015 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22016 } else if (pkg.applicationInfo.isForwardLocked()) { 22017 currentAsec = true; 22018 currentVolumeUuid = "forward_locked"; 22019 } else { 22020 currentAsec = false; 22021 currentVolumeUuid = ps.volumeUuid; 22022 22023 final File probe = new File(pkg.codePath); 22024 final File probeOat = new File(probe, "oat"); 22025 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22026 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22027 "Move only supported for modern cluster style installs"); 22028 } 22029 } 22030 22031 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22032 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22033 "Package already moved to " + volumeUuid); 22034 } 22035 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22036 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22037 "Device admin cannot be moved"); 22038 } 22039 22040 if (mFrozenPackages.contains(packageName)) { 22041 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22042 "Failed to move already frozen package"); 22043 } 22044 22045 codeFile = new File(pkg.codePath); 22046 installerPackageName = ps.installerPackageName; 22047 packageAbiOverride = ps.cpuAbiOverrideString; 22048 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22049 seinfo = pkg.applicationInfo.seInfo; 22050 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22051 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22052 freezer = freezePackage(packageName, "movePackageInternal"); 22053 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22054 } 22055 22056 final Bundle extras = new Bundle(); 22057 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22058 extras.putString(Intent.EXTRA_TITLE, label); 22059 mMoveCallbacks.notifyCreated(moveId, extras); 22060 22061 int installFlags; 22062 final boolean moveCompleteApp; 22063 final File measurePath; 22064 22065 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22066 installFlags = INSTALL_INTERNAL; 22067 moveCompleteApp = !currentAsec; 22068 measurePath = Environment.getDataAppDirectory(volumeUuid); 22069 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22070 installFlags = INSTALL_EXTERNAL; 22071 moveCompleteApp = false; 22072 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22073 } else { 22074 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22075 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22076 || !volume.isMountedWritable()) { 22077 freezer.close(); 22078 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22079 "Move location not mounted private volume"); 22080 } 22081 22082 Preconditions.checkState(!currentAsec); 22083 22084 installFlags = INSTALL_INTERNAL; 22085 moveCompleteApp = true; 22086 measurePath = Environment.getDataAppDirectory(volumeUuid); 22087 } 22088 22089 final PackageStats stats = new PackageStats(null, -1); 22090 synchronized (mInstaller) { 22091 for (int userId : installedUserIds) { 22092 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22093 freezer.close(); 22094 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22095 "Failed to measure package size"); 22096 } 22097 } 22098 } 22099 22100 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22101 + stats.dataSize); 22102 22103 final long startFreeBytes = measurePath.getFreeSpace(); 22104 final long sizeBytes; 22105 if (moveCompleteApp) { 22106 sizeBytes = stats.codeSize + stats.dataSize; 22107 } else { 22108 sizeBytes = stats.codeSize; 22109 } 22110 22111 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22112 freezer.close(); 22113 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22114 "Not enough free space to move"); 22115 } 22116 22117 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22118 22119 final CountDownLatch installedLatch = new CountDownLatch(1); 22120 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22121 @Override 22122 public void onUserActionRequired(Intent intent) throws RemoteException { 22123 throw new IllegalStateException(); 22124 } 22125 22126 @Override 22127 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22128 Bundle extras) throws RemoteException { 22129 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22130 + PackageManager.installStatusToString(returnCode, msg)); 22131 22132 installedLatch.countDown(); 22133 freezer.close(); 22134 22135 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22136 switch (status) { 22137 case PackageInstaller.STATUS_SUCCESS: 22138 mMoveCallbacks.notifyStatusChanged(moveId, 22139 PackageManager.MOVE_SUCCEEDED); 22140 break; 22141 case PackageInstaller.STATUS_FAILURE_STORAGE: 22142 mMoveCallbacks.notifyStatusChanged(moveId, 22143 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22144 break; 22145 default: 22146 mMoveCallbacks.notifyStatusChanged(moveId, 22147 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22148 break; 22149 } 22150 } 22151 }; 22152 22153 final MoveInfo move; 22154 if (moveCompleteApp) { 22155 // Kick off a thread to report progress estimates 22156 new Thread() { 22157 @Override 22158 public void run() { 22159 while (true) { 22160 try { 22161 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22162 break; 22163 } 22164 } catch (InterruptedException ignored) { 22165 } 22166 22167 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22168 final int progress = 10 + (int) MathUtils.constrain( 22169 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22170 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22171 } 22172 } 22173 }.start(); 22174 22175 final String dataAppName = codeFile.getName(); 22176 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22177 dataAppName, appId, seinfo, targetSdkVersion); 22178 } else { 22179 move = null; 22180 } 22181 22182 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22183 22184 final Message msg = mHandler.obtainMessage(INIT_COPY); 22185 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22186 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22187 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22188 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22189 PackageManager.INSTALL_REASON_UNKNOWN); 22190 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22191 msg.obj = params; 22192 22193 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22194 System.identityHashCode(msg.obj)); 22195 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22196 System.identityHashCode(msg.obj)); 22197 22198 mHandler.sendMessage(msg); 22199 } 22200 22201 @Override 22202 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22204 22205 final int realMoveId = mNextMoveId.getAndIncrement(); 22206 final Bundle extras = new Bundle(); 22207 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22208 mMoveCallbacks.notifyCreated(realMoveId, extras); 22209 22210 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22211 @Override 22212 public void onCreated(int moveId, Bundle extras) { 22213 // Ignored 22214 } 22215 22216 @Override 22217 public void onStatusChanged(int moveId, int status, long estMillis) { 22218 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22219 } 22220 }; 22221 22222 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22223 storage.setPrimaryStorageUuid(volumeUuid, callback); 22224 return realMoveId; 22225 } 22226 22227 @Override 22228 public int getMoveStatus(int moveId) { 22229 mContext.enforceCallingOrSelfPermission( 22230 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22231 return mMoveCallbacks.mLastStatus.get(moveId); 22232 } 22233 22234 @Override 22235 public void registerMoveCallback(IPackageMoveObserver callback) { 22236 mContext.enforceCallingOrSelfPermission( 22237 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22238 mMoveCallbacks.register(callback); 22239 } 22240 22241 @Override 22242 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22243 mContext.enforceCallingOrSelfPermission( 22244 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22245 mMoveCallbacks.unregister(callback); 22246 } 22247 22248 @Override 22249 public boolean setInstallLocation(int loc) { 22250 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22251 null); 22252 if (getInstallLocation() == loc) { 22253 return true; 22254 } 22255 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22256 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22257 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22258 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22259 return true; 22260 } 22261 return false; 22262 } 22263 22264 @Override 22265 public int getInstallLocation() { 22266 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22267 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22268 PackageHelper.APP_INSTALL_AUTO); 22269 } 22270 22271 /** Called by UserManagerService */ 22272 void cleanUpUser(UserManagerService userManager, int userHandle) { 22273 synchronized (mPackages) { 22274 mDirtyUsers.remove(userHandle); 22275 mUserNeedsBadging.delete(userHandle); 22276 mSettings.removeUserLPw(userHandle); 22277 mPendingBroadcasts.remove(userHandle); 22278 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22279 removeUnusedPackagesLPw(userManager, userHandle); 22280 } 22281 } 22282 22283 /** 22284 * We're removing userHandle and would like to remove any downloaded packages 22285 * that are no longer in use by any other user. 22286 * @param userHandle the user being removed 22287 */ 22288 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22289 final boolean DEBUG_CLEAN_APKS = false; 22290 int [] users = userManager.getUserIds(); 22291 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22292 while (psit.hasNext()) { 22293 PackageSetting ps = psit.next(); 22294 if (ps.pkg == null) { 22295 continue; 22296 } 22297 final String packageName = ps.pkg.packageName; 22298 // Skip over if system app 22299 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22300 continue; 22301 } 22302 if (DEBUG_CLEAN_APKS) { 22303 Slog.i(TAG, "Checking package " + packageName); 22304 } 22305 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22306 if (keep) { 22307 if (DEBUG_CLEAN_APKS) { 22308 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22309 } 22310 } else { 22311 for (int i = 0; i < users.length; i++) { 22312 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22313 keep = true; 22314 if (DEBUG_CLEAN_APKS) { 22315 Slog.i(TAG, " Keeping package " + packageName + " for user " 22316 + users[i]); 22317 } 22318 break; 22319 } 22320 } 22321 } 22322 if (!keep) { 22323 if (DEBUG_CLEAN_APKS) { 22324 Slog.i(TAG, " Removing package " + packageName); 22325 } 22326 mHandler.post(new Runnable() { 22327 public void run() { 22328 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22329 userHandle, 0); 22330 } //end run 22331 }); 22332 } 22333 } 22334 } 22335 22336 /** Called by UserManagerService */ 22337 void createNewUser(int userId, String[] disallowedPackages) { 22338 synchronized (mInstallLock) { 22339 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22340 } 22341 synchronized (mPackages) { 22342 scheduleWritePackageRestrictionsLocked(userId); 22343 scheduleWritePackageListLocked(userId); 22344 applyFactoryDefaultBrowserLPw(userId); 22345 primeDomainVerificationsLPw(userId); 22346 } 22347 } 22348 22349 void onNewUserCreated(final int userId) { 22350 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22351 // If permission review for legacy apps is required, we represent 22352 // dagerous permissions for such apps as always granted runtime 22353 // permissions to keep per user flag state whether review is needed. 22354 // Hence, if a new user is added we have to propagate dangerous 22355 // permission grants for these legacy apps. 22356 if (mPermissionReviewRequired) { 22357 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22358 | UPDATE_PERMISSIONS_REPLACE_ALL); 22359 } 22360 } 22361 22362 @Override 22363 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22364 mContext.enforceCallingOrSelfPermission( 22365 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22366 "Only package verification agents can read the verifier device identity"); 22367 22368 synchronized (mPackages) { 22369 return mSettings.getVerifierDeviceIdentityLPw(); 22370 } 22371 } 22372 22373 @Override 22374 public void setPermissionEnforced(String permission, boolean enforced) { 22375 // TODO: Now that we no longer change GID for storage, this should to away. 22376 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22377 "setPermissionEnforced"); 22378 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22379 synchronized (mPackages) { 22380 if (mSettings.mReadExternalStorageEnforced == null 22381 || mSettings.mReadExternalStorageEnforced != enforced) { 22382 mSettings.mReadExternalStorageEnforced = enforced; 22383 mSettings.writeLPr(); 22384 } 22385 } 22386 // kill any non-foreground processes so we restart them and 22387 // grant/revoke the GID. 22388 final IActivityManager am = ActivityManager.getService(); 22389 if (am != null) { 22390 final long token = Binder.clearCallingIdentity(); 22391 try { 22392 am.killProcessesBelowForeground("setPermissionEnforcement"); 22393 } catch (RemoteException e) { 22394 } finally { 22395 Binder.restoreCallingIdentity(token); 22396 } 22397 } 22398 } else { 22399 throw new IllegalArgumentException("No selective enforcement for " + permission); 22400 } 22401 } 22402 22403 @Override 22404 @Deprecated 22405 public boolean isPermissionEnforced(String permission) { 22406 return true; 22407 } 22408 22409 @Override 22410 public boolean isStorageLow() { 22411 final long token = Binder.clearCallingIdentity(); 22412 try { 22413 final DeviceStorageMonitorInternal 22414 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22415 if (dsm != null) { 22416 return dsm.isMemoryLow(); 22417 } else { 22418 return false; 22419 } 22420 } finally { 22421 Binder.restoreCallingIdentity(token); 22422 } 22423 } 22424 22425 @Override 22426 public IPackageInstaller getPackageInstaller() { 22427 return mInstallerService; 22428 } 22429 22430 private boolean userNeedsBadging(int userId) { 22431 int index = mUserNeedsBadging.indexOfKey(userId); 22432 if (index < 0) { 22433 final UserInfo userInfo; 22434 final long token = Binder.clearCallingIdentity(); 22435 try { 22436 userInfo = sUserManager.getUserInfo(userId); 22437 } finally { 22438 Binder.restoreCallingIdentity(token); 22439 } 22440 final boolean b; 22441 if (userInfo != null && userInfo.isManagedProfile()) { 22442 b = true; 22443 } else { 22444 b = false; 22445 } 22446 mUserNeedsBadging.put(userId, b); 22447 return b; 22448 } 22449 return mUserNeedsBadging.valueAt(index); 22450 } 22451 22452 @Override 22453 public KeySet getKeySetByAlias(String packageName, String alias) { 22454 if (packageName == null || alias == null) { 22455 return null; 22456 } 22457 synchronized(mPackages) { 22458 final PackageParser.Package pkg = mPackages.get(packageName); 22459 if (pkg == null) { 22460 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22461 throw new IllegalArgumentException("Unknown package: " + packageName); 22462 } 22463 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22464 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22465 } 22466 } 22467 22468 @Override 22469 public KeySet getSigningKeySet(String packageName) { 22470 if (packageName == null) { 22471 return null; 22472 } 22473 synchronized(mPackages) { 22474 final PackageParser.Package pkg = mPackages.get(packageName); 22475 if (pkg == null) { 22476 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22477 throw new IllegalArgumentException("Unknown package: " + packageName); 22478 } 22479 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22480 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22481 throw new SecurityException("May not access signing KeySet of other apps."); 22482 } 22483 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22484 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22485 } 22486 } 22487 22488 @Override 22489 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22490 if (packageName == null || ks == null) { 22491 return false; 22492 } 22493 synchronized(mPackages) { 22494 final PackageParser.Package pkg = mPackages.get(packageName); 22495 if (pkg == null) { 22496 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22497 throw new IllegalArgumentException("Unknown package: " + packageName); 22498 } 22499 IBinder ksh = ks.getToken(); 22500 if (ksh instanceof KeySetHandle) { 22501 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22502 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22503 } 22504 return false; 22505 } 22506 } 22507 22508 @Override 22509 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22510 if (packageName == null || ks == null) { 22511 return false; 22512 } 22513 synchronized(mPackages) { 22514 final PackageParser.Package pkg = mPackages.get(packageName); 22515 if (pkg == null) { 22516 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22517 throw new IllegalArgumentException("Unknown package: " + packageName); 22518 } 22519 IBinder ksh = ks.getToken(); 22520 if (ksh instanceof KeySetHandle) { 22521 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22522 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22523 } 22524 return false; 22525 } 22526 } 22527 22528 private void deletePackageIfUnusedLPr(final String packageName) { 22529 PackageSetting ps = mSettings.mPackages.get(packageName); 22530 if (ps == null) { 22531 return; 22532 } 22533 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22534 // TODO Implement atomic delete if package is unused 22535 // It is currently possible that the package will be deleted even if it is installed 22536 // after this method returns. 22537 mHandler.post(new Runnable() { 22538 public void run() { 22539 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22540 0, PackageManager.DELETE_ALL_USERS); 22541 } 22542 }); 22543 } 22544 } 22545 22546 /** 22547 * Check and throw if the given before/after packages would be considered a 22548 * downgrade. 22549 */ 22550 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22551 throws PackageManagerException { 22552 if (after.versionCode < before.mVersionCode) { 22553 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22554 "Update version code " + after.versionCode + " is older than current " 22555 + before.mVersionCode); 22556 } else if (after.versionCode == before.mVersionCode) { 22557 if (after.baseRevisionCode < before.baseRevisionCode) { 22558 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22559 "Update base revision code " + after.baseRevisionCode 22560 + " is older than current " + before.baseRevisionCode); 22561 } 22562 22563 if (!ArrayUtils.isEmpty(after.splitNames)) { 22564 for (int i = 0; i < after.splitNames.length; i++) { 22565 final String splitName = after.splitNames[i]; 22566 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22567 if (j != -1) { 22568 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22569 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22570 "Update split " + splitName + " revision code " 22571 + after.splitRevisionCodes[i] + " is older than current " 22572 + before.splitRevisionCodes[j]); 22573 } 22574 } 22575 } 22576 } 22577 } 22578 } 22579 22580 private static class MoveCallbacks extends Handler { 22581 private static final int MSG_CREATED = 1; 22582 private static final int MSG_STATUS_CHANGED = 2; 22583 22584 private final RemoteCallbackList<IPackageMoveObserver> 22585 mCallbacks = new RemoteCallbackList<>(); 22586 22587 private final SparseIntArray mLastStatus = new SparseIntArray(); 22588 22589 public MoveCallbacks(Looper looper) { 22590 super(looper); 22591 } 22592 22593 public void register(IPackageMoveObserver callback) { 22594 mCallbacks.register(callback); 22595 } 22596 22597 public void unregister(IPackageMoveObserver callback) { 22598 mCallbacks.unregister(callback); 22599 } 22600 22601 @Override 22602 public void handleMessage(Message msg) { 22603 final SomeArgs args = (SomeArgs) msg.obj; 22604 final int n = mCallbacks.beginBroadcast(); 22605 for (int i = 0; i < n; i++) { 22606 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22607 try { 22608 invokeCallback(callback, msg.what, args); 22609 } catch (RemoteException ignored) { 22610 } 22611 } 22612 mCallbacks.finishBroadcast(); 22613 args.recycle(); 22614 } 22615 22616 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22617 throws RemoteException { 22618 switch (what) { 22619 case MSG_CREATED: { 22620 callback.onCreated(args.argi1, (Bundle) args.arg2); 22621 break; 22622 } 22623 case MSG_STATUS_CHANGED: { 22624 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22625 break; 22626 } 22627 } 22628 } 22629 22630 private void notifyCreated(int moveId, Bundle extras) { 22631 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22632 22633 final SomeArgs args = SomeArgs.obtain(); 22634 args.argi1 = moveId; 22635 args.arg2 = extras; 22636 obtainMessage(MSG_CREATED, args).sendToTarget(); 22637 } 22638 22639 private void notifyStatusChanged(int moveId, int status) { 22640 notifyStatusChanged(moveId, status, -1); 22641 } 22642 22643 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22644 Slog.v(TAG, "Move " + moveId + " status " + status); 22645 22646 final SomeArgs args = SomeArgs.obtain(); 22647 args.argi1 = moveId; 22648 args.argi2 = status; 22649 args.arg3 = estMillis; 22650 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22651 22652 synchronized (mLastStatus) { 22653 mLastStatus.put(moveId, status); 22654 } 22655 } 22656 } 22657 22658 private final static class OnPermissionChangeListeners extends Handler { 22659 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22660 22661 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22662 new RemoteCallbackList<>(); 22663 22664 public OnPermissionChangeListeners(Looper looper) { 22665 super(looper); 22666 } 22667 22668 @Override 22669 public void handleMessage(Message msg) { 22670 switch (msg.what) { 22671 case MSG_ON_PERMISSIONS_CHANGED: { 22672 final int uid = msg.arg1; 22673 handleOnPermissionsChanged(uid); 22674 } break; 22675 } 22676 } 22677 22678 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22679 mPermissionListeners.register(listener); 22680 22681 } 22682 22683 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22684 mPermissionListeners.unregister(listener); 22685 } 22686 22687 public void onPermissionsChanged(int uid) { 22688 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22689 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22690 } 22691 } 22692 22693 private void handleOnPermissionsChanged(int uid) { 22694 final int count = mPermissionListeners.beginBroadcast(); 22695 try { 22696 for (int i = 0; i < count; i++) { 22697 IOnPermissionsChangeListener callback = mPermissionListeners 22698 .getBroadcastItem(i); 22699 try { 22700 callback.onPermissionsChanged(uid); 22701 } catch (RemoteException e) { 22702 Log.e(TAG, "Permission listener is dead", e); 22703 } 22704 } 22705 } finally { 22706 mPermissionListeners.finishBroadcast(); 22707 } 22708 } 22709 } 22710 22711 private class PackageManagerInternalImpl extends PackageManagerInternal { 22712 @Override 22713 public void setLocationPackagesProvider(PackagesProvider provider) { 22714 synchronized (mPackages) { 22715 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22716 } 22717 } 22718 22719 @Override 22720 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22721 synchronized (mPackages) { 22722 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22723 } 22724 } 22725 22726 @Override 22727 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22728 synchronized (mPackages) { 22729 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22730 } 22731 } 22732 22733 @Override 22734 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22735 synchronized (mPackages) { 22736 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22737 } 22738 } 22739 22740 @Override 22741 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22742 synchronized (mPackages) { 22743 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22744 } 22745 } 22746 22747 @Override 22748 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22749 synchronized (mPackages) { 22750 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22751 } 22752 } 22753 22754 @Override 22755 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22756 synchronized (mPackages) { 22757 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22758 packageName, userId); 22759 } 22760 } 22761 22762 @Override 22763 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22764 synchronized (mPackages) { 22765 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22766 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22767 packageName, userId); 22768 } 22769 } 22770 22771 @Override 22772 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22773 synchronized (mPackages) { 22774 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22775 packageName, userId); 22776 } 22777 } 22778 22779 @Override 22780 public void setKeepUninstalledPackages(final List<String> packageList) { 22781 Preconditions.checkNotNull(packageList); 22782 List<String> removedFromList = null; 22783 synchronized (mPackages) { 22784 if (mKeepUninstalledPackages != null) { 22785 final int packagesCount = mKeepUninstalledPackages.size(); 22786 for (int i = 0; i < packagesCount; i++) { 22787 String oldPackage = mKeepUninstalledPackages.get(i); 22788 if (packageList != null && packageList.contains(oldPackage)) { 22789 continue; 22790 } 22791 if (removedFromList == null) { 22792 removedFromList = new ArrayList<>(); 22793 } 22794 removedFromList.add(oldPackage); 22795 } 22796 } 22797 mKeepUninstalledPackages = new ArrayList<>(packageList); 22798 if (removedFromList != null) { 22799 final int removedCount = removedFromList.size(); 22800 for (int i = 0; i < removedCount; i++) { 22801 deletePackageIfUnusedLPr(removedFromList.get(i)); 22802 } 22803 } 22804 } 22805 } 22806 22807 @Override 22808 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22809 synchronized (mPackages) { 22810 // If we do not support permission review, done. 22811 if (!mPermissionReviewRequired) { 22812 return false; 22813 } 22814 22815 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22816 if (packageSetting == null) { 22817 return false; 22818 } 22819 22820 // Permission review applies only to apps not supporting the new permission model. 22821 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22822 return false; 22823 } 22824 22825 // Legacy apps have the permission and get user consent on launch. 22826 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22827 return permissionsState.isPermissionReviewRequired(userId); 22828 } 22829 } 22830 22831 @Override 22832 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22833 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22834 } 22835 22836 @Override 22837 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22838 int userId) { 22839 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22840 } 22841 22842 @Override 22843 public void setDeviceAndProfileOwnerPackages( 22844 int deviceOwnerUserId, String deviceOwnerPackage, 22845 SparseArray<String> profileOwnerPackages) { 22846 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22847 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22848 } 22849 22850 @Override 22851 public boolean isPackageDataProtected(int userId, String packageName) { 22852 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22853 } 22854 22855 @Override 22856 public boolean isPackageEphemeral(int userId, String packageName) { 22857 synchronized (mPackages) { 22858 final PackageSetting ps = mSettings.mPackages.get(packageName); 22859 return ps != null ? ps.getInstantApp(userId) : false; 22860 } 22861 } 22862 22863 @Override 22864 public boolean wasPackageEverLaunched(String packageName, int userId) { 22865 synchronized (mPackages) { 22866 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22867 } 22868 } 22869 22870 @Override 22871 public void grantRuntimePermission(String packageName, String name, int userId, 22872 boolean overridePolicy) { 22873 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22874 overridePolicy); 22875 } 22876 22877 @Override 22878 public void revokeRuntimePermission(String packageName, String name, int userId, 22879 boolean overridePolicy) { 22880 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22881 overridePolicy); 22882 } 22883 22884 @Override 22885 public String getNameForUid(int uid) { 22886 return PackageManagerService.this.getNameForUid(uid); 22887 } 22888 22889 @Override 22890 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 22891 Intent origIntent, String resolvedType, Intent launchIntent, 22892 String callingPackage, int userId) { 22893 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 22894 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 22895 } 22896 22897 @Override 22898 public void grantEphemeralAccess(int userId, Intent intent, 22899 int targetAppId, int ephemeralAppId) { 22900 synchronized (mPackages) { 22901 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22902 targetAppId, ephemeralAppId); 22903 } 22904 } 22905 22906 @Override 22907 public void pruneInstantApps() { 22908 synchronized (mPackages) { 22909 mInstantAppRegistry.pruneInstantAppsLPw(); 22910 } 22911 } 22912 22913 @Override 22914 public String getSetupWizardPackageName() { 22915 return mSetupWizardPackage; 22916 } 22917 22918 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22919 if (policy != null) { 22920 mExternalSourcesPolicy = policy; 22921 } 22922 } 22923 22924 @Override 22925 public boolean isPackagePersistent(String packageName) { 22926 synchronized (mPackages) { 22927 PackageParser.Package pkg = mPackages.get(packageName); 22928 return pkg != null 22929 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 22930 | ApplicationInfo.FLAG_PERSISTENT)) == 22931 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 22932 : false; 22933 } 22934 } 22935 22936 @Override 22937 public List<PackageInfo> getOverlayPackages(int userId) { 22938 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 22939 synchronized (mPackages) { 22940 for (PackageParser.Package p : mPackages.values()) { 22941 if (p.mOverlayTarget != null) { 22942 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 22943 if (pkg != null) { 22944 overlayPackages.add(pkg); 22945 } 22946 } 22947 } 22948 } 22949 return overlayPackages; 22950 } 22951 22952 @Override 22953 public List<String> getTargetPackageNames(int userId) { 22954 List<String> targetPackages = new ArrayList<>(); 22955 synchronized (mPackages) { 22956 for (PackageParser.Package p : mPackages.values()) { 22957 if (p.mOverlayTarget == null) { 22958 targetPackages.add(p.packageName); 22959 } 22960 } 22961 } 22962 return targetPackages; 22963 } 22964 22965 22966 @Override 22967 public boolean setEnabledOverlayPackages(int userId, String targetPackageName, 22968 List<String> overlayPackageNames) { 22969 // TODO: implement when we integrate OMS properly 22970 return false; 22971 } 22972 } 22973 22974 @Override 22975 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 22976 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 22977 synchronized (mPackages) { 22978 final long identity = Binder.clearCallingIdentity(); 22979 try { 22980 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 22981 packageNames, userId); 22982 } finally { 22983 Binder.restoreCallingIdentity(identity); 22984 } 22985 } 22986 } 22987 22988 @Override 22989 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 22990 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 22991 synchronized (mPackages) { 22992 final long identity = Binder.clearCallingIdentity(); 22993 try { 22994 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 22995 packageNames, userId); 22996 } finally { 22997 Binder.restoreCallingIdentity(identity); 22998 } 22999 } 23000 } 23001 23002 private static void enforceSystemOrPhoneCaller(String tag) { 23003 int callingUid = Binder.getCallingUid(); 23004 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23005 throw new SecurityException( 23006 "Cannot call " + tag + " from UID " + callingUid); 23007 } 23008 } 23009 23010 boolean isHistoricalPackageUsageAvailable() { 23011 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23012 } 23013 23014 /** 23015 * Return a <b>copy</b> of the collection of packages known to the package manager. 23016 * @return A copy of the values of mPackages. 23017 */ 23018 Collection<PackageParser.Package> getPackages() { 23019 synchronized (mPackages) { 23020 return new ArrayList<>(mPackages.values()); 23021 } 23022 } 23023 23024 /** 23025 * Logs process start information (including base APK hash) to the security log. 23026 * @hide 23027 */ 23028 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23029 String apkFile, int pid) { 23030 if (!SecurityLog.isLoggingEnabled()) { 23031 return; 23032 } 23033 Bundle data = new Bundle(); 23034 data.putLong("startTimestamp", System.currentTimeMillis()); 23035 data.putString("processName", processName); 23036 data.putInt("uid", uid); 23037 data.putString("seinfo", seinfo); 23038 data.putString("apkFile", apkFile); 23039 data.putInt("pid", pid); 23040 Message msg = mProcessLoggingHandler.obtainMessage( 23041 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23042 msg.setData(data); 23043 mProcessLoggingHandler.sendMessage(msg); 23044 } 23045 23046 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23047 return mCompilerStats.getPackageStats(pkgName); 23048 } 23049 23050 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23051 return getOrCreateCompilerPackageStats(pkg.packageName); 23052 } 23053 23054 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23055 return mCompilerStats.getOrCreatePackageStats(pkgName); 23056 } 23057 23058 public void deleteCompilerPackageStats(String pkgName) { 23059 mCompilerStats.deletePackageStats(pkgName); 23060 } 23061 23062 @Override 23063 public int getInstallReason(String packageName, int userId) { 23064 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23065 true /* requireFullPermission */, false /* checkShell */, 23066 "get install reason"); 23067 synchronized (mPackages) { 23068 final PackageSetting ps = mSettings.mPackages.get(packageName); 23069 if (ps != null) { 23070 return ps.getInstallReason(userId); 23071 } 23072 } 23073 return PackageManager.INSTALL_REASON_UNKNOWN; 23074 } 23075 23076 @Override 23077 public boolean canRequestPackageInstalls(String packageName, int userId) { 23078 int callingUid = Binder.getCallingUid(); 23079 int uid = getPackageUid(packageName, 0, userId); 23080 if (callingUid != uid && callingUid != Process.ROOT_UID 23081 && callingUid != Process.SYSTEM_UID) { 23082 throw new SecurityException( 23083 "Caller uid " + callingUid + " does not own package " + packageName); 23084 } 23085 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23086 if (info == null) { 23087 return false; 23088 } 23089 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23090 throw new UnsupportedOperationException( 23091 "Operation only supported on apps targeting Android O or higher"); 23092 } 23093 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23094 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23095 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23096 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23097 } 23098 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23099 return false; 23100 } 23101 if (mExternalSourcesPolicy != null) { 23102 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23103 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23104 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23105 } 23106 } 23107 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23108 } 23109} 23110