PackageManagerService.java revision d143808365c06be7e64837d005d07e91ebfad745
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.AuxiliaryResolveInfo; 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.ConcurrentUtils; 255import com.android.internal.util.FastPrintWriter; 256import com.android.internal.util.FastXmlSerializer; 257import com.android.internal.util.IndentingPrintWriter; 258import com.android.internal.util.Preconditions; 259import com.android.internal.util.XmlUtils; 260import com.android.server.AttributeCache; 261import com.android.server.BackgroundDexOptJobService; 262import com.android.server.DeviceIdleController; 263import com.android.server.EventLogTags; 264import com.android.server.FgThread; 265import com.android.server.IntentResolver; 266import com.android.server.LocalServices; 267import com.android.server.ServiceThread; 268import com.android.server.SystemConfig; 269import com.android.server.SystemServerInitThreadPool; 270import com.android.server.Watchdog; 271import com.android.server.net.NetworkPolicyManagerInternal; 272import com.android.server.pm.Installer.InstallerException; 273import com.android.server.pm.PermissionsState.PermissionState; 274import com.android.server.pm.Settings.DatabaseVersion; 275import com.android.server.pm.Settings.VersionInfo; 276import com.android.server.pm.dex.DexManager; 277import com.android.server.storage.DeviceStorageMonitorInternal; 278 279import dalvik.system.CloseGuard; 280import dalvik.system.DexFile; 281import dalvik.system.VMRuntime; 282 283import libcore.io.IoUtils; 284import libcore.util.EmptyArray; 285 286import org.xmlpull.v1.XmlPullParser; 287import org.xmlpull.v1.XmlPullParserException; 288import org.xmlpull.v1.XmlSerializer; 289 290import java.io.BufferedOutputStream; 291import java.io.BufferedReader; 292import java.io.ByteArrayInputStream; 293import java.io.ByteArrayOutputStream; 294import java.io.File; 295import java.io.FileDescriptor; 296import java.io.FileInputStream; 297import java.io.FileNotFoundException; 298import java.io.FileOutputStream; 299import java.io.FileReader; 300import java.io.FilenameFilter; 301import java.io.IOException; 302import java.io.PrintWriter; 303import java.nio.charset.StandardCharsets; 304import java.security.DigestInputStream; 305import java.security.MessageDigest; 306import java.security.NoSuchAlgorithmException; 307import java.security.PublicKey; 308import java.security.SecureRandom; 309import java.security.cert.Certificate; 310import java.security.cert.CertificateEncodingException; 311import java.security.cert.CertificateException; 312import java.text.SimpleDateFormat; 313import java.util.ArrayList; 314import java.util.Arrays; 315import java.util.Collection; 316import java.util.Collections; 317import java.util.Comparator; 318import java.util.Date; 319import java.util.HashSet; 320import java.util.HashMap; 321import java.util.Iterator; 322import java.util.List; 323import java.util.Map; 324import java.util.Objects; 325import java.util.Set; 326import java.util.concurrent.CountDownLatch; 327import java.util.concurrent.Future; 328import java.util.concurrent.TimeUnit; 329import java.util.concurrent.atomic.AtomicBoolean; 330import java.util.concurrent.atomic.AtomicInteger; 331 332/** 333 * Keep track of all those APKs everywhere. 334 * <p> 335 * Internally there are two important locks: 336 * <ul> 337 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 338 * and other related state. It is a fine-grained lock that should only be held 339 * momentarily, as it's one of the most contended locks in the system. 340 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 341 * operations typically involve heavy lifting of application data on disk. Since 342 * {@code installd} is single-threaded, and it's operations can often be slow, 343 * this lock should never be acquired while already holding {@link #mPackages}. 344 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 345 * holding {@link #mInstallLock}. 346 * </ul> 347 * Many internal methods rely on the caller to hold the appropriate locks, and 348 * this contract is expressed through method name suffixes: 349 * <ul> 350 * <li>fooLI(): the caller must hold {@link #mInstallLock} 351 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 352 * being modified must be frozen 353 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 354 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 355 * </ul> 356 * <p> 357 * Because this class is very central to the platform's security; please run all 358 * CTS and unit tests whenever making modifications: 359 * 360 * <pre> 361 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 362 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 363 * </pre> 364 */ 365public class PackageManagerService extends IPackageManager.Stub { 366 static final String TAG = "PackageManager"; 367 static final boolean DEBUG_SETTINGS = false; 368 static final boolean DEBUG_PREFERRED = false; 369 static final boolean DEBUG_UPGRADE = false; 370 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 371 private static final boolean DEBUG_BACKUP = false; 372 private static final boolean DEBUG_INSTALL = false; 373 private static final boolean DEBUG_REMOVE = false; 374 private static final boolean DEBUG_BROADCASTS = false; 375 private static final boolean DEBUG_SHOW_INFO = false; 376 private static final boolean DEBUG_PACKAGE_INFO = false; 377 private static final boolean DEBUG_INTENT_MATCHING = false; 378 private static final boolean DEBUG_PACKAGE_SCANNING = false; 379 private static final boolean DEBUG_VERIFY = false; 380 private static final boolean DEBUG_FILTERS = false; 381 382 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 383 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 384 // user, but by default initialize to this. 385 public static final boolean DEBUG_DEXOPT = false; 386 387 private static final boolean DEBUG_ABI_SELECTION = false; 388 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 389 private static final boolean DEBUG_TRIAGED_MISSING = false; 390 private static final boolean DEBUG_APP_DATA = false; 391 392 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 393 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 394 395 private static final boolean DISABLE_EPHEMERAL_APPS = false; 396 private static final boolean HIDE_EPHEMERAL_APIS = false; 397 398 private static final boolean ENABLE_FREE_CACHE_V2 = 399 SystemProperties.getBoolean("fw.free_cache_v2", false); 400 401 private static final int RADIO_UID = Process.PHONE_UID; 402 private static final int LOG_UID = Process.LOG_UID; 403 private static final int NFC_UID = Process.NFC_UID; 404 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 405 private static final int SHELL_UID = Process.SHELL_UID; 406 407 // Cap the size of permission trees that 3rd party apps can define 408 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 409 410 // Suffix used during package installation when copying/moving 411 // package apks to install directory. 412 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 413 414 static final int SCAN_NO_DEX = 1<<1; 415 static final int SCAN_FORCE_DEX = 1<<2; 416 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 417 static final int SCAN_NEW_INSTALL = 1<<4; 418 static final int SCAN_UPDATE_TIME = 1<<5; 419 static final int SCAN_BOOTING = 1<<6; 420 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 421 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 422 static final int SCAN_REPLACING = 1<<9; 423 static final int SCAN_REQUIRE_KNOWN = 1<<10; 424 static final int SCAN_MOVE = 1<<11; 425 static final int SCAN_INITIAL = 1<<12; 426 static final int SCAN_CHECK_ONLY = 1<<13; 427 static final int SCAN_DONT_KILL_APP = 1<<14; 428 static final int SCAN_IGNORE_FROZEN = 1<<15; 429 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 430 static final int SCAN_AS_INSTANT_APP = 1<<17; 431 static final int SCAN_AS_FULL_APP = 1<<18; 432 /** Should not be with the scan flags */ 433 static final int FLAGS_REMOVE_CHATTY = 1<<31; 434 435 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 436 437 private static final int[] EMPTY_INT_ARRAY = new int[0]; 438 439 /** 440 * Timeout (in milliseconds) after which the watchdog should declare that 441 * our handler thread is wedged. The usual default for such things is one 442 * minute but we sometimes do very lengthy I/O operations on this thread, 443 * such as installing multi-gigabyte applications, so ours needs to be longer. 444 */ 445 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 446 447 /** 448 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 449 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 450 * settings entry if available, otherwise we use the hardcoded default. If it's been 451 * more than this long since the last fstrim, we force one during the boot sequence. 452 * 453 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 454 * one gets run at the next available charging+idle time. This final mandatory 455 * no-fstrim check kicks in only of the other scheduling criteria is never met. 456 */ 457 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 458 459 /** 460 * Whether verification is enabled by default. 461 */ 462 private static final boolean DEFAULT_VERIFY_ENABLE = true; 463 464 /** 465 * The default maximum time to wait for the verification agent to return in 466 * milliseconds. 467 */ 468 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 469 470 /** 471 * The default response for package verification timeout. 472 * 473 * This can be either PackageManager.VERIFICATION_ALLOW or 474 * PackageManager.VERIFICATION_REJECT. 475 */ 476 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 477 478 static final String PLATFORM_PACKAGE_NAME = "android"; 479 480 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 481 482 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 483 DEFAULT_CONTAINER_PACKAGE, 484 "com.android.defcontainer.DefaultContainerService"); 485 486 private static final String KILL_APP_REASON_GIDS_CHANGED = 487 "permission grant or revoke changed gids"; 488 489 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 490 "permissions revoked"; 491 492 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 493 494 private static final String PACKAGE_SCHEME = "package"; 495 496 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 497 /** 498 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 499 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 500 * VENDOR_OVERLAY_DIR. 501 */ 502 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 503 /** 504 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 505 * is in VENDOR_OVERLAY_THEME_PROPERTY. 506 */ 507 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 508 = "persist.vendor.overlay.theme"; 509 510 /** Permission grant: not grant the permission. */ 511 private static final int GRANT_DENIED = 1; 512 513 /** Permission grant: grant the permission as an install permission. */ 514 private static final int GRANT_INSTALL = 2; 515 516 /** Permission grant: grant the permission as a runtime one. */ 517 private static final int GRANT_RUNTIME = 3; 518 519 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 520 private static final int GRANT_UPGRADE = 4; 521 522 /** Canonical intent used to identify what counts as a "web browser" app */ 523 private static final Intent sBrowserIntent; 524 static { 525 sBrowserIntent = new Intent(); 526 sBrowserIntent.setAction(Intent.ACTION_VIEW); 527 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 528 sBrowserIntent.setData(Uri.parse("http:")); 529 } 530 531 /** 532 * The set of all protected actions [i.e. those actions for which a high priority 533 * intent filter is disallowed]. 534 */ 535 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 536 static { 537 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 538 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 539 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 540 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 541 } 542 543 // Compilation reasons. 544 public static final int REASON_FIRST_BOOT = 0; 545 public static final int REASON_BOOT = 1; 546 public static final int REASON_INSTALL = 2; 547 public static final int REASON_BACKGROUND_DEXOPT = 3; 548 public static final int REASON_AB_OTA = 4; 549 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 550 public static final int REASON_SHARED_APK = 6; 551 public static final int REASON_FORCED_DEXOPT = 7; 552 public static final int REASON_CORE_APP = 8; 553 554 public static final int REASON_LAST = REASON_CORE_APP; 555 556 /** All dangerous permission names in the same order as the events in MetricsEvent */ 557 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 558 Manifest.permission.READ_CALENDAR, 559 Manifest.permission.WRITE_CALENDAR, 560 Manifest.permission.CAMERA, 561 Manifest.permission.READ_CONTACTS, 562 Manifest.permission.WRITE_CONTACTS, 563 Manifest.permission.GET_ACCOUNTS, 564 Manifest.permission.ACCESS_FINE_LOCATION, 565 Manifest.permission.ACCESS_COARSE_LOCATION, 566 Manifest.permission.RECORD_AUDIO, 567 Manifest.permission.READ_PHONE_STATE, 568 Manifest.permission.CALL_PHONE, 569 Manifest.permission.READ_CALL_LOG, 570 Manifest.permission.WRITE_CALL_LOG, 571 Manifest.permission.ADD_VOICEMAIL, 572 Manifest.permission.USE_SIP, 573 Manifest.permission.PROCESS_OUTGOING_CALLS, 574 Manifest.permission.READ_CELL_BROADCASTS, 575 Manifest.permission.BODY_SENSORS, 576 Manifest.permission.SEND_SMS, 577 Manifest.permission.RECEIVE_SMS, 578 Manifest.permission.READ_SMS, 579 Manifest.permission.RECEIVE_WAP_PUSH, 580 Manifest.permission.RECEIVE_MMS, 581 Manifest.permission.READ_EXTERNAL_STORAGE, 582 Manifest.permission.WRITE_EXTERNAL_STORAGE, 583 Manifest.permission.READ_PHONE_NUMBER); 584 585 586 /** 587 * Version number for the package parser cache. Increment this whenever the format or 588 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 589 */ 590 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 591 592 /** 593 * Whether the package parser cache is enabled. 594 */ 595 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 596 597 final ServiceThread mHandlerThread; 598 599 final PackageHandler mHandler; 600 601 private final ProcessLoggingHandler mProcessLoggingHandler; 602 603 /** 604 * Messages for {@link #mHandler} that need to wait for system ready before 605 * being dispatched. 606 */ 607 private ArrayList<Message> mPostSystemReadyMessages; 608 609 final int mSdkVersion = Build.VERSION.SDK_INT; 610 611 final Context mContext; 612 final boolean mFactoryTest; 613 final boolean mOnlyCore; 614 final DisplayMetrics mMetrics; 615 final int mDefParseFlags; 616 final String[] mSeparateProcesses; 617 final boolean mIsUpgrade; 618 final boolean mIsPreNUpgrade; 619 final boolean mIsPreNMR1Upgrade; 620 621 @GuardedBy("mPackages") 622 private boolean mDexOptDialogShown; 623 624 /** The location for ASEC container files on internal storage. */ 625 final String mAsecInternalPath; 626 627 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 628 // LOCK HELD. Can be called with mInstallLock held. 629 @GuardedBy("mInstallLock") 630 final Installer mInstaller; 631 632 /** Directory where installed third-party apps stored */ 633 final File mAppInstallDir; 634 635 /** 636 * Directory to which applications installed internally have their 637 * 32 bit native libraries copied. 638 */ 639 private File mAppLib32InstallDir; 640 641 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 642 // apps. 643 final File mDrmAppPrivateInstallDir; 644 645 // ---------------------------------------------------------------- 646 647 // Lock for state used when installing and doing other long running 648 // operations. Methods that must be called with this lock held have 649 // the suffix "LI". 650 final Object mInstallLock = new Object(); 651 652 // ---------------------------------------------------------------- 653 654 // Keys are String (package name), values are Package. This also serves 655 // as the lock for the global state. Methods that must be called with 656 // this lock held have the prefix "LP". 657 @GuardedBy("mPackages") 658 final ArrayMap<String, PackageParser.Package> mPackages = 659 new ArrayMap<String, PackageParser.Package>(); 660 661 final ArrayMap<String, Set<String>> mKnownCodebase = 662 new ArrayMap<String, Set<String>>(); 663 664 // Tracks available target package names -> overlay package paths. 665 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 666 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 667 668 /** 669 * Tracks new system packages [received in an OTA] that we expect to 670 * find updated user-installed versions. Keys are package name, values 671 * are package location. 672 */ 673 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 674 /** 675 * Tracks high priority intent filters for protected actions. During boot, certain 676 * filter actions are protected and should never be allowed to have a high priority 677 * intent filter for them. However, there is one, and only one exception -- the 678 * setup wizard. It must be able to define a high priority intent filter for these 679 * actions to ensure there are no escapes from the wizard. We need to delay processing 680 * of these during boot as we need to look at all of the system packages in order 681 * to know which component is the setup wizard. 682 */ 683 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 684 /** 685 * Whether or not processing protected filters should be deferred. 686 */ 687 private boolean mDeferProtectedFilters = true; 688 689 /** 690 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 691 */ 692 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 693 /** 694 * Whether or not system app permissions should be promoted from install to runtime. 695 */ 696 boolean mPromoteSystemApps; 697 698 @GuardedBy("mPackages") 699 final Settings mSettings; 700 701 /** 702 * Set of package names that are currently "frozen", which means active 703 * surgery is being done on the code/data for that package. The platform 704 * will refuse to launch frozen packages to avoid race conditions. 705 * 706 * @see PackageFreezer 707 */ 708 @GuardedBy("mPackages") 709 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 710 711 final ProtectedPackages mProtectedPackages; 712 713 boolean mFirstBoot; 714 715 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 716 717 // System configuration read by SystemConfig. 718 final int[] mGlobalGids; 719 final SparseArray<ArraySet<String>> mSystemPermissions; 720 @GuardedBy("mAvailableFeatures") 721 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 722 723 // If mac_permissions.xml was found for seinfo labeling. 724 boolean mFoundPolicyFile; 725 726 private final InstantAppRegistry mInstantAppRegistry; 727 728 @GuardedBy("mPackages") 729 int mChangedPackagesSequenceNumber; 730 /** 731 * List of changed [installed, removed or updated] packages. 732 * mapping from user id -> sequence number -> package name 733 */ 734 @GuardedBy("mPackages") 735 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 736 /** 737 * The sequence number of the last change to a package. 738 * mapping from user id -> package name -> sequence number 739 */ 740 @GuardedBy("mPackages") 741 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 742 743 public static final class SharedLibraryEntry { 744 public final String path; 745 public final String apk; 746 public final SharedLibraryInfo info; 747 748 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 749 String declaringPackageName, int declaringPackageVersionCode) { 750 path = _path; 751 apk = _apk; 752 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 753 declaringPackageName, declaringPackageVersionCode), null); 754 } 755 } 756 757 // Currently known shared libraries. 758 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 759 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 760 new ArrayMap<>(); 761 762 // All available activities, for your resolving pleasure. 763 final ActivityIntentResolver mActivities = 764 new ActivityIntentResolver(); 765 766 // All available receivers, for your resolving pleasure. 767 final ActivityIntentResolver mReceivers = 768 new ActivityIntentResolver(); 769 770 // All available services, for your resolving pleasure. 771 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 772 773 // All available providers, for your resolving pleasure. 774 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 775 776 // Mapping from provider base names (first directory in content URI codePath) 777 // to the provider information. 778 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 779 new ArrayMap<String, PackageParser.Provider>(); 780 781 // Mapping from instrumentation class names to info about them. 782 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 783 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 784 785 // Mapping from permission names to info about them. 786 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 787 new ArrayMap<String, PackageParser.PermissionGroup>(); 788 789 // Packages whose data we have transfered into another package, thus 790 // should no longer exist. 791 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 792 793 // Broadcast actions that are only available to the system. 794 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 795 796 /** List of packages waiting for verification. */ 797 final SparseArray<PackageVerificationState> mPendingVerification 798 = new SparseArray<PackageVerificationState>(); 799 800 /** Set of packages associated with each app op permission. */ 801 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 802 803 final PackageInstallerService mInstallerService; 804 805 private final PackageDexOptimizer mPackageDexOptimizer; 806 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 807 // is used by other apps). 808 private final DexManager mDexManager; 809 810 private AtomicInteger mNextMoveId = new AtomicInteger(); 811 private final MoveCallbacks mMoveCallbacks; 812 813 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 814 815 // Cache of users who need badging. 816 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 817 818 /** Token for keys in mPendingVerification. */ 819 private int mPendingVerificationToken = 0; 820 821 volatile boolean mSystemReady; 822 volatile boolean mSafeMode; 823 volatile boolean mHasSystemUidErrors; 824 825 ApplicationInfo mAndroidApplication; 826 final ActivityInfo mResolveActivity = new ActivityInfo(); 827 final ResolveInfo mResolveInfo = new ResolveInfo(); 828 ComponentName mResolveComponentName; 829 PackageParser.Package mPlatformPackage; 830 ComponentName mCustomResolverComponentName; 831 832 boolean mResolverReplaced = false; 833 834 private final @Nullable ComponentName mIntentFilterVerifierComponent; 835 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 836 837 private int mIntentFilterVerificationToken = 0; 838 839 /** The service connection to the ephemeral resolver */ 840 final EphemeralResolverConnection mInstantAppResolverConnection; 841 842 /** Component used to install ephemeral applications */ 843 ComponentName mInstantAppInstallerComponent; 844 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 845 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 846 847 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 848 = new SparseArray<IntentFilterVerificationState>(); 849 850 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 851 852 // List of packages names to keep cached, even if they are uninstalled for all users 853 private List<String> mKeepUninstalledPackages; 854 855 private UserManagerInternal mUserManagerInternal; 856 857 private DeviceIdleController.LocalService mDeviceIdleController; 858 859 private File mCacheDir; 860 861 private ArraySet<String> mPrivappPermissionsViolations; 862 863 private Future<?> mPrepareAppDataFuture; 864 865 private static class IFVerificationParams { 866 PackageParser.Package pkg; 867 boolean replacing; 868 int userId; 869 int verifierUid; 870 871 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 872 int _userId, int _verifierUid) { 873 pkg = _pkg; 874 replacing = _replacing; 875 userId = _userId; 876 replacing = _replacing; 877 verifierUid = _verifierUid; 878 } 879 } 880 881 private interface IntentFilterVerifier<T extends IntentFilter> { 882 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 883 T filter, String packageName); 884 void startVerifications(int userId); 885 void receiveVerificationResponse(int verificationId); 886 } 887 888 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 889 private Context mContext; 890 private ComponentName mIntentFilterVerifierComponent; 891 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 892 893 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 894 mContext = context; 895 mIntentFilterVerifierComponent = verifierComponent; 896 } 897 898 private String getDefaultScheme() { 899 return IntentFilter.SCHEME_HTTPS; 900 } 901 902 @Override 903 public void startVerifications(int userId) { 904 // Launch verifications requests 905 int count = mCurrentIntentFilterVerifications.size(); 906 for (int n=0; n<count; n++) { 907 int verificationId = mCurrentIntentFilterVerifications.get(n); 908 final IntentFilterVerificationState ivs = 909 mIntentFilterVerificationStates.get(verificationId); 910 911 String packageName = ivs.getPackageName(); 912 913 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 914 final int filterCount = filters.size(); 915 ArraySet<String> domainsSet = new ArraySet<>(); 916 for (int m=0; m<filterCount; m++) { 917 PackageParser.ActivityIntentInfo filter = filters.get(m); 918 domainsSet.addAll(filter.getHostsList()); 919 } 920 synchronized (mPackages) { 921 if (mSettings.createIntentFilterVerificationIfNeededLPw( 922 packageName, domainsSet) != null) { 923 scheduleWriteSettingsLocked(); 924 } 925 } 926 sendVerificationRequest(userId, verificationId, ivs); 927 } 928 mCurrentIntentFilterVerifications.clear(); 929 } 930 931 private void sendVerificationRequest(int userId, int verificationId, 932 IntentFilterVerificationState ivs) { 933 934 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 935 verificationIntent.putExtra( 936 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 937 verificationId); 938 verificationIntent.putExtra( 939 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 940 getDefaultScheme()); 941 verificationIntent.putExtra( 942 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 943 ivs.getHostsString()); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 946 ivs.getPackageName()); 947 verificationIntent.setComponent(mIntentFilterVerifierComponent); 948 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 949 950 UserHandle user = new UserHandle(userId); 951 mContext.sendBroadcastAsUser(verificationIntent, user); 952 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 953 "Sending IntentFilter verification broadcast"); 954 } 955 956 public void receiveVerificationResponse(int verificationId) { 957 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 958 959 final boolean verified = ivs.isVerified(); 960 961 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 962 final int count = filters.size(); 963 if (DEBUG_DOMAIN_VERIFICATION) { 964 Slog.i(TAG, "Received verification response " + verificationId 965 + " for " + count + " filters, verified=" + verified); 966 } 967 for (int n=0; n<count; n++) { 968 PackageParser.ActivityIntentInfo filter = filters.get(n); 969 filter.setVerified(verified); 970 971 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 972 + " verified with result:" + verified + " and hosts:" 973 + ivs.getHostsString()); 974 } 975 976 mIntentFilterVerificationStates.remove(verificationId); 977 978 final String packageName = ivs.getPackageName(); 979 IntentFilterVerificationInfo ivi = null; 980 981 synchronized (mPackages) { 982 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 983 } 984 if (ivi == null) { 985 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 986 + verificationId + " packageName:" + packageName); 987 return; 988 } 989 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 990 "Updating IntentFilterVerificationInfo for package " + packageName 991 +" verificationId:" + verificationId); 992 993 synchronized (mPackages) { 994 if (verified) { 995 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 996 } else { 997 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 998 } 999 scheduleWriteSettingsLocked(); 1000 1001 final int userId = ivs.getUserId(); 1002 if (userId != UserHandle.USER_ALL) { 1003 final int userStatus = 1004 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1005 1006 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1007 boolean needUpdate = false; 1008 1009 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1010 // already been set by the User thru the Disambiguation dialog 1011 switch (userStatus) { 1012 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1013 if (verified) { 1014 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1015 } else { 1016 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1017 } 1018 needUpdate = true; 1019 break; 1020 1021 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1022 if (verified) { 1023 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1024 needUpdate = true; 1025 } 1026 break; 1027 1028 default: 1029 // Nothing to do 1030 } 1031 1032 if (needUpdate) { 1033 mSettings.updateIntentFilterVerificationStatusLPw( 1034 packageName, updatedStatus, userId); 1035 scheduleWritePackageRestrictionsLocked(userId); 1036 } 1037 } 1038 } 1039 } 1040 1041 @Override 1042 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1043 ActivityIntentInfo filter, String packageName) { 1044 if (!hasValidDomains(filter)) { 1045 return false; 1046 } 1047 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1048 if (ivs == null) { 1049 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1050 packageName); 1051 } 1052 if (DEBUG_DOMAIN_VERIFICATION) { 1053 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1054 } 1055 ivs.addFilter(filter); 1056 return true; 1057 } 1058 1059 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1060 int userId, int verificationId, String packageName) { 1061 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1062 verifierUid, userId, packageName); 1063 ivs.setPendingState(); 1064 synchronized (mPackages) { 1065 mIntentFilterVerificationStates.append(verificationId, ivs); 1066 mCurrentIntentFilterVerifications.add(verificationId); 1067 } 1068 return ivs; 1069 } 1070 } 1071 1072 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1073 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1074 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1075 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1076 } 1077 1078 // Set of pending broadcasts for aggregating enable/disable of components. 1079 static class PendingPackageBroadcasts { 1080 // for each user id, a map of <package name -> components within that package> 1081 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1082 1083 public PendingPackageBroadcasts() { 1084 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1085 } 1086 1087 public ArrayList<String> get(int userId, String packageName) { 1088 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1089 return packages.get(packageName); 1090 } 1091 1092 public void put(int userId, String packageName, ArrayList<String> components) { 1093 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1094 packages.put(packageName, components); 1095 } 1096 1097 public void remove(int userId, String packageName) { 1098 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1099 if (packages != null) { 1100 packages.remove(packageName); 1101 } 1102 } 1103 1104 public void remove(int userId) { 1105 mUidMap.remove(userId); 1106 } 1107 1108 public int userIdCount() { 1109 return mUidMap.size(); 1110 } 1111 1112 public int userIdAt(int n) { 1113 return mUidMap.keyAt(n); 1114 } 1115 1116 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1117 return mUidMap.get(userId); 1118 } 1119 1120 public int size() { 1121 // total number of pending broadcast entries across all userIds 1122 int num = 0; 1123 for (int i = 0; i< mUidMap.size(); i++) { 1124 num += mUidMap.valueAt(i).size(); 1125 } 1126 return num; 1127 } 1128 1129 public void clear() { 1130 mUidMap.clear(); 1131 } 1132 1133 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1134 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1135 if (map == null) { 1136 map = new ArrayMap<String, ArrayList<String>>(); 1137 mUidMap.put(userId, map); 1138 } 1139 return map; 1140 } 1141 } 1142 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1143 1144 // Service Connection to remote media container service to copy 1145 // package uri's from external media onto secure containers 1146 // or internal storage. 1147 private IMediaContainerService mContainerService = null; 1148 1149 static final int SEND_PENDING_BROADCAST = 1; 1150 static final int MCS_BOUND = 3; 1151 static final int END_COPY = 4; 1152 static final int INIT_COPY = 5; 1153 static final int MCS_UNBIND = 6; 1154 static final int START_CLEANING_PACKAGE = 7; 1155 static final int FIND_INSTALL_LOC = 8; 1156 static final int POST_INSTALL = 9; 1157 static final int MCS_RECONNECT = 10; 1158 static final int MCS_GIVE_UP = 11; 1159 static final int UPDATED_MEDIA_STATUS = 12; 1160 static final int WRITE_SETTINGS = 13; 1161 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1162 static final int PACKAGE_VERIFIED = 15; 1163 static final int CHECK_PENDING_VERIFICATION = 16; 1164 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1165 static final int INTENT_FILTER_VERIFIED = 18; 1166 static final int WRITE_PACKAGE_LIST = 19; 1167 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1168 1169 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1170 1171 // Delay time in millisecs 1172 static final int BROADCAST_DELAY = 10 * 1000; 1173 1174 static UserManagerService sUserManager; 1175 1176 // Stores a list of users whose package restrictions file needs to be updated 1177 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1178 1179 final private DefaultContainerConnection mDefContainerConn = 1180 new DefaultContainerConnection(); 1181 class DefaultContainerConnection implements ServiceConnection { 1182 public void onServiceConnected(ComponentName name, IBinder service) { 1183 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1184 final IMediaContainerService imcs = IMediaContainerService.Stub 1185 .asInterface(Binder.allowBlocking(service)); 1186 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1187 } 1188 1189 public void onServiceDisconnected(ComponentName name) { 1190 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1191 } 1192 } 1193 1194 // Recordkeeping of restore-after-install operations that are currently in flight 1195 // between the Package Manager and the Backup Manager 1196 static class PostInstallData { 1197 public InstallArgs args; 1198 public PackageInstalledInfo res; 1199 1200 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1201 args = _a; 1202 res = _r; 1203 } 1204 } 1205 1206 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1207 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1208 1209 // XML tags for backup/restore of various bits of state 1210 private static final String TAG_PREFERRED_BACKUP = "pa"; 1211 private static final String TAG_DEFAULT_APPS = "da"; 1212 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1213 1214 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1215 private static final String TAG_ALL_GRANTS = "rt-grants"; 1216 private static final String TAG_GRANT = "grant"; 1217 private static final String ATTR_PACKAGE_NAME = "pkg"; 1218 1219 private static final String TAG_PERMISSION = "perm"; 1220 private static final String ATTR_PERMISSION_NAME = "name"; 1221 private static final String ATTR_IS_GRANTED = "g"; 1222 private static final String ATTR_USER_SET = "set"; 1223 private static final String ATTR_USER_FIXED = "fixed"; 1224 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1225 1226 // System/policy permission grants are not backed up 1227 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1228 FLAG_PERMISSION_POLICY_FIXED 1229 | FLAG_PERMISSION_SYSTEM_FIXED 1230 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1231 1232 // And we back up these user-adjusted states 1233 private static final int USER_RUNTIME_GRANT_MASK = 1234 FLAG_PERMISSION_USER_SET 1235 | FLAG_PERMISSION_USER_FIXED 1236 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1237 1238 final @Nullable String mRequiredVerifierPackage; 1239 final @NonNull String mRequiredInstallerPackage; 1240 final @NonNull String mRequiredUninstallerPackage; 1241 final @Nullable String mSetupWizardPackage; 1242 final @Nullable String mStorageManagerPackage; 1243 final @NonNull String mServicesSystemSharedLibraryPackageName; 1244 final @NonNull String mSharedSystemSharedLibraryPackageName; 1245 1246 final boolean mPermissionReviewRequired; 1247 1248 private final PackageUsage mPackageUsage = new PackageUsage(); 1249 private final CompilerStats mCompilerStats = new CompilerStats(); 1250 1251 class PackageHandler extends Handler { 1252 private boolean mBound = false; 1253 final ArrayList<HandlerParams> mPendingInstalls = 1254 new ArrayList<HandlerParams>(); 1255 1256 private boolean connectToService() { 1257 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1258 " DefaultContainerService"); 1259 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1261 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1262 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 mBound = true; 1265 return true; 1266 } 1267 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1268 return false; 1269 } 1270 1271 private void disconnectService() { 1272 mContainerService = null; 1273 mBound = false; 1274 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1275 mContext.unbindService(mDefContainerConn); 1276 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1277 } 1278 1279 PackageHandler(Looper looper) { 1280 super(looper); 1281 } 1282 1283 public void handleMessage(Message msg) { 1284 try { 1285 doHandleMessage(msg); 1286 } finally { 1287 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1288 } 1289 } 1290 1291 void doHandleMessage(Message msg) { 1292 switch (msg.what) { 1293 case INIT_COPY: { 1294 HandlerParams params = (HandlerParams) msg.obj; 1295 int idx = mPendingInstalls.size(); 1296 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1297 // If a bind was already initiated we dont really 1298 // need to do anything. The pending install 1299 // will be processed later on. 1300 if (!mBound) { 1301 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1302 System.identityHashCode(mHandler)); 1303 // If this is the only one pending we might 1304 // have to bind to the service again. 1305 if (!connectToService()) { 1306 Slog.e(TAG, "Failed to bind to media container service"); 1307 params.serviceError(); 1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1309 System.identityHashCode(mHandler)); 1310 if (params.traceMethod != null) { 1311 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1312 params.traceCookie); 1313 } 1314 return; 1315 } else { 1316 // Once we bind to the service, the first 1317 // pending request will be processed. 1318 mPendingInstalls.add(idx, params); 1319 } 1320 } else { 1321 mPendingInstalls.add(idx, params); 1322 // Already bound to the service. Just make 1323 // sure we trigger off processing the first request. 1324 if (idx == 0) { 1325 mHandler.sendEmptyMessage(MCS_BOUND); 1326 } 1327 } 1328 break; 1329 } 1330 case MCS_BOUND: { 1331 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1332 if (msg.obj != null) { 1333 mContainerService = (IMediaContainerService) msg.obj; 1334 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1335 System.identityHashCode(mHandler)); 1336 } 1337 if (mContainerService == null) { 1338 if (!mBound) { 1339 // Something seriously wrong since we are not bound and we are not 1340 // waiting for connection. Bail out. 1341 Slog.e(TAG, "Cannot bind to media container service"); 1342 for (HandlerParams params : mPendingInstalls) { 1343 // Indicate service bind error 1344 params.serviceError(); 1345 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1346 System.identityHashCode(params)); 1347 if (params.traceMethod != null) { 1348 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1349 params.traceMethod, params.traceCookie); 1350 } 1351 return; 1352 } 1353 mPendingInstalls.clear(); 1354 } else { 1355 Slog.w(TAG, "Waiting to connect to media container service"); 1356 } 1357 } else if (mPendingInstalls.size() > 0) { 1358 HandlerParams params = mPendingInstalls.get(0); 1359 if (params != null) { 1360 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1361 System.identityHashCode(params)); 1362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1363 if (params.startCopy()) { 1364 // We are done... look for more work or to 1365 // go idle. 1366 if (DEBUG_SD_INSTALL) Log.i(TAG, 1367 "Checking for more work or unbind..."); 1368 // Delete pending install 1369 if (mPendingInstalls.size() > 0) { 1370 mPendingInstalls.remove(0); 1371 } 1372 if (mPendingInstalls.size() == 0) { 1373 if (mBound) { 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, 1375 "Posting delayed MCS_UNBIND"); 1376 removeMessages(MCS_UNBIND); 1377 Message ubmsg = obtainMessage(MCS_UNBIND); 1378 // Unbind after a little delay, to avoid 1379 // continual thrashing. 1380 sendMessageDelayed(ubmsg, 10000); 1381 } 1382 } else { 1383 // There are more pending requests in queue. 1384 // Just post MCS_BOUND message to trigger processing 1385 // of next pending install. 1386 if (DEBUG_SD_INSTALL) Log.i(TAG, 1387 "Posting MCS_BOUND for next work"); 1388 mHandler.sendEmptyMessage(MCS_BOUND); 1389 } 1390 } 1391 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1392 } 1393 } else { 1394 // Should never happen ideally. 1395 Slog.w(TAG, "Empty queue"); 1396 } 1397 break; 1398 } 1399 case MCS_RECONNECT: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1401 if (mPendingInstalls.size() > 0) { 1402 if (mBound) { 1403 disconnectService(); 1404 } 1405 if (!connectToService()) { 1406 Slog.e(TAG, "Failed to bind to media container service"); 1407 for (HandlerParams params : mPendingInstalls) { 1408 // Indicate service bind error 1409 params.serviceError(); 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1411 System.identityHashCode(params)); 1412 } 1413 mPendingInstalls.clear(); 1414 } 1415 } 1416 break; 1417 } 1418 case MCS_UNBIND: { 1419 // If there is no actual work left, then time to unbind. 1420 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1421 1422 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1423 if (mBound) { 1424 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1425 1426 disconnectService(); 1427 } 1428 } else if (mPendingInstalls.size() > 0) { 1429 // There are more pending requests in queue. 1430 // Just post MCS_BOUND message to trigger processing 1431 // of next pending install. 1432 mHandler.sendEmptyMessage(MCS_BOUND); 1433 } 1434 1435 break; 1436 } 1437 case MCS_GIVE_UP: { 1438 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1439 HandlerParams params = mPendingInstalls.remove(0); 1440 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1441 System.identityHashCode(params)); 1442 break; 1443 } 1444 case SEND_PENDING_BROADCAST: { 1445 String packages[]; 1446 ArrayList<String> components[]; 1447 int size = 0; 1448 int uids[]; 1449 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1450 synchronized (mPackages) { 1451 if (mPendingBroadcasts == null) { 1452 return; 1453 } 1454 size = mPendingBroadcasts.size(); 1455 if (size <= 0) { 1456 // Nothing to be done. Just return 1457 return; 1458 } 1459 packages = new String[size]; 1460 components = new ArrayList[size]; 1461 uids = new int[size]; 1462 int i = 0; // filling out the above arrays 1463 1464 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1465 int packageUserId = mPendingBroadcasts.userIdAt(n); 1466 Iterator<Map.Entry<String, ArrayList<String>>> it 1467 = mPendingBroadcasts.packagesForUserId(packageUserId) 1468 .entrySet().iterator(); 1469 while (it.hasNext() && i < size) { 1470 Map.Entry<String, ArrayList<String>> ent = it.next(); 1471 packages[i] = ent.getKey(); 1472 components[i] = ent.getValue(); 1473 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1474 uids[i] = (ps != null) 1475 ? UserHandle.getUid(packageUserId, ps.appId) 1476 : -1; 1477 i++; 1478 } 1479 } 1480 size = i; 1481 mPendingBroadcasts.clear(); 1482 } 1483 // Send broadcasts 1484 for (int i = 0; i < size; i++) { 1485 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1486 } 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1488 break; 1489 } 1490 case START_CLEANING_PACKAGE: { 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1492 final String packageName = (String)msg.obj; 1493 final int userId = msg.arg1; 1494 final boolean andCode = msg.arg2 != 0; 1495 synchronized (mPackages) { 1496 if (userId == UserHandle.USER_ALL) { 1497 int[] users = sUserManager.getUserIds(); 1498 for (int user : users) { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(user, packageName, andCode)); 1501 } 1502 } else { 1503 mSettings.addPackageToCleanLPw( 1504 new PackageCleanItem(userId, packageName, andCode)); 1505 } 1506 } 1507 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1508 startCleaningPackages(); 1509 } break; 1510 case POST_INSTALL: { 1511 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1512 1513 PostInstallData data = mRunningInstalls.get(msg.arg1); 1514 final boolean didRestore = (msg.arg2 != 0); 1515 mRunningInstalls.delete(msg.arg1); 1516 1517 if (data != null) { 1518 InstallArgs args = data.args; 1519 PackageInstalledInfo parentRes = data.res; 1520 1521 final boolean grantPermissions = (args.installFlags 1522 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1523 final boolean killApp = (args.installFlags 1524 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1525 final String[] grantedPermissions = args.installGrantPermissions; 1526 1527 // Handle the parent package 1528 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1529 grantedPermissions, didRestore, args.installerPackageName, 1530 args.observer); 1531 1532 // Handle the child packages 1533 final int childCount = (parentRes.addedChildPackages != null) 1534 ? parentRes.addedChildPackages.size() : 0; 1535 for (int i = 0; i < childCount; i++) { 1536 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1537 handlePackagePostInstall(childRes, grantPermissions, killApp, 1538 grantedPermissions, false, args.installerPackageName, 1539 args.observer); 1540 } 1541 1542 // Log tracing if needed 1543 if (args.traceMethod != null) { 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1545 args.traceCookie); 1546 } 1547 } else { 1548 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1549 } 1550 1551 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1552 } break; 1553 case UPDATED_MEDIA_STATUS: { 1554 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1555 boolean reportStatus = msg.arg1 == 1; 1556 boolean doGc = msg.arg2 == 1; 1557 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1558 if (doGc) { 1559 // Force a gc to clear up stale containers. 1560 Runtime.getRuntime().gc(); 1561 } 1562 if (msg.obj != null) { 1563 @SuppressWarnings("unchecked") 1564 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1565 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1566 // Unload containers 1567 unloadAllContainers(args); 1568 } 1569 if (reportStatus) { 1570 try { 1571 if (DEBUG_SD_INSTALL) Log.i(TAG, 1572 "Invoking StorageManagerService call back"); 1573 PackageHelper.getStorageManager().finishMediaUpdate(); 1574 } catch (RemoteException e) { 1575 Log.e(TAG, "StorageManagerService not running?"); 1576 } 1577 } 1578 } break; 1579 case WRITE_SETTINGS: { 1580 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1581 synchronized (mPackages) { 1582 removeMessages(WRITE_SETTINGS); 1583 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1584 mSettings.writeLPr(); 1585 mDirtyUsers.clear(); 1586 } 1587 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1588 } break; 1589 case WRITE_PACKAGE_RESTRICTIONS: { 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1591 synchronized (mPackages) { 1592 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1593 for (int userId : mDirtyUsers) { 1594 mSettings.writePackageRestrictionsLPr(userId); 1595 } 1596 mDirtyUsers.clear(); 1597 } 1598 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1599 } break; 1600 case WRITE_PACKAGE_LIST: { 1601 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1602 synchronized (mPackages) { 1603 removeMessages(WRITE_PACKAGE_LIST); 1604 mSettings.writePackageListLPr(msg.arg1); 1605 } 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1607 } break; 1608 case CHECK_PENDING_VERIFICATION: { 1609 final int verificationId = msg.arg1; 1610 final PackageVerificationState state = mPendingVerification.get(verificationId); 1611 1612 if ((state != null) && !state.timeoutExtended()) { 1613 final InstallArgs args = state.getInstallArgs(); 1614 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1615 1616 Slog.i(TAG, "Verification timed out for " + originUri); 1617 mPendingVerification.remove(verificationId); 1618 1619 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1620 1621 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1622 Slog.i(TAG, "Continuing with installation of " + originUri); 1623 state.setVerifierResponse(Binder.getCallingUid(), 1624 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1625 broadcastPackageVerified(verificationId, originUri, 1626 PackageManager.VERIFICATION_ALLOW, 1627 state.getInstallArgs().getUser()); 1628 try { 1629 ret = args.copyApk(mContainerService, true); 1630 } catch (RemoteException e) { 1631 Slog.e(TAG, "Could not contact the ContainerService"); 1632 } 1633 } else { 1634 broadcastPackageVerified(verificationId, originUri, 1635 PackageManager.VERIFICATION_REJECT, 1636 state.getInstallArgs().getUser()); 1637 } 1638 1639 Trace.asyncTraceEnd( 1640 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1641 1642 processPendingInstall(args, ret); 1643 mHandler.sendEmptyMessage(MCS_UNBIND); 1644 } 1645 break; 1646 } 1647 case PACKAGE_VERIFIED: { 1648 final int verificationId = msg.arg1; 1649 1650 final PackageVerificationState state = mPendingVerification.get(verificationId); 1651 if (state == null) { 1652 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1653 break; 1654 } 1655 1656 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1657 1658 state.setVerifierResponse(response.callerUid, response.code); 1659 1660 if (state.isVerificationComplete()) { 1661 mPendingVerification.remove(verificationId); 1662 1663 final InstallArgs args = state.getInstallArgs(); 1664 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1665 1666 int ret; 1667 if (state.isInstallAllowed()) { 1668 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1669 broadcastPackageVerified(verificationId, originUri, 1670 response.code, state.getInstallArgs().getUser()); 1671 try { 1672 ret = args.copyApk(mContainerService, true); 1673 } catch (RemoteException e) { 1674 Slog.e(TAG, "Could not contact the ContainerService"); 1675 } 1676 } else { 1677 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1678 } 1679 1680 Trace.asyncTraceEnd( 1681 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1682 1683 processPendingInstall(args, ret); 1684 mHandler.sendEmptyMessage(MCS_UNBIND); 1685 } 1686 1687 break; 1688 } 1689 case START_INTENT_FILTER_VERIFICATIONS: { 1690 IFVerificationParams params = (IFVerificationParams) msg.obj; 1691 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1692 params.replacing, params.pkg); 1693 break; 1694 } 1695 case INTENT_FILTER_VERIFIED: { 1696 final int verificationId = msg.arg1; 1697 1698 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1699 verificationId); 1700 if (state == null) { 1701 Slog.w(TAG, "Invalid IntentFilter verification token " 1702 + verificationId + " received"); 1703 break; 1704 } 1705 1706 final int userId = state.getUserId(); 1707 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1709 "Processing IntentFilter verification with token:" 1710 + verificationId + " and userId:" + userId); 1711 1712 final IntentFilterVerificationResponse response = 1713 (IntentFilterVerificationResponse) msg.obj; 1714 1715 state.setVerifierResponse(response.callerUid, response.code); 1716 1717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1718 "IntentFilter verification with token:" + verificationId 1719 + " and userId:" + userId 1720 + " is settings verifier response with response code:" 1721 + response.code); 1722 1723 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1724 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1725 + response.getFailedDomainsString()); 1726 } 1727 1728 if (state.isVerificationComplete()) { 1729 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1730 } else { 1731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1732 "IntentFilter verification with token:" + verificationId 1733 + " was not said to be complete"); 1734 } 1735 1736 break; 1737 } 1738 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1739 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1740 mInstantAppResolverConnection, 1741 (EphemeralRequest) msg.obj, 1742 mInstantAppInstallerActivity, 1743 mHandler); 1744 } 1745 } 1746 } 1747 } 1748 1749 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1750 boolean killApp, String[] grantedPermissions, 1751 boolean launchedForRestore, String installerPackage, 1752 IPackageInstallObserver2 installObserver) { 1753 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1754 // Send the removed broadcasts 1755 if (res.removedInfo != null) { 1756 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1757 } 1758 1759 // Now that we successfully installed the package, grant runtime 1760 // permissions if requested before broadcasting the install. Also 1761 // for legacy apps in permission review mode we clear the permission 1762 // review flag which is used to emulate runtime permissions for 1763 // legacy apps. 1764 if (grantPermissions) { 1765 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1766 } 1767 1768 final boolean update = res.removedInfo != null 1769 && res.removedInfo.removedPackage != null; 1770 1771 // If this is the first time we have child packages for a disabled privileged 1772 // app that had no children, we grant requested runtime permissions to the new 1773 // children if the parent on the system image had them already granted. 1774 if (res.pkg.parentPackage != null) { 1775 synchronized (mPackages) { 1776 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1777 } 1778 } 1779 1780 synchronized (mPackages) { 1781 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1782 } 1783 1784 final String packageName = res.pkg.applicationInfo.packageName; 1785 1786 // Determine the set of users who are adding this package for 1787 // the first time vs. those who are seeing an update. 1788 int[] firstUsers = EMPTY_INT_ARRAY; 1789 int[] updateUsers = EMPTY_INT_ARRAY; 1790 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1791 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1792 for (int newUser : res.newUsers) { 1793 if (ps.getInstantApp(newUser)) { 1794 continue; 1795 } 1796 if (allNewUsers) { 1797 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1798 continue; 1799 } 1800 boolean isNew = true; 1801 for (int origUser : res.origUsers) { 1802 if (origUser == newUser) { 1803 isNew = false; 1804 break; 1805 } 1806 } 1807 if (isNew) { 1808 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1809 } else { 1810 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1811 } 1812 } 1813 1814 // Send installed broadcasts if the package is not a static shared lib. 1815 if (res.pkg.staticSharedLibName == null) { 1816 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1817 1818 // Send added for users that see the package for the first time 1819 // sendPackageAddedForNewUsers also deals with system apps 1820 int appId = UserHandle.getAppId(res.uid); 1821 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1822 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1823 1824 // Send added for users that don't see the package for the first time 1825 Bundle extras = new Bundle(1); 1826 extras.putInt(Intent.EXTRA_UID, res.uid); 1827 if (update) { 1828 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1829 } 1830 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1831 extras, 0 /*flags*/, null /*targetPackage*/, 1832 null /*finishedReceiver*/, updateUsers); 1833 1834 // Send replaced for users that don't see the package for the first time 1835 if (update) { 1836 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1837 packageName, extras, 0 /*flags*/, 1838 null /*targetPackage*/, null /*finishedReceiver*/, 1839 updateUsers); 1840 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1841 null /*package*/, null /*extras*/, 0 /*flags*/, 1842 packageName /*targetPackage*/, 1843 null /*finishedReceiver*/, updateUsers); 1844 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1845 // First-install and we did a restore, so we're responsible for the 1846 // first-launch broadcast. 1847 if (DEBUG_BACKUP) { 1848 Slog.i(TAG, "Post-restore of " + packageName 1849 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1850 } 1851 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1852 } 1853 1854 // Send broadcast package appeared if forward locked/external for all users 1855 // treat asec-hosted packages like removable media on upgrade 1856 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1857 if (DEBUG_INSTALL) { 1858 Slog.i(TAG, "upgrading pkg " + res.pkg 1859 + " is ASEC-hosted -> AVAILABLE"); 1860 } 1861 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1862 ArrayList<String> pkgList = new ArrayList<>(1); 1863 pkgList.add(packageName); 1864 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1865 } 1866 } 1867 1868 // Work that needs to happen on first install within each user 1869 if (firstUsers != null && firstUsers.length > 0) { 1870 synchronized (mPackages) { 1871 for (int userId : firstUsers) { 1872 // If this app is a browser and it's newly-installed for some 1873 // users, clear any default-browser state in those users. The 1874 // app's nature doesn't depend on the user, so we can just check 1875 // its browser nature in any user and generalize. 1876 if (packageIsBrowser(packageName, userId)) { 1877 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1878 } 1879 1880 // We may also need to apply pending (restored) runtime 1881 // permission grants within these users. 1882 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1883 } 1884 } 1885 } 1886 1887 // Log current value of "unknown sources" setting 1888 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1889 getUnknownSourcesSettings()); 1890 1891 // Force a gc to clear up things 1892 Runtime.getRuntime().gc(); 1893 1894 // Remove the replaced package's older resources safely now 1895 // We delete after a gc for applications on sdcard. 1896 if (res.removedInfo != null && res.removedInfo.args != null) { 1897 synchronized (mInstallLock) { 1898 res.removedInfo.args.doPostDeleteLI(true); 1899 } 1900 } 1901 1902 // Notify DexManager that the package was installed for new users. 1903 // The updated users should already be indexed and the package code paths 1904 // should not change. 1905 // Don't notify the manager for ephemeral apps as they are not expected to 1906 // survive long enough to benefit of background optimizations. 1907 for (int userId : firstUsers) { 1908 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1909 mDexManager.notifyPackageInstalled(info, userId); 1910 } 1911 } 1912 1913 // If someone is watching installs - notify them 1914 if (installObserver != null) { 1915 try { 1916 Bundle extras = extrasForInstallResult(res); 1917 installObserver.onPackageInstalled(res.name, res.returnCode, 1918 res.returnMsg, extras); 1919 } catch (RemoteException e) { 1920 Slog.i(TAG, "Observer no longer exists."); 1921 } 1922 } 1923 } 1924 1925 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1926 PackageParser.Package pkg) { 1927 if (pkg.parentPackage == null) { 1928 return; 1929 } 1930 if (pkg.requestedPermissions == null) { 1931 return; 1932 } 1933 final PackageSetting disabledSysParentPs = mSettings 1934 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1935 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1936 || !disabledSysParentPs.isPrivileged() 1937 || (disabledSysParentPs.childPackageNames != null 1938 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1939 return; 1940 } 1941 final int[] allUserIds = sUserManager.getUserIds(); 1942 final int permCount = pkg.requestedPermissions.size(); 1943 for (int i = 0; i < permCount; i++) { 1944 String permission = pkg.requestedPermissions.get(i); 1945 BasePermission bp = mSettings.mPermissions.get(permission); 1946 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1947 continue; 1948 } 1949 for (int userId : allUserIds) { 1950 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1951 permission, userId)) { 1952 grantRuntimePermission(pkg.packageName, permission, userId); 1953 } 1954 } 1955 } 1956 } 1957 1958 private StorageEventListener mStorageListener = new StorageEventListener() { 1959 @Override 1960 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1961 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1962 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1963 final String volumeUuid = vol.getFsUuid(); 1964 1965 // Clean up any users or apps that were removed or recreated 1966 // while this volume was missing 1967 sUserManager.reconcileUsers(volumeUuid); 1968 reconcileApps(volumeUuid); 1969 1970 // Clean up any install sessions that expired or were 1971 // cancelled while this volume was missing 1972 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1973 1974 loadPrivatePackages(vol); 1975 1976 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1977 unloadPrivatePackages(vol); 1978 } 1979 } 1980 1981 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1982 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1983 updateExternalMediaStatus(true, false); 1984 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1985 updateExternalMediaStatus(false, false); 1986 } 1987 } 1988 } 1989 1990 @Override 1991 public void onVolumeForgotten(String fsUuid) { 1992 if (TextUtils.isEmpty(fsUuid)) { 1993 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1994 return; 1995 } 1996 1997 // Remove any apps installed on the forgotten volume 1998 synchronized (mPackages) { 1999 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2000 for (PackageSetting ps : packages) { 2001 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2002 deletePackageVersioned(new VersionedPackage(ps.name, 2003 PackageManager.VERSION_CODE_HIGHEST), 2004 new LegacyPackageDeleteObserver(null).getBinder(), 2005 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2006 // Try very hard to release any references to this package 2007 // so we don't risk the system server being killed due to 2008 // open FDs 2009 AttributeCache.instance().removePackage(ps.name); 2010 } 2011 2012 mSettings.onVolumeForgotten(fsUuid); 2013 mSettings.writeLPr(); 2014 } 2015 } 2016 }; 2017 2018 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2019 String[] grantedPermissions) { 2020 for (int userId : userIds) { 2021 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2022 } 2023 } 2024 2025 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2026 String[] grantedPermissions) { 2027 SettingBase sb = (SettingBase) pkg.mExtras; 2028 if (sb == null) { 2029 return; 2030 } 2031 2032 PermissionsState permissionsState = sb.getPermissionsState(); 2033 2034 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2035 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2036 2037 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2038 >= Build.VERSION_CODES.M; 2039 2040 for (String permission : pkg.requestedPermissions) { 2041 final BasePermission bp; 2042 synchronized (mPackages) { 2043 bp = mSettings.mPermissions.get(permission); 2044 } 2045 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2046 && (grantedPermissions == null 2047 || ArrayUtils.contains(grantedPermissions, permission))) { 2048 final int flags = permissionsState.getPermissionFlags(permission, userId); 2049 if (supportsRuntimePermissions) { 2050 // Installer cannot change immutable permissions. 2051 if ((flags & immutableFlags) == 0) { 2052 grantRuntimePermission(pkg.packageName, permission, userId); 2053 } 2054 } else if (mPermissionReviewRequired) { 2055 // In permission review mode we clear the review flag when we 2056 // are asked to install the app with all permissions granted. 2057 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2058 updatePermissionFlags(permission, pkg.packageName, 2059 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2060 } 2061 } 2062 } 2063 } 2064 } 2065 2066 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2067 Bundle extras = null; 2068 switch (res.returnCode) { 2069 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2070 extras = new Bundle(); 2071 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2072 res.origPermission); 2073 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2074 res.origPackage); 2075 break; 2076 } 2077 case PackageManager.INSTALL_SUCCEEDED: { 2078 extras = new Bundle(); 2079 extras.putBoolean(Intent.EXTRA_REPLACING, 2080 res.removedInfo != null && res.removedInfo.removedPackage != null); 2081 break; 2082 } 2083 } 2084 return extras; 2085 } 2086 2087 void scheduleWriteSettingsLocked() { 2088 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2089 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2090 } 2091 } 2092 2093 void scheduleWritePackageListLocked(int userId) { 2094 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2095 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2096 msg.arg1 = userId; 2097 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2098 } 2099 } 2100 2101 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2102 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2103 scheduleWritePackageRestrictionsLocked(userId); 2104 } 2105 2106 void scheduleWritePackageRestrictionsLocked(int userId) { 2107 final int[] userIds = (userId == UserHandle.USER_ALL) 2108 ? sUserManager.getUserIds() : new int[]{userId}; 2109 for (int nextUserId : userIds) { 2110 if (!sUserManager.exists(nextUserId)) return; 2111 mDirtyUsers.add(nextUserId); 2112 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2113 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2114 } 2115 } 2116 } 2117 2118 public static PackageManagerService main(Context context, Installer installer, 2119 boolean factoryTest, boolean onlyCore) { 2120 // Self-check for initial settings. 2121 PackageManagerServiceCompilerMapping.checkProperties(); 2122 2123 PackageManagerService m = new PackageManagerService(context, installer, 2124 factoryTest, onlyCore); 2125 m.enableSystemUserPackages(); 2126 ServiceManager.addService("package", m); 2127 return m; 2128 } 2129 2130 private void enableSystemUserPackages() { 2131 if (!UserManager.isSplitSystemUser()) { 2132 return; 2133 } 2134 // For system user, enable apps based on the following conditions: 2135 // - app is whitelisted or belong to one of these groups: 2136 // -- system app which has no launcher icons 2137 // -- system app which has INTERACT_ACROSS_USERS permission 2138 // -- system IME app 2139 // - app is not in the blacklist 2140 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2141 Set<String> enableApps = new ArraySet<>(); 2142 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2143 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2144 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2145 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2146 enableApps.addAll(wlApps); 2147 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2148 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2149 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2150 enableApps.removeAll(blApps); 2151 Log.i(TAG, "Applications installed for system user: " + enableApps); 2152 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2153 UserHandle.SYSTEM); 2154 final int allAppsSize = allAps.size(); 2155 synchronized (mPackages) { 2156 for (int i = 0; i < allAppsSize; i++) { 2157 String pName = allAps.get(i); 2158 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2159 // Should not happen, but we shouldn't be failing if it does 2160 if (pkgSetting == null) { 2161 continue; 2162 } 2163 boolean install = enableApps.contains(pName); 2164 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2165 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2166 + " for system user"); 2167 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2168 } 2169 } 2170 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2171 } 2172 } 2173 2174 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2175 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2176 Context.DISPLAY_SERVICE); 2177 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2178 } 2179 2180 /** 2181 * Requests that files preopted on a secondary system partition be copied to the data partition 2182 * if possible. Note that the actual copying of the files is accomplished by init for security 2183 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2184 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2185 */ 2186 private static void requestCopyPreoptedFiles() { 2187 final int WAIT_TIME_MS = 100; 2188 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2189 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2190 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2191 // We will wait for up to 100 seconds. 2192 final long timeStart = SystemClock.uptimeMillis(); 2193 final long timeEnd = timeStart + 100 * 1000; 2194 long timeNow = timeStart; 2195 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2196 try { 2197 Thread.sleep(WAIT_TIME_MS); 2198 } catch (InterruptedException e) { 2199 // Do nothing 2200 } 2201 timeNow = SystemClock.uptimeMillis(); 2202 if (timeNow > timeEnd) { 2203 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2204 Slog.wtf(TAG, "cppreopt did not finish!"); 2205 break; 2206 } 2207 } 2208 2209 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2210 } 2211 } 2212 2213 public PackageManagerService(Context context, Installer installer, 2214 boolean factoryTest, boolean onlyCore) { 2215 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2216 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2217 SystemClock.uptimeMillis()); 2218 2219 if (mSdkVersion <= 0) { 2220 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2221 } 2222 2223 mContext = context; 2224 2225 mPermissionReviewRequired = context.getResources().getBoolean( 2226 R.bool.config_permissionReviewRequired); 2227 2228 mFactoryTest = factoryTest; 2229 mOnlyCore = onlyCore; 2230 mMetrics = new DisplayMetrics(); 2231 mSettings = new Settings(mPackages); 2232 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 2245 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2246 if (separateProcesses != null && separateProcesses.length() > 0) { 2247 if ("*".equals(separateProcesses)) { 2248 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2249 mSeparateProcesses = null; 2250 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2251 } else { 2252 mDefParseFlags = 0; 2253 mSeparateProcesses = separateProcesses.split(","); 2254 Slog.w(TAG, "Running with debug.separate_processes: " 2255 + separateProcesses); 2256 } 2257 } else { 2258 mDefParseFlags = 0; 2259 mSeparateProcesses = null; 2260 } 2261 2262 mInstaller = installer; 2263 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2264 "*dexopt*"); 2265 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2266 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2267 2268 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2269 FgThread.get().getLooper()); 2270 2271 getDefaultDisplayMetrics(context, mMetrics); 2272 2273 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2274 SystemConfig systemConfig = SystemConfig.getInstance(); 2275 mGlobalGids = systemConfig.getGlobalGids(); 2276 mSystemPermissions = systemConfig.getSystemPermissions(); 2277 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2279 2280 mProtectedPackages = new ProtectedPackages(mContext); 2281 2282 synchronized (mInstallLock) { 2283 // writer 2284 synchronized (mPackages) { 2285 mHandlerThread = new ServiceThread(TAG, 2286 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2287 mHandlerThread.start(); 2288 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2289 mProcessLoggingHandler = new ProcessLoggingHandler(); 2290 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2291 2292 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2293 mInstantAppRegistry = new InstantAppRegistry(this); 2294 2295 File dataDir = Environment.getDataDirectory(); 2296 mAppInstallDir = new File(dataDir, "app"); 2297 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2298 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2299 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2300 sUserManager = new UserManagerService(context, this, 2301 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2302 2303 // Propagate permission configuration in to package manager. 2304 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2305 = systemConfig.getPermissions(); 2306 for (int i=0; i<permConfig.size(); i++) { 2307 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2308 BasePermission bp = mSettings.mPermissions.get(perm.name); 2309 if (bp == null) { 2310 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2311 mSettings.mPermissions.put(perm.name, bp); 2312 } 2313 if (perm.gids != null) { 2314 bp.setGids(perm.gids, perm.perUser); 2315 } 2316 } 2317 2318 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2319 final int builtInLibCount = libConfig.size(); 2320 for (int i = 0; i < builtInLibCount; i++) { 2321 String name = libConfig.keyAt(i); 2322 String path = libConfig.valueAt(i); 2323 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2324 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2325 } 2326 2327 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2328 2329 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2330 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2331 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2332 2333 // Clean up orphaned packages for which the code path doesn't exist 2334 // and they are an update to a system app - caused by bug/32321269 2335 final int packageSettingCount = mSettings.mPackages.size(); 2336 for (int i = packageSettingCount - 1; i >= 0; i--) { 2337 PackageSetting ps = mSettings.mPackages.valueAt(i); 2338 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2339 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2340 mSettings.mPackages.removeAt(i); 2341 mSettings.enableSystemPackageLPw(ps.name); 2342 } 2343 } 2344 2345 if (mFirstBoot) { 2346 requestCopyPreoptedFiles(); 2347 } 2348 2349 String customResolverActivity = Resources.getSystem().getString( 2350 R.string.config_customResolverActivity); 2351 if (TextUtils.isEmpty(customResolverActivity)) { 2352 customResolverActivity = null; 2353 } else { 2354 mCustomResolverComponentName = ComponentName.unflattenFromString( 2355 customResolverActivity); 2356 } 2357 2358 long startTime = SystemClock.uptimeMillis(); 2359 2360 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2361 startTime); 2362 2363 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2364 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2365 2366 if (bootClassPath == null) { 2367 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2368 } 2369 2370 if (systemServerClassPath == null) { 2371 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2372 } 2373 2374 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2375 final String[] dexCodeInstructionSets = 2376 getDexCodeInstructionSets( 2377 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2378 2379 /** 2380 * Ensure all external libraries have had dexopt run on them. 2381 */ 2382 if (mSharedLibraries.size() > 0) { 2383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2384 // NOTE: For now, we're compiling these system "shared libraries" 2385 // (and framework jars) into all available architectures. It's possible 2386 // to compile them only when we come across an app that uses them (there's 2387 // already logic for that in scanPackageLI) but that adds some complexity. 2388 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2389 final int libCount = mSharedLibraries.size(); 2390 for (int i = 0; i < libCount; i++) { 2391 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2392 final int versionCount = versionedLib.size(); 2393 for (int j = 0; j < versionCount; j++) { 2394 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2395 final String libPath = libEntry.path != null 2396 ? libEntry.path : libEntry.apk; 2397 if (libPath == null) { 2398 continue; 2399 } 2400 try { 2401 // Shared libraries do not have profiles so we perform a full 2402 // AOT compilation (if needed). 2403 int dexoptNeeded = DexFile.getDexOptNeeded( 2404 libPath, dexCodeInstructionSet, 2405 getCompilerFilterForReason(REASON_SHARED_APK), 2406 false /* newProfile */); 2407 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2408 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2409 dexCodeInstructionSet, dexoptNeeded, null, 2410 DEXOPT_PUBLIC, 2411 getCompilerFilterForReason(REASON_SHARED_APK), 2412 StorageManager.UUID_PRIVATE_INTERNAL, 2413 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2414 } 2415 } catch (FileNotFoundException e) { 2416 Slog.w(TAG, "Library not found: " + libPath); 2417 } catch (IOException | InstallerException e) { 2418 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2419 + e.getMessage()); 2420 } 2421 } 2422 } 2423 } 2424 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2425 } 2426 2427 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2428 2429 final VersionInfo ver = mSettings.getInternalVersion(); 2430 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2431 2432 // when upgrading from pre-M, promote system app permissions from install to runtime 2433 mPromoteSystemApps = 2434 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2435 2436 // When upgrading from pre-N, we need to handle package extraction like first boot, 2437 // as there is no profiling data available. 2438 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2439 2440 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2441 2442 // save off the names of pre-existing system packages prior to scanning; we don't 2443 // want to automatically grant runtime permissions for new system apps 2444 if (mPromoteSystemApps) { 2445 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2446 while (pkgSettingIter.hasNext()) { 2447 PackageSetting ps = pkgSettingIter.next(); 2448 if (isSystemApp(ps)) { 2449 mExistingSystemPackages.add(ps.name); 2450 } 2451 } 2452 } 2453 2454 mCacheDir = preparePackageParserCache(mIsUpgrade); 2455 2456 // Set flag to monitor and not change apk file paths when 2457 // scanning install directories. 2458 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2459 2460 if (mIsUpgrade || mFirstBoot) { 2461 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2462 } 2463 2464 // Collect vendor overlay packages. (Do this before scanning any apps.) 2465 // For security and version matching reason, only consider 2466 // overlay packages if they reside in the right directory. 2467 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2468 if (overlayThemeDir.isEmpty()) { 2469 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2470 } 2471 if (!overlayThemeDir.isEmpty()) { 2472 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2473 | PackageParser.PARSE_IS_SYSTEM 2474 | PackageParser.PARSE_IS_SYSTEM_DIR 2475 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2476 } 2477 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2478 | PackageParser.PARSE_IS_SYSTEM 2479 | PackageParser.PARSE_IS_SYSTEM_DIR 2480 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2481 2482 // Find base frameworks (resource packages without code). 2483 scanDirTracedLI(frameworkDir, mDefParseFlags 2484 | PackageParser.PARSE_IS_SYSTEM 2485 | PackageParser.PARSE_IS_SYSTEM_DIR 2486 | PackageParser.PARSE_IS_PRIVILEGED, 2487 scanFlags | SCAN_NO_DEX, 0); 2488 2489 // Collected privileged system packages. 2490 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2491 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2492 | PackageParser.PARSE_IS_SYSTEM 2493 | PackageParser.PARSE_IS_SYSTEM_DIR 2494 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2495 2496 // Collect ordinary system packages. 2497 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2498 scanDirTracedLI(systemAppDir, mDefParseFlags 2499 | PackageParser.PARSE_IS_SYSTEM 2500 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2501 2502 // Collect all vendor packages. 2503 File vendorAppDir = new File("/vendor/app"); 2504 try { 2505 vendorAppDir = vendorAppDir.getCanonicalFile(); 2506 } catch (IOException e) { 2507 // failed to look up canonical path, continue with original one 2508 } 2509 scanDirTracedLI(vendorAppDir, mDefParseFlags 2510 | PackageParser.PARSE_IS_SYSTEM 2511 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2512 2513 // Collect all OEM packages. 2514 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2515 scanDirTracedLI(oemAppDir, mDefParseFlags 2516 | PackageParser.PARSE_IS_SYSTEM 2517 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2518 2519 // Prune any system packages that no longer exist. 2520 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2521 if (!mOnlyCore) { 2522 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2523 while (psit.hasNext()) { 2524 PackageSetting ps = psit.next(); 2525 2526 /* 2527 * If this is not a system app, it can't be a 2528 * disable system app. 2529 */ 2530 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2531 continue; 2532 } 2533 2534 /* 2535 * If the package is scanned, it's not erased. 2536 */ 2537 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2538 if (scannedPkg != null) { 2539 /* 2540 * If the system app is both scanned and in the 2541 * disabled packages list, then it must have been 2542 * added via OTA. Remove it from the currently 2543 * scanned package so the previously user-installed 2544 * application can be scanned. 2545 */ 2546 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2547 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2548 + ps.name + "; removing system app. Last known codePath=" 2549 + ps.codePathString + ", installStatus=" + ps.installStatus 2550 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2551 + scannedPkg.mVersionCode); 2552 removePackageLI(scannedPkg, true); 2553 mExpectingBetter.put(ps.name, ps.codePath); 2554 } 2555 2556 continue; 2557 } 2558 2559 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2560 psit.remove(); 2561 logCriticalInfo(Log.WARN, "System package " + ps.name 2562 + " no longer exists; it's data will be wiped"); 2563 // Actual deletion of code and data will be handled by later 2564 // reconciliation step 2565 } else { 2566 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2567 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2568 possiblyDeletedUpdatedSystemApps.add(ps.name); 2569 } 2570 } 2571 } 2572 } 2573 2574 //look for any incomplete package installations 2575 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2576 for (int i = 0; i < deletePkgsList.size(); i++) { 2577 // Actual deletion of code and data will be handled by later 2578 // reconciliation step 2579 final String packageName = deletePkgsList.get(i).name; 2580 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2581 synchronized (mPackages) { 2582 mSettings.removePackageLPw(packageName); 2583 } 2584 } 2585 2586 //delete tmp files 2587 deleteTempPackageFiles(); 2588 2589 // Remove any shared userIDs that have no associated packages 2590 mSettings.pruneSharedUsersLPw(); 2591 2592 if (!mOnlyCore) { 2593 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2594 SystemClock.uptimeMillis()); 2595 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2596 2597 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2598 | PackageParser.PARSE_FORWARD_LOCK, 2599 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2600 2601 /** 2602 * Remove disable package settings for any updated system 2603 * apps that were removed via an OTA. If they're not a 2604 * previously-updated app, remove them completely. 2605 * Otherwise, just revoke their system-level permissions. 2606 */ 2607 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2608 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2609 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2610 2611 String msg; 2612 if (deletedPkg == null) { 2613 msg = "Updated system package " + deletedAppName 2614 + " no longer exists; it's data will be wiped"; 2615 // Actual deletion of code and data will be handled by later 2616 // reconciliation step 2617 } else { 2618 msg = "Updated system app + " + deletedAppName 2619 + " no longer present; removing system privileges for " 2620 + deletedAppName; 2621 2622 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2623 2624 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2625 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2626 } 2627 logCriticalInfo(Log.WARN, msg); 2628 } 2629 2630 /** 2631 * Make sure all system apps that we expected to appear on 2632 * the userdata partition actually showed up. If they never 2633 * appeared, crawl back and revive the system version. 2634 */ 2635 for (int i = 0; i < mExpectingBetter.size(); i++) { 2636 final String packageName = mExpectingBetter.keyAt(i); 2637 if (!mPackages.containsKey(packageName)) { 2638 final File scanFile = mExpectingBetter.valueAt(i); 2639 2640 logCriticalInfo(Log.WARN, "Expected better " + packageName 2641 + " but never showed up; reverting to system"); 2642 2643 int reparseFlags = mDefParseFlags; 2644 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2645 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2646 | PackageParser.PARSE_IS_SYSTEM_DIR 2647 | PackageParser.PARSE_IS_PRIVILEGED; 2648 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2649 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2650 | PackageParser.PARSE_IS_SYSTEM_DIR; 2651 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2652 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2653 | PackageParser.PARSE_IS_SYSTEM_DIR; 2654 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2655 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2656 | PackageParser.PARSE_IS_SYSTEM_DIR; 2657 } else { 2658 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2659 continue; 2660 } 2661 2662 mSettings.enableSystemPackageLPw(packageName); 2663 2664 try { 2665 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2666 } catch (PackageManagerException e) { 2667 Slog.e(TAG, "Failed to parse original system package: " 2668 + e.getMessage()); 2669 } 2670 } 2671 } 2672 } 2673 mExpectingBetter.clear(); 2674 2675 // Resolve the storage manager. 2676 mStorageManagerPackage = getStorageManagerPackageName(); 2677 2678 // Resolve protected action filters. Only the setup wizard is allowed to 2679 // have a high priority filter for these actions. 2680 mSetupWizardPackage = getSetupWizardPackageName(); 2681 if (mProtectedFilters.size() > 0) { 2682 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2683 Slog.i(TAG, "No setup wizard;" 2684 + " All protected intents capped to priority 0"); 2685 } 2686 for (ActivityIntentInfo filter : mProtectedFilters) { 2687 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2688 if (DEBUG_FILTERS) { 2689 Slog.i(TAG, "Found setup wizard;" 2690 + " allow priority " + filter.getPriority() + ";" 2691 + " package: " + filter.activity.info.packageName 2692 + " activity: " + filter.activity.className 2693 + " priority: " + filter.getPriority()); 2694 } 2695 // skip setup wizard; allow it to keep the high priority filter 2696 continue; 2697 } 2698 Slog.w(TAG, "Protected action; cap priority to 0;" 2699 + " package: " + filter.activity.info.packageName 2700 + " activity: " + filter.activity.className 2701 + " origPrio: " + filter.getPriority()); 2702 filter.setPriority(0); 2703 } 2704 } 2705 mDeferProtectedFilters = false; 2706 mProtectedFilters.clear(); 2707 2708 // Now that we know all of the shared libraries, update all clients to have 2709 // the correct library paths. 2710 updateAllSharedLibrariesLPw(null); 2711 2712 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2713 // NOTE: We ignore potential failures here during a system scan (like 2714 // the rest of the commands above) because there's precious little we 2715 // can do about it. A settings error is reported, though. 2716 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2717 } 2718 2719 // Now that we know all the packages we are keeping, 2720 // read and update their last usage times. 2721 mPackageUsage.read(mPackages); 2722 mCompilerStats.read(); 2723 2724 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2725 SystemClock.uptimeMillis()); 2726 Slog.i(TAG, "Time to scan packages: " 2727 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2728 + " seconds"); 2729 2730 // If the platform SDK has changed since the last time we booted, 2731 // we need to re-grant app permission to catch any new ones that 2732 // appear. This is really a hack, and means that apps can in some 2733 // cases get permissions that the user didn't initially explicitly 2734 // allow... it would be nice to have some better way to handle 2735 // this situation. 2736 int updateFlags = UPDATE_PERMISSIONS_ALL; 2737 if (ver.sdkVersion != mSdkVersion) { 2738 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2739 + mSdkVersion + "; regranting permissions for internal storage"); 2740 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2741 } 2742 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2743 ver.sdkVersion = mSdkVersion; 2744 2745 // If this is the first boot or an update from pre-M, and it is a normal 2746 // boot, then we need to initialize the default preferred apps across 2747 // all defined users. 2748 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2749 for (UserInfo user : sUserManager.getUsers(true)) { 2750 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2751 applyFactoryDefaultBrowserLPw(user.id); 2752 primeDomainVerificationsLPw(user.id); 2753 } 2754 } 2755 2756 // Prepare storage for system user really early during boot, 2757 // since core system apps like SettingsProvider and SystemUI 2758 // can't wait for user to start 2759 final int storageFlags; 2760 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2761 storageFlags = StorageManager.FLAG_STORAGE_DE; 2762 } else { 2763 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2764 } 2765 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2766 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2767 true /* onlyCoreApps */); 2768 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2769 if (deferPackages == null || deferPackages.isEmpty()) { 2770 return; 2771 } 2772 int count = 0; 2773 for (String pkgName : deferPackages) { 2774 PackageParser.Package pkg = null; 2775 synchronized (mPackages) { 2776 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2777 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2778 pkg = ps.pkg; 2779 } 2780 } 2781 if (pkg != null) { 2782 synchronized (mInstallLock) { 2783 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2784 true /* maybeMigrateAppData */); 2785 } 2786 count++; 2787 } 2788 } 2789 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2790 }, "prepareAppData"); 2791 2792 // If this is first boot after an OTA, and a normal boot, then 2793 // we need to clear code cache directories. 2794 // Note that we do *not* clear the application profiles. These remain valid 2795 // across OTAs and are used to drive profile verification (post OTA) and 2796 // profile compilation (without waiting to collect a fresh set of profiles). 2797 if (mIsUpgrade && !onlyCore) { 2798 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2799 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2800 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2801 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2802 // No apps are running this early, so no need to freeze 2803 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2804 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2805 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2806 } 2807 } 2808 ver.fingerprint = Build.FINGERPRINT; 2809 } 2810 2811 checkDefaultBrowser(); 2812 2813 // clear only after permissions and other defaults have been updated 2814 mExistingSystemPackages.clear(); 2815 mPromoteSystemApps = false; 2816 2817 // All the changes are done during package scanning. 2818 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2819 2820 // can downgrade to reader 2821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2822 mSettings.writeLPr(); 2823 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2824 2825 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2826 // early on (before the package manager declares itself as early) because other 2827 // components in the system server might ask for package contexts for these apps. 2828 // 2829 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2830 // (i.e, that the data partition is unavailable). 2831 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2832 long start = System.nanoTime(); 2833 List<PackageParser.Package> coreApps = new ArrayList<>(); 2834 for (PackageParser.Package pkg : mPackages.values()) { 2835 if (pkg.coreApp) { 2836 coreApps.add(pkg); 2837 } 2838 } 2839 2840 int[] stats = performDexOptUpgrade(coreApps, false, 2841 getCompilerFilterForReason(REASON_CORE_APP)); 2842 2843 final int elapsedTimeSeconds = 2844 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2845 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2846 2847 if (DEBUG_DEXOPT) { 2848 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2849 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2850 } 2851 2852 2853 // TODO: Should we log these stats to tron too ? 2854 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2855 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2856 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2857 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2858 } 2859 2860 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2861 SystemClock.uptimeMillis()); 2862 2863 if (!mOnlyCore) { 2864 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2865 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2866 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2867 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2868 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2869 mIntentFilterVerifierComponent); 2870 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2871 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2872 SharedLibraryInfo.VERSION_UNDEFINED); 2873 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2874 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2875 SharedLibraryInfo.VERSION_UNDEFINED); 2876 } else { 2877 mRequiredVerifierPackage = null; 2878 mRequiredInstallerPackage = null; 2879 mRequiredUninstallerPackage = null; 2880 mIntentFilterVerifierComponent = null; 2881 mIntentFilterVerifier = null; 2882 mServicesSystemSharedLibraryPackageName = null; 2883 mSharedSystemSharedLibraryPackageName = null; 2884 } 2885 2886 mInstallerService = new PackageInstallerService(context, this); 2887 2888 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2889 if (ephemeralResolverComponent != null) { 2890 if (DEBUG_EPHEMERAL) { 2891 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2892 } 2893 mInstantAppResolverConnection = 2894 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2895 } else { 2896 mInstantAppResolverConnection = null; 2897 } 2898 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2899 if (mInstantAppInstallerComponent != null) { 2900 if (DEBUG_EPHEMERAL) { 2901 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2902 } 2903 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2904 } 2905 2906 // Read and update the usage of dex files. 2907 // Do this at the end of PM init so that all the packages have their 2908 // data directory reconciled. 2909 // At this point we know the code paths of the packages, so we can validate 2910 // the disk file and build the internal cache. 2911 // The usage file is expected to be small so loading and verifying it 2912 // should take a fairly small time compare to the other activities (e.g. package 2913 // scanning). 2914 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2915 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2916 for (int userId : currentUserIds) { 2917 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2918 } 2919 mDexManager.load(userPackages); 2920 } // synchronized (mPackages) 2921 } // synchronized (mInstallLock) 2922 2923 // Now after opening every single application zip, make sure they 2924 // are all flushed. Not really needed, but keeps things nice and 2925 // tidy. 2926 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2927 Runtime.getRuntime().gc(); 2928 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2929 2930 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2931 FallbackCategoryProvider.loadFallbacks(); 2932 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2933 2934 // The initial scanning above does many calls into installd while 2935 // holding the mPackages lock, but we're mostly interested in yelling 2936 // once we have a booted system. 2937 mInstaller.setWarnIfHeld(mPackages); 2938 2939 // Expose private service for system components to use. 2940 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2941 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2942 } 2943 2944 private static File preparePackageParserCache(boolean isUpgrade) { 2945 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2946 return null; 2947 } 2948 2949 // Disable package parsing on eng builds to allow for faster incremental development. 2950 if ("eng".equals(Build.TYPE)) { 2951 return null; 2952 } 2953 2954 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2955 Slog.i(TAG, "Disabling package parser cache due to system property."); 2956 return null; 2957 } 2958 2959 // The base directory for the package parser cache lives under /data/system/. 2960 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2961 "package_cache"); 2962 if (cacheBaseDir == null) { 2963 return null; 2964 } 2965 2966 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2967 // This also serves to "GC" unused entries when the package cache version changes (which 2968 // can only happen during upgrades). 2969 if (isUpgrade) { 2970 FileUtils.deleteContents(cacheBaseDir); 2971 } 2972 2973 2974 // Return the versioned package cache directory. This is something like 2975 // "/data/system/package_cache/1" 2976 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2977 2978 // The following is a workaround to aid development on non-numbered userdebug 2979 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2980 // the system partition is newer. 2981 // 2982 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2983 // that starts with "eng." to signify that this is an engineering build and not 2984 // destined for release. 2985 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2986 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2987 2988 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2989 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2990 // in general and should not be used for production changes. In this specific case, 2991 // we know that they will work. 2992 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2993 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2994 FileUtils.deleteContents(cacheBaseDir); 2995 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2996 } 2997 } 2998 2999 return cacheDir; 3000 } 3001 3002 @Override 3003 public boolean isFirstBoot() { 3004 return mFirstBoot; 3005 } 3006 3007 @Override 3008 public boolean isOnlyCoreApps() { 3009 return mOnlyCore; 3010 } 3011 3012 @Override 3013 public boolean isUpgrade() { 3014 return mIsUpgrade; 3015 } 3016 3017 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3018 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3019 3020 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3021 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3022 UserHandle.USER_SYSTEM); 3023 if (matches.size() == 1) { 3024 return matches.get(0).getComponentInfo().packageName; 3025 } else if (matches.size() == 0) { 3026 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3027 return null; 3028 } 3029 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3030 } 3031 3032 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3033 synchronized (mPackages) { 3034 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3035 if (libraryEntry == null) { 3036 throw new IllegalStateException("Missing required shared library:" + name); 3037 } 3038 return libraryEntry.apk; 3039 } 3040 } 3041 3042 private @NonNull String getRequiredInstallerLPr() { 3043 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3044 intent.addCategory(Intent.CATEGORY_DEFAULT); 3045 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3046 3047 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3048 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3049 UserHandle.USER_SYSTEM); 3050 if (matches.size() == 1) { 3051 ResolveInfo resolveInfo = matches.get(0); 3052 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3053 throw new RuntimeException("The installer must be a privileged app"); 3054 } 3055 return matches.get(0).getComponentInfo().packageName; 3056 } else { 3057 throw new RuntimeException("There must be exactly one installer; found " + matches); 3058 } 3059 } 3060 3061 private @NonNull String getRequiredUninstallerLPr() { 3062 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3063 intent.addCategory(Intent.CATEGORY_DEFAULT); 3064 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3065 3066 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3067 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3068 UserHandle.USER_SYSTEM); 3069 if (resolveInfo == null || 3070 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3071 throw new RuntimeException("There must be exactly one uninstaller; found " 3072 + resolveInfo); 3073 } 3074 return resolveInfo.getComponentInfo().packageName; 3075 } 3076 3077 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3078 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3079 3080 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3081 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3082 UserHandle.USER_SYSTEM); 3083 ResolveInfo best = null; 3084 final int N = matches.size(); 3085 for (int i = 0; i < N; i++) { 3086 final ResolveInfo cur = matches.get(i); 3087 final String packageName = cur.getComponentInfo().packageName; 3088 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3089 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3090 continue; 3091 } 3092 3093 if (best == null || cur.priority > best.priority) { 3094 best = cur; 3095 } 3096 } 3097 3098 if (best != null) { 3099 return best.getComponentInfo().getComponentName(); 3100 } else { 3101 throw new RuntimeException("There must be at least one intent filter verifier"); 3102 } 3103 } 3104 3105 private @Nullable ComponentName getEphemeralResolverLPr() { 3106 final String[] packageArray = 3107 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3108 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3109 if (DEBUG_EPHEMERAL) { 3110 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3111 } 3112 return null; 3113 } 3114 3115 final int resolveFlags = 3116 MATCH_DIRECT_BOOT_AWARE 3117 | MATCH_DIRECT_BOOT_UNAWARE 3118 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3119 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3120 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3121 resolveFlags, UserHandle.USER_SYSTEM); 3122 3123 final int N = resolvers.size(); 3124 if (N == 0) { 3125 if (DEBUG_EPHEMERAL) { 3126 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3127 } 3128 return null; 3129 } 3130 3131 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3132 for (int i = 0; i < N; i++) { 3133 final ResolveInfo info = resolvers.get(i); 3134 3135 if (info.serviceInfo == null) { 3136 continue; 3137 } 3138 3139 final String packageName = info.serviceInfo.packageName; 3140 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3141 if (DEBUG_EPHEMERAL) { 3142 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3143 + " pkg: " + packageName + ", info:" + info); 3144 } 3145 continue; 3146 } 3147 3148 if (DEBUG_EPHEMERAL) { 3149 Slog.v(TAG, "Ephemeral resolver found;" 3150 + " pkg: " + packageName + ", info:" + info); 3151 } 3152 return new ComponentName(packageName, info.serviceInfo.name); 3153 } 3154 if (DEBUG_EPHEMERAL) { 3155 Slog.v(TAG, "Ephemeral resolver NOT found"); 3156 } 3157 return null; 3158 } 3159 3160 private @Nullable ComponentName getEphemeralInstallerLPr() { 3161 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3162 intent.addCategory(Intent.CATEGORY_DEFAULT); 3163 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3164 3165 final int resolveFlags = 3166 MATCH_DIRECT_BOOT_AWARE 3167 | MATCH_DIRECT_BOOT_UNAWARE 3168 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3169 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3170 resolveFlags, UserHandle.USER_SYSTEM); 3171 Iterator<ResolveInfo> iter = matches.iterator(); 3172 while (iter.hasNext()) { 3173 final ResolveInfo rInfo = iter.next(); 3174 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3175 if (ps != null) { 3176 final PermissionsState permissionsState = ps.getPermissionsState(); 3177 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3178 continue; 3179 } 3180 } 3181 iter.remove(); 3182 } 3183 if (matches.size() == 0) { 3184 return null; 3185 } else if (matches.size() == 1) { 3186 return matches.get(0).getComponentInfo().getComponentName(); 3187 } else { 3188 throw new RuntimeException( 3189 "There must be at most one ephemeral installer; found " + matches); 3190 } 3191 } 3192 3193 private void primeDomainVerificationsLPw(int userId) { 3194 if (DEBUG_DOMAIN_VERIFICATION) { 3195 Slog.d(TAG, "Priming domain verifications in user " + userId); 3196 } 3197 3198 SystemConfig systemConfig = SystemConfig.getInstance(); 3199 ArraySet<String> packages = systemConfig.getLinkedApps(); 3200 3201 for (String packageName : packages) { 3202 PackageParser.Package pkg = mPackages.get(packageName); 3203 if (pkg != null) { 3204 if (!pkg.isSystemApp()) { 3205 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3206 continue; 3207 } 3208 3209 ArraySet<String> domains = null; 3210 for (PackageParser.Activity a : pkg.activities) { 3211 for (ActivityIntentInfo filter : a.intents) { 3212 if (hasValidDomains(filter)) { 3213 if (domains == null) { 3214 domains = new ArraySet<String>(); 3215 } 3216 domains.addAll(filter.getHostsList()); 3217 } 3218 } 3219 } 3220 3221 if (domains != null && domains.size() > 0) { 3222 if (DEBUG_DOMAIN_VERIFICATION) { 3223 Slog.v(TAG, " + " + packageName); 3224 } 3225 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3226 // state w.r.t. the formal app-linkage "no verification attempted" state; 3227 // and then 'always' in the per-user state actually used for intent resolution. 3228 final IntentFilterVerificationInfo ivi; 3229 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3230 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3231 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3232 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3233 } else { 3234 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3235 + "' does not handle web links"); 3236 } 3237 } else { 3238 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3239 } 3240 } 3241 3242 scheduleWritePackageRestrictionsLocked(userId); 3243 scheduleWriteSettingsLocked(); 3244 } 3245 3246 private void applyFactoryDefaultBrowserLPw(int userId) { 3247 // The default browser app's package name is stored in a string resource, 3248 // with a product-specific overlay used for vendor customization. 3249 String browserPkg = mContext.getResources().getString( 3250 com.android.internal.R.string.default_browser); 3251 if (!TextUtils.isEmpty(browserPkg)) { 3252 // non-empty string => required to be a known package 3253 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3254 if (ps == null) { 3255 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3256 browserPkg = null; 3257 } else { 3258 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3259 } 3260 } 3261 3262 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3263 // default. If there's more than one, just leave everything alone. 3264 if (browserPkg == null) { 3265 calculateDefaultBrowserLPw(userId); 3266 } 3267 } 3268 3269 private void calculateDefaultBrowserLPw(int userId) { 3270 List<String> allBrowsers = resolveAllBrowserApps(userId); 3271 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3272 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3273 } 3274 3275 private List<String> resolveAllBrowserApps(int userId) { 3276 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3277 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3278 PackageManager.MATCH_ALL, userId); 3279 3280 final int count = list.size(); 3281 List<String> result = new ArrayList<String>(count); 3282 for (int i=0; i<count; i++) { 3283 ResolveInfo info = list.get(i); 3284 if (info.activityInfo == null 3285 || !info.handleAllWebDataURI 3286 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3287 || result.contains(info.activityInfo.packageName)) { 3288 continue; 3289 } 3290 result.add(info.activityInfo.packageName); 3291 } 3292 3293 return result; 3294 } 3295 3296 private boolean packageIsBrowser(String packageName, int userId) { 3297 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3298 PackageManager.MATCH_ALL, userId); 3299 final int N = list.size(); 3300 for (int i = 0; i < N; i++) { 3301 ResolveInfo info = list.get(i); 3302 if (packageName.equals(info.activityInfo.packageName)) { 3303 return true; 3304 } 3305 } 3306 return false; 3307 } 3308 3309 private void checkDefaultBrowser() { 3310 final int myUserId = UserHandle.myUserId(); 3311 final String packageName = getDefaultBrowserPackageName(myUserId); 3312 if (packageName != null) { 3313 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3314 if (info == null) { 3315 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3316 synchronized (mPackages) { 3317 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3318 } 3319 } 3320 } 3321 } 3322 3323 @Override 3324 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3325 throws RemoteException { 3326 try { 3327 return super.onTransact(code, data, reply, flags); 3328 } catch (RuntimeException e) { 3329 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3330 Slog.wtf(TAG, "Package Manager Crash", e); 3331 } 3332 throw e; 3333 } 3334 } 3335 3336 static int[] appendInts(int[] cur, int[] add) { 3337 if (add == null) return cur; 3338 if (cur == null) return add; 3339 final int N = add.length; 3340 for (int i=0; i<N; i++) { 3341 cur = appendInt(cur, add[i]); 3342 } 3343 return cur; 3344 } 3345 3346 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3347 if (!sUserManager.exists(userId)) return null; 3348 if (ps == null) { 3349 return null; 3350 } 3351 final PackageParser.Package p = ps.pkg; 3352 if (p == null) { 3353 return null; 3354 } 3355 // Filter out ephemeral app metadata: 3356 // * The system/shell/root can see metadata for any app 3357 // * An installed app can see metadata for 1) other installed apps 3358 // and 2) ephemeral apps that have explicitly interacted with it 3359 // * Ephemeral apps can only see their own metadata 3360 // * Holding a signature permission allows seeing instant apps 3361 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3362 if (callingAppId != Process.SYSTEM_UID 3363 && callingAppId != Process.SHELL_UID 3364 && callingAppId != Process.ROOT_UID 3365 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3366 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3367 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3368 if (instantAppPackageName != null) { 3369 // ephemeral apps can only get information on themselves 3370 if (!instantAppPackageName.equals(p.packageName)) { 3371 return null; 3372 } 3373 } else { 3374 if (ps.getInstantApp(userId)) { 3375 // only get access to the ephemeral app if we've been granted access 3376 if (!mInstantAppRegistry.isInstantAccessGranted( 3377 userId, callingAppId, ps.appId)) { 3378 return null; 3379 } 3380 } 3381 } 3382 } 3383 3384 final PermissionsState permissionsState = ps.getPermissionsState(); 3385 3386 // Compute GIDs only if requested 3387 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3388 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3389 // Compute granted permissions only if package has requested permissions 3390 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3391 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3392 final PackageUserState state = ps.readUserState(userId); 3393 3394 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3395 && ps.isSystem()) { 3396 flags |= MATCH_ANY_USER; 3397 } 3398 3399 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3400 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3401 3402 if (packageInfo == null) { 3403 return null; 3404 } 3405 3406 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3407 resolveExternalPackageNameLPr(p); 3408 3409 return packageInfo; 3410 } 3411 3412 @Override 3413 public void checkPackageStartable(String packageName, int userId) { 3414 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3415 3416 synchronized (mPackages) { 3417 final PackageSetting ps = mSettings.mPackages.get(packageName); 3418 if (ps == null) { 3419 throw new SecurityException("Package " + packageName + " was not found!"); 3420 } 3421 3422 if (!ps.getInstalled(userId)) { 3423 throw new SecurityException( 3424 "Package " + packageName + " was not installed for user " + userId + "!"); 3425 } 3426 3427 if (mSafeMode && !ps.isSystem()) { 3428 throw new SecurityException("Package " + packageName + " not a system app!"); 3429 } 3430 3431 if (mFrozenPackages.contains(packageName)) { 3432 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3433 } 3434 3435 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3436 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3437 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3438 } 3439 } 3440 } 3441 3442 @Override 3443 public boolean isPackageAvailable(String packageName, int userId) { 3444 if (!sUserManager.exists(userId)) return false; 3445 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3446 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3447 synchronized (mPackages) { 3448 PackageParser.Package p = mPackages.get(packageName); 3449 if (p != null) { 3450 final PackageSetting ps = (PackageSetting) p.mExtras; 3451 if (ps != null) { 3452 final PackageUserState state = ps.readUserState(userId); 3453 if (state != null) { 3454 return PackageParser.isAvailable(state); 3455 } 3456 } 3457 } 3458 } 3459 return false; 3460 } 3461 3462 @Override 3463 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3464 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3465 flags, userId); 3466 } 3467 3468 @Override 3469 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3470 int flags, int userId) { 3471 return getPackageInfoInternal(versionedPackage.getPackageName(), 3472 // TODO: We will change version code to long, so in the new API it is long 3473 (int) versionedPackage.getVersionCode(), flags, userId); 3474 } 3475 3476 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3477 int flags, int userId) { 3478 if (!sUserManager.exists(userId)) return null; 3479 flags = updateFlagsForPackage(flags, userId, packageName); 3480 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3481 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3482 3483 // reader 3484 synchronized (mPackages) { 3485 // Normalize package name to handle renamed packages and static libs 3486 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3487 3488 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3489 if (matchFactoryOnly) { 3490 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3491 if (ps != null) { 3492 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3493 return null; 3494 } 3495 return generatePackageInfo(ps, flags, userId); 3496 } 3497 } 3498 3499 PackageParser.Package p = mPackages.get(packageName); 3500 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3501 return null; 3502 } 3503 if (DEBUG_PACKAGE_INFO) 3504 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3505 if (p != null) { 3506 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3507 Binder.getCallingUid(), userId)) { 3508 return null; 3509 } 3510 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3511 } 3512 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3513 final PackageSetting ps = mSettings.mPackages.get(packageName); 3514 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3515 return null; 3516 } 3517 return generatePackageInfo(ps, flags, userId); 3518 } 3519 } 3520 return null; 3521 } 3522 3523 3524 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3525 // System/shell/root get to see all static libs 3526 final int appId = UserHandle.getAppId(uid); 3527 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3528 || appId == Process.ROOT_UID) { 3529 return false; 3530 } 3531 3532 // No package means no static lib as it is always on internal storage 3533 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3534 return false; 3535 } 3536 3537 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3538 ps.pkg.staticSharedLibVersion); 3539 if (libEntry == null) { 3540 return false; 3541 } 3542 3543 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3544 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3545 if (uidPackageNames == null) { 3546 return true; 3547 } 3548 3549 for (String uidPackageName : uidPackageNames) { 3550 if (ps.name.equals(uidPackageName)) { 3551 return false; 3552 } 3553 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3554 if (uidPs != null) { 3555 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3556 libEntry.info.getName()); 3557 if (index < 0) { 3558 continue; 3559 } 3560 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3561 return false; 3562 } 3563 } 3564 } 3565 return true; 3566 } 3567 3568 @Override 3569 public String[] currentToCanonicalPackageNames(String[] names) { 3570 String[] out = new String[names.length]; 3571 // reader 3572 synchronized (mPackages) { 3573 for (int i=names.length-1; i>=0; i--) { 3574 PackageSetting ps = mSettings.mPackages.get(names[i]); 3575 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3576 } 3577 } 3578 return out; 3579 } 3580 3581 @Override 3582 public String[] canonicalToCurrentPackageNames(String[] names) { 3583 String[] out = new String[names.length]; 3584 // reader 3585 synchronized (mPackages) { 3586 for (int i=names.length-1; i>=0; i--) { 3587 String cur = mSettings.getRenamedPackageLPr(names[i]); 3588 out[i] = cur != null ? cur : names[i]; 3589 } 3590 } 3591 return out; 3592 } 3593 3594 @Override 3595 public int getPackageUid(String packageName, int flags, int userId) { 3596 if (!sUserManager.exists(userId)) return -1; 3597 flags = updateFlagsForPackage(flags, userId, packageName); 3598 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3599 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3600 3601 // reader 3602 synchronized (mPackages) { 3603 final PackageParser.Package p = mPackages.get(packageName); 3604 if (p != null && p.isMatch(flags)) { 3605 return UserHandle.getUid(userId, p.applicationInfo.uid); 3606 } 3607 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3608 final PackageSetting ps = mSettings.mPackages.get(packageName); 3609 if (ps != null && ps.isMatch(flags)) { 3610 return UserHandle.getUid(userId, ps.appId); 3611 } 3612 } 3613 } 3614 3615 return -1; 3616 } 3617 3618 @Override 3619 public int[] getPackageGids(String packageName, int flags, int userId) { 3620 if (!sUserManager.exists(userId)) return null; 3621 flags = updateFlagsForPackage(flags, userId, packageName); 3622 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3623 false /* requireFullPermission */, false /* checkShell */, 3624 "getPackageGids"); 3625 3626 // reader 3627 synchronized (mPackages) { 3628 final PackageParser.Package p = mPackages.get(packageName); 3629 if (p != null && p.isMatch(flags)) { 3630 PackageSetting ps = (PackageSetting) p.mExtras; 3631 // TODO: Shouldn't this be checking for package installed state for userId and 3632 // return null? 3633 return ps.getPermissionsState().computeGids(userId); 3634 } 3635 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3636 final PackageSetting ps = mSettings.mPackages.get(packageName); 3637 if (ps != null && ps.isMatch(flags)) { 3638 return ps.getPermissionsState().computeGids(userId); 3639 } 3640 } 3641 } 3642 3643 return null; 3644 } 3645 3646 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3647 if (bp.perm != null) { 3648 return PackageParser.generatePermissionInfo(bp.perm, flags); 3649 } 3650 PermissionInfo pi = new PermissionInfo(); 3651 pi.name = bp.name; 3652 pi.packageName = bp.sourcePackage; 3653 pi.nonLocalizedLabel = bp.name; 3654 pi.protectionLevel = bp.protectionLevel; 3655 return pi; 3656 } 3657 3658 @Override 3659 public PermissionInfo getPermissionInfo(String name, int flags) { 3660 // reader 3661 synchronized (mPackages) { 3662 final BasePermission p = mSettings.mPermissions.get(name); 3663 if (p != null) { 3664 return generatePermissionInfo(p, flags); 3665 } 3666 return null; 3667 } 3668 } 3669 3670 @Override 3671 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3672 int flags) { 3673 // reader 3674 synchronized (mPackages) { 3675 if (group != null && !mPermissionGroups.containsKey(group)) { 3676 // This is thrown as NameNotFoundException 3677 return null; 3678 } 3679 3680 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3681 for (BasePermission p : mSettings.mPermissions.values()) { 3682 if (group == null) { 3683 if (p.perm == null || p.perm.info.group == null) { 3684 out.add(generatePermissionInfo(p, flags)); 3685 } 3686 } else { 3687 if (p.perm != null && group.equals(p.perm.info.group)) { 3688 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3689 } 3690 } 3691 } 3692 return new ParceledListSlice<>(out); 3693 } 3694 } 3695 3696 @Override 3697 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3698 // reader 3699 synchronized (mPackages) { 3700 return PackageParser.generatePermissionGroupInfo( 3701 mPermissionGroups.get(name), flags); 3702 } 3703 } 3704 3705 @Override 3706 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3707 // reader 3708 synchronized (mPackages) { 3709 final int N = mPermissionGroups.size(); 3710 ArrayList<PermissionGroupInfo> out 3711 = new ArrayList<PermissionGroupInfo>(N); 3712 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3713 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3714 } 3715 return new ParceledListSlice<>(out); 3716 } 3717 } 3718 3719 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3720 int uid, int userId) { 3721 if (!sUserManager.exists(userId)) return null; 3722 PackageSetting ps = mSettings.mPackages.get(packageName); 3723 if (ps != null) { 3724 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3725 return null; 3726 } 3727 if (ps.pkg == null) { 3728 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3729 if (pInfo != null) { 3730 return pInfo.applicationInfo; 3731 } 3732 return null; 3733 } 3734 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3735 ps.readUserState(userId), userId); 3736 if (ai != null) { 3737 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3738 } 3739 return ai; 3740 } 3741 return null; 3742 } 3743 3744 @Override 3745 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3746 if (!sUserManager.exists(userId)) return null; 3747 flags = updateFlagsForApplication(flags, userId, packageName); 3748 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3749 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3750 3751 // writer 3752 synchronized (mPackages) { 3753 // Normalize package name to handle renamed packages and static libs 3754 packageName = resolveInternalPackageNameLPr(packageName, 3755 PackageManager.VERSION_CODE_HIGHEST); 3756 3757 PackageParser.Package p = mPackages.get(packageName); 3758 if (DEBUG_PACKAGE_INFO) Log.v( 3759 TAG, "getApplicationInfo " + packageName 3760 + ": " + p); 3761 if (p != null) { 3762 PackageSetting ps = mSettings.mPackages.get(packageName); 3763 if (ps == null) return null; 3764 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3765 return null; 3766 } 3767 // Note: isEnabledLP() does not apply here - always return info 3768 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3769 p, flags, ps.readUserState(userId), userId); 3770 if (ai != null) { 3771 ai.packageName = resolveExternalPackageNameLPr(p); 3772 } 3773 return ai; 3774 } 3775 if ("android".equals(packageName)||"system".equals(packageName)) { 3776 return mAndroidApplication; 3777 } 3778 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3779 // Already generates the external package name 3780 return generateApplicationInfoFromSettingsLPw(packageName, 3781 Binder.getCallingUid(), flags, userId); 3782 } 3783 } 3784 return null; 3785 } 3786 3787 private String normalizePackageNameLPr(String packageName) { 3788 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3789 return normalizedPackageName != null ? normalizedPackageName : packageName; 3790 } 3791 3792 @Override 3793 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3794 final IPackageDataObserver observer) { 3795 mContext.enforceCallingOrSelfPermission( 3796 android.Manifest.permission.CLEAR_APP_CACHE, null); 3797 mHandler.post(() -> { 3798 boolean success = false; 3799 try { 3800 freeStorage(volumeUuid, freeStorageSize, 0); 3801 success = true; 3802 } catch (IOException e) { 3803 Slog.w(TAG, e); 3804 } 3805 if (observer != null) { 3806 try { 3807 observer.onRemoveCompleted(null, success); 3808 } catch (RemoteException e) { 3809 Slog.w(TAG, e); 3810 } 3811 } 3812 }); 3813 } 3814 3815 @Override 3816 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3817 final IntentSender pi) { 3818 mContext.enforceCallingOrSelfPermission( 3819 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3820 mHandler.post(() -> { 3821 boolean success = false; 3822 try { 3823 freeStorage(volumeUuid, freeStorageSize, 0); 3824 success = true; 3825 } catch (IOException e) { 3826 Slog.w(TAG, e); 3827 } 3828 if (pi != null) { 3829 try { 3830 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3831 } catch (SendIntentException e) { 3832 Slog.w(TAG, e); 3833 } 3834 } 3835 }); 3836 } 3837 3838 /** 3839 * Blocking call to clear various types of cached data across the system 3840 * until the requested bytes are available. 3841 */ 3842 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3843 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3844 final File file = storage.findPathForUuid(volumeUuid); 3845 3846 if (ENABLE_FREE_CACHE_V2) { 3847 final boolean aggressive = (storageFlags 3848 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3849 3850 // 1. Pre-flight to determine if we have any chance to succeed 3851 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3852 3853 // 3. Consider parsed APK data (aggressive only) 3854 if (aggressive) { 3855 FileUtils.deleteContents(mCacheDir); 3856 } 3857 if (file.getUsableSpace() >= bytes) return; 3858 3859 // 4. Consider cached app data (above quotas) 3860 try { 3861 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3862 } catch (InstallerException ignored) { 3863 } 3864 if (file.getUsableSpace() >= bytes) return; 3865 3866 // 5. Consider shared libraries with refcount=0 and age>2h 3867 // 6. Consider dexopt output (aggressive only) 3868 // 7. Consider ephemeral apps not used in last week 3869 3870 // 8. Consider cached app data (below quotas) 3871 try { 3872 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3873 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3874 } catch (InstallerException ignored) { 3875 } 3876 if (file.getUsableSpace() >= bytes) return; 3877 3878 // 9. Consider DropBox entries 3879 // 10. Consider ephemeral cookies 3880 3881 } else { 3882 try { 3883 mInstaller.freeCache(volumeUuid, bytes, 0); 3884 } catch (InstallerException ignored) { 3885 } 3886 if (file.getUsableSpace() >= bytes) return; 3887 } 3888 3889 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3890 } 3891 3892 /** 3893 * Update given flags based on encryption status of current user. 3894 */ 3895 private int updateFlags(int flags, int userId) { 3896 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3897 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3898 // Caller expressed an explicit opinion about what encryption 3899 // aware/unaware components they want to see, so fall through and 3900 // give them what they want 3901 } else { 3902 // Caller expressed no opinion, so match based on user state 3903 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3904 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3905 } else { 3906 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3907 } 3908 } 3909 return flags; 3910 } 3911 3912 private UserManagerInternal getUserManagerInternal() { 3913 if (mUserManagerInternal == null) { 3914 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3915 } 3916 return mUserManagerInternal; 3917 } 3918 3919 private DeviceIdleController.LocalService getDeviceIdleController() { 3920 if (mDeviceIdleController == null) { 3921 mDeviceIdleController = 3922 LocalServices.getService(DeviceIdleController.LocalService.class); 3923 } 3924 return mDeviceIdleController; 3925 } 3926 3927 /** 3928 * Update given flags when being used to request {@link PackageInfo}. 3929 */ 3930 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3931 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3932 boolean triaged = true; 3933 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3934 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3935 // Caller is asking for component details, so they'd better be 3936 // asking for specific encryption matching behavior, or be triaged 3937 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3938 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3939 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3940 triaged = false; 3941 } 3942 } 3943 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3944 | PackageManager.MATCH_SYSTEM_ONLY 3945 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3946 triaged = false; 3947 } 3948 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3949 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3950 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3951 + Debug.getCallers(5)); 3952 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3953 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3954 // If the caller wants all packages and has a restricted profile associated with it, 3955 // then match all users. This is to make sure that launchers that need to access work 3956 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3957 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3958 flags |= PackageManager.MATCH_ANY_USER; 3959 } 3960 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3961 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3962 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3963 } 3964 return updateFlags(flags, userId); 3965 } 3966 3967 /** 3968 * Update given flags when being used to request {@link ApplicationInfo}. 3969 */ 3970 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3971 return updateFlagsForPackage(flags, userId, cookie); 3972 } 3973 3974 /** 3975 * Update given flags when being used to request {@link ComponentInfo}. 3976 */ 3977 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3978 if (cookie instanceof Intent) { 3979 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3980 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3981 } 3982 } 3983 3984 boolean triaged = true; 3985 // Caller is asking for component details, so they'd better be 3986 // asking for specific encryption matching behavior, or be triaged 3987 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3988 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3989 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3990 triaged = false; 3991 } 3992 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3993 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3994 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3995 } 3996 3997 return updateFlags(flags, userId); 3998 } 3999 4000 /** 4001 * Update given intent when being used to request {@link ResolveInfo}. 4002 */ 4003 private Intent updateIntentForResolve(Intent intent) { 4004 if (intent.getSelector() != null) { 4005 intent = intent.getSelector(); 4006 } 4007 if (DEBUG_PREFERRED) { 4008 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4009 } 4010 return intent; 4011 } 4012 4013 /** 4014 * Update given flags when being used to request {@link ResolveInfo}. 4015 */ 4016 int updateFlagsForResolve(int flags, int userId, Object cookie) { 4017 // Safe mode means we shouldn't match any third-party components 4018 if (mSafeMode) { 4019 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4020 } 4021 final int callingUid = Binder.getCallingUid(); 4022 if (getInstantAppPackageName(callingUid) != null) { 4023 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4024 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4025 flags |= PackageManager.MATCH_INSTANT; 4026 } else { 4027 // Otherwise, prevent leaking ephemeral components 4028 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4029 if (callingUid != Process.SYSTEM_UID 4030 && callingUid != Process.SHELL_UID 4031 && callingUid != 0) { 4032 // Unless called from the system process 4033 flags &= ~PackageManager.MATCH_INSTANT; 4034 } 4035 } 4036 return updateFlagsForComponent(flags, userId, cookie); 4037 } 4038 4039 @Override 4040 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4041 if (!sUserManager.exists(userId)) return null; 4042 flags = updateFlagsForComponent(flags, userId, component); 4043 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4044 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4045 synchronized (mPackages) { 4046 PackageParser.Activity a = mActivities.mActivities.get(component); 4047 4048 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4049 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4050 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4051 if (ps == null) return null; 4052 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4053 userId); 4054 } 4055 if (mResolveComponentName.equals(component)) { 4056 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4057 new PackageUserState(), userId); 4058 } 4059 } 4060 return null; 4061 } 4062 4063 @Override 4064 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4065 String resolvedType) { 4066 synchronized (mPackages) { 4067 if (component.equals(mResolveComponentName)) { 4068 // The resolver supports EVERYTHING! 4069 return true; 4070 } 4071 PackageParser.Activity a = mActivities.mActivities.get(component); 4072 if (a == null) { 4073 return false; 4074 } 4075 for (int i=0; i<a.intents.size(); i++) { 4076 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4077 intent.getData(), intent.getCategories(), TAG) >= 0) { 4078 return true; 4079 } 4080 } 4081 return false; 4082 } 4083 } 4084 4085 @Override 4086 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4087 if (!sUserManager.exists(userId)) return null; 4088 flags = updateFlagsForComponent(flags, userId, component); 4089 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4090 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4091 synchronized (mPackages) { 4092 PackageParser.Activity a = mReceivers.mActivities.get(component); 4093 if (DEBUG_PACKAGE_INFO) Log.v( 4094 TAG, "getReceiverInfo " + component + ": " + a); 4095 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4096 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4097 if (ps == null) return null; 4098 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4099 userId); 4100 } 4101 } 4102 return null; 4103 } 4104 4105 @Override 4106 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4107 if (!sUserManager.exists(userId)) return null; 4108 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4109 4110 flags = updateFlagsForPackage(flags, userId, null); 4111 4112 final boolean canSeeStaticLibraries = 4113 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4114 == PERMISSION_GRANTED 4115 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4116 == PERMISSION_GRANTED 4117 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4118 == PERMISSION_GRANTED 4119 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4120 == PERMISSION_GRANTED; 4121 4122 synchronized (mPackages) { 4123 List<SharedLibraryInfo> result = null; 4124 4125 final int libCount = mSharedLibraries.size(); 4126 for (int i = 0; i < libCount; i++) { 4127 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4128 if (versionedLib == null) { 4129 continue; 4130 } 4131 4132 final int versionCount = versionedLib.size(); 4133 for (int j = 0; j < versionCount; j++) { 4134 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4135 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4136 break; 4137 } 4138 final long identity = Binder.clearCallingIdentity(); 4139 try { 4140 // TODO: We will change version code to long, so in the new API it is long 4141 PackageInfo packageInfo = getPackageInfoVersioned( 4142 libInfo.getDeclaringPackage(), flags, userId); 4143 if (packageInfo == null) { 4144 continue; 4145 } 4146 } finally { 4147 Binder.restoreCallingIdentity(identity); 4148 } 4149 4150 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4151 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4152 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4153 4154 if (result == null) { 4155 result = new ArrayList<>(); 4156 } 4157 result.add(resLibInfo); 4158 } 4159 } 4160 4161 return result != null ? new ParceledListSlice<>(result) : null; 4162 } 4163 } 4164 4165 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4166 SharedLibraryInfo libInfo, int flags, int userId) { 4167 List<VersionedPackage> versionedPackages = null; 4168 final int packageCount = mSettings.mPackages.size(); 4169 for (int i = 0; i < packageCount; i++) { 4170 PackageSetting ps = mSettings.mPackages.valueAt(i); 4171 4172 if (ps == null) { 4173 continue; 4174 } 4175 4176 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4177 continue; 4178 } 4179 4180 final String libName = libInfo.getName(); 4181 if (libInfo.isStatic()) { 4182 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4183 if (libIdx < 0) { 4184 continue; 4185 } 4186 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4187 continue; 4188 } 4189 if (versionedPackages == null) { 4190 versionedPackages = new ArrayList<>(); 4191 } 4192 // If the dependent is a static shared lib, use the public package name 4193 String dependentPackageName = ps.name; 4194 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4195 dependentPackageName = ps.pkg.manifestPackageName; 4196 } 4197 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4198 } else if (ps.pkg != null) { 4199 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4200 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4201 if (versionedPackages == null) { 4202 versionedPackages = new ArrayList<>(); 4203 } 4204 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4205 } 4206 } 4207 } 4208 4209 return versionedPackages; 4210 } 4211 4212 @Override 4213 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4214 if (!sUserManager.exists(userId)) return null; 4215 flags = updateFlagsForComponent(flags, userId, component); 4216 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4217 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4218 synchronized (mPackages) { 4219 PackageParser.Service s = mServices.mServices.get(component); 4220 if (DEBUG_PACKAGE_INFO) Log.v( 4221 TAG, "getServiceInfo " + component + ": " + s); 4222 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4223 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4224 if (ps == null) return null; 4225 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 4226 userId); 4227 } 4228 } 4229 return null; 4230 } 4231 4232 @Override 4233 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4234 if (!sUserManager.exists(userId)) return null; 4235 flags = updateFlagsForComponent(flags, userId, component); 4236 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4237 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4238 synchronized (mPackages) { 4239 PackageParser.Provider p = mProviders.mProviders.get(component); 4240 if (DEBUG_PACKAGE_INFO) Log.v( 4241 TAG, "getProviderInfo " + component + ": " + p); 4242 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4243 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4244 if (ps == null) return null; 4245 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 4246 userId); 4247 } 4248 } 4249 return null; 4250 } 4251 4252 @Override 4253 public String[] getSystemSharedLibraryNames() { 4254 synchronized (mPackages) { 4255 Set<String> libs = null; 4256 final int libCount = mSharedLibraries.size(); 4257 for (int i = 0; i < libCount; i++) { 4258 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4259 if (versionedLib == null) { 4260 continue; 4261 } 4262 final int versionCount = versionedLib.size(); 4263 for (int j = 0; j < versionCount; j++) { 4264 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4265 if (!libEntry.info.isStatic()) { 4266 if (libs == null) { 4267 libs = new ArraySet<>(); 4268 } 4269 libs.add(libEntry.info.getName()); 4270 break; 4271 } 4272 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4273 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4274 UserHandle.getUserId(Binder.getCallingUid()))) { 4275 if (libs == null) { 4276 libs = new ArraySet<>(); 4277 } 4278 libs.add(libEntry.info.getName()); 4279 break; 4280 } 4281 } 4282 } 4283 4284 if (libs != null) { 4285 String[] libsArray = new String[libs.size()]; 4286 libs.toArray(libsArray); 4287 return libsArray; 4288 } 4289 4290 return null; 4291 } 4292 } 4293 4294 @Override 4295 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4296 synchronized (mPackages) { 4297 return mServicesSystemSharedLibraryPackageName; 4298 } 4299 } 4300 4301 @Override 4302 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4303 synchronized (mPackages) { 4304 return mSharedSystemSharedLibraryPackageName; 4305 } 4306 } 4307 4308 private void updateSequenceNumberLP(String packageName, int[] userList) { 4309 for (int i = userList.length - 1; i >= 0; --i) { 4310 final int userId = userList[i]; 4311 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4312 if (changedPackages == null) { 4313 changedPackages = new SparseArray<>(); 4314 mChangedPackages.put(userId, changedPackages); 4315 } 4316 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4317 if (sequenceNumbers == null) { 4318 sequenceNumbers = new HashMap<>(); 4319 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4320 } 4321 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4322 if (sequenceNumber != null) { 4323 changedPackages.remove(sequenceNumber); 4324 } 4325 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4326 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4327 } 4328 mChangedPackagesSequenceNumber++; 4329 } 4330 4331 @Override 4332 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4333 synchronized (mPackages) { 4334 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4335 return null; 4336 } 4337 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4338 if (changedPackages == null) { 4339 return null; 4340 } 4341 final List<String> packageNames = 4342 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4343 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4344 final String packageName = changedPackages.get(i); 4345 if (packageName != null) { 4346 packageNames.add(packageName); 4347 } 4348 } 4349 return packageNames.isEmpty() 4350 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4351 } 4352 } 4353 4354 @Override 4355 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4356 ArrayList<FeatureInfo> res; 4357 synchronized (mAvailableFeatures) { 4358 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4359 res.addAll(mAvailableFeatures.values()); 4360 } 4361 final FeatureInfo fi = new FeatureInfo(); 4362 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4363 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4364 res.add(fi); 4365 4366 return new ParceledListSlice<>(res); 4367 } 4368 4369 @Override 4370 public boolean hasSystemFeature(String name, int version) { 4371 synchronized (mAvailableFeatures) { 4372 final FeatureInfo feat = mAvailableFeatures.get(name); 4373 if (feat == null) { 4374 return false; 4375 } else { 4376 return feat.version >= version; 4377 } 4378 } 4379 } 4380 4381 @Override 4382 public int checkPermission(String permName, String pkgName, int userId) { 4383 if (!sUserManager.exists(userId)) { 4384 return PackageManager.PERMISSION_DENIED; 4385 } 4386 4387 synchronized (mPackages) { 4388 final PackageParser.Package p = mPackages.get(pkgName); 4389 if (p != null && p.mExtras != null) { 4390 final PackageSetting ps = (PackageSetting) p.mExtras; 4391 final PermissionsState permissionsState = ps.getPermissionsState(); 4392 if (permissionsState.hasPermission(permName, userId)) { 4393 return PackageManager.PERMISSION_GRANTED; 4394 } 4395 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4396 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4397 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4398 return PackageManager.PERMISSION_GRANTED; 4399 } 4400 } 4401 } 4402 4403 return PackageManager.PERMISSION_DENIED; 4404 } 4405 4406 @Override 4407 public int checkUidPermission(String permName, int uid) { 4408 final int userId = UserHandle.getUserId(uid); 4409 4410 if (!sUserManager.exists(userId)) { 4411 return PackageManager.PERMISSION_DENIED; 4412 } 4413 4414 synchronized (mPackages) { 4415 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4416 if (obj != null) { 4417 final SettingBase ps = (SettingBase) obj; 4418 final PermissionsState permissionsState = ps.getPermissionsState(); 4419 if (permissionsState.hasPermission(permName, userId)) { 4420 return PackageManager.PERMISSION_GRANTED; 4421 } 4422 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4423 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4424 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4425 return PackageManager.PERMISSION_GRANTED; 4426 } 4427 } else { 4428 ArraySet<String> perms = mSystemPermissions.get(uid); 4429 if (perms != null) { 4430 if (perms.contains(permName)) { 4431 return PackageManager.PERMISSION_GRANTED; 4432 } 4433 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4434 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4435 return PackageManager.PERMISSION_GRANTED; 4436 } 4437 } 4438 } 4439 } 4440 4441 return PackageManager.PERMISSION_DENIED; 4442 } 4443 4444 @Override 4445 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4446 if (UserHandle.getCallingUserId() != userId) { 4447 mContext.enforceCallingPermission( 4448 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4449 "isPermissionRevokedByPolicy for user " + userId); 4450 } 4451 4452 if (checkPermission(permission, packageName, userId) 4453 == PackageManager.PERMISSION_GRANTED) { 4454 return false; 4455 } 4456 4457 final long identity = Binder.clearCallingIdentity(); 4458 try { 4459 final int flags = getPermissionFlags(permission, packageName, userId); 4460 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4461 } finally { 4462 Binder.restoreCallingIdentity(identity); 4463 } 4464 } 4465 4466 @Override 4467 public String getPermissionControllerPackageName() { 4468 synchronized (mPackages) { 4469 return mRequiredInstallerPackage; 4470 } 4471 } 4472 4473 /** 4474 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4475 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4476 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4477 * @param message the message to log on security exception 4478 */ 4479 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4480 boolean checkShell, String message) { 4481 if (userId < 0) { 4482 throw new IllegalArgumentException("Invalid userId " + userId); 4483 } 4484 if (checkShell) { 4485 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4486 } 4487 if (userId == UserHandle.getUserId(callingUid)) return; 4488 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4489 if (requireFullPermission) { 4490 mContext.enforceCallingOrSelfPermission( 4491 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4492 } else { 4493 try { 4494 mContext.enforceCallingOrSelfPermission( 4495 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4496 } catch (SecurityException se) { 4497 mContext.enforceCallingOrSelfPermission( 4498 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4499 } 4500 } 4501 } 4502 } 4503 4504 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4505 if (callingUid == Process.SHELL_UID) { 4506 if (userHandle >= 0 4507 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4508 throw new SecurityException("Shell does not have permission to access user " 4509 + userHandle); 4510 } else if (userHandle < 0) { 4511 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4512 + Debug.getCallers(3)); 4513 } 4514 } 4515 } 4516 4517 private BasePermission findPermissionTreeLP(String permName) { 4518 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4519 if (permName.startsWith(bp.name) && 4520 permName.length() > bp.name.length() && 4521 permName.charAt(bp.name.length()) == '.') { 4522 return bp; 4523 } 4524 } 4525 return null; 4526 } 4527 4528 private BasePermission checkPermissionTreeLP(String permName) { 4529 if (permName != null) { 4530 BasePermission bp = findPermissionTreeLP(permName); 4531 if (bp != null) { 4532 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4533 return bp; 4534 } 4535 throw new SecurityException("Calling uid " 4536 + Binder.getCallingUid() 4537 + " is not allowed to add to permission tree " 4538 + bp.name + " owned by uid " + bp.uid); 4539 } 4540 } 4541 throw new SecurityException("No permission tree found for " + permName); 4542 } 4543 4544 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4545 if (s1 == null) { 4546 return s2 == null; 4547 } 4548 if (s2 == null) { 4549 return false; 4550 } 4551 if (s1.getClass() != s2.getClass()) { 4552 return false; 4553 } 4554 return s1.equals(s2); 4555 } 4556 4557 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4558 if (pi1.icon != pi2.icon) return false; 4559 if (pi1.logo != pi2.logo) return false; 4560 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4561 if (!compareStrings(pi1.name, pi2.name)) return false; 4562 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4563 // We'll take care of setting this one. 4564 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4565 // These are not currently stored in settings. 4566 //if (!compareStrings(pi1.group, pi2.group)) return false; 4567 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4568 //if (pi1.labelRes != pi2.labelRes) return false; 4569 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4570 return true; 4571 } 4572 4573 int permissionInfoFootprint(PermissionInfo info) { 4574 int size = info.name.length(); 4575 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4576 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4577 return size; 4578 } 4579 4580 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4581 int size = 0; 4582 for (BasePermission perm : mSettings.mPermissions.values()) { 4583 if (perm.uid == tree.uid) { 4584 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4585 } 4586 } 4587 return size; 4588 } 4589 4590 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4591 // We calculate the max size of permissions defined by this uid and throw 4592 // if that plus the size of 'info' would exceed our stated maximum. 4593 if (tree.uid != Process.SYSTEM_UID) { 4594 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4595 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4596 throw new SecurityException("Permission tree size cap exceeded"); 4597 } 4598 } 4599 } 4600 4601 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4602 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4603 throw new SecurityException("Label must be specified in permission"); 4604 } 4605 BasePermission tree = checkPermissionTreeLP(info.name); 4606 BasePermission bp = mSettings.mPermissions.get(info.name); 4607 boolean added = bp == null; 4608 boolean changed = true; 4609 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4610 if (added) { 4611 enforcePermissionCapLocked(info, tree); 4612 bp = new BasePermission(info.name, tree.sourcePackage, 4613 BasePermission.TYPE_DYNAMIC); 4614 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4615 throw new SecurityException( 4616 "Not allowed to modify non-dynamic permission " 4617 + info.name); 4618 } else { 4619 if (bp.protectionLevel == fixedLevel 4620 && bp.perm.owner.equals(tree.perm.owner) 4621 && bp.uid == tree.uid 4622 && comparePermissionInfos(bp.perm.info, info)) { 4623 changed = false; 4624 } 4625 } 4626 bp.protectionLevel = fixedLevel; 4627 info = new PermissionInfo(info); 4628 info.protectionLevel = fixedLevel; 4629 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4630 bp.perm.info.packageName = tree.perm.info.packageName; 4631 bp.uid = tree.uid; 4632 if (added) { 4633 mSettings.mPermissions.put(info.name, bp); 4634 } 4635 if (changed) { 4636 if (!async) { 4637 mSettings.writeLPr(); 4638 } else { 4639 scheduleWriteSettingsLocked(); 4640 } 4641 } 4642 return added; 4643 } 4644 4645 @Override 4646 public boolean addPermission(PermissionInfo info) { 4647 synchronized (mPackages) { 4648 return addPermissionLocked(info, false); 4649 } 4650 } 4651 4652 @Override 4653 public boolean addPermissionAsync(PermissionInfo info) { 4654 synchronized (mPackages) { 4655 return addPermissionLocked(info, true); 4656 } 4657 } 4658 4659 @Override 4660 public void removePermission(String name) { 4661 synchronized (mPackages) { 4662 checkPermissionTreeLP(name); 4663 BasePermission bp = mSettings.mPermissions.get(name); 4664 if (bp != null) { 4665 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4666 throw new SecurityException( 4667 "Not allowed to modify non-dynamic permission " 4668 + name); 4669 } 4670 mSettings.mPermissions.remove(name); 4671 mSettings.writeLPr(); 4672 } 4673 } 4674 } 4675 4676 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4677 BasePermission bp) { 4678 int index = pkg.requestedPermissions.indexOf(bp.name); 4679 if (index == -1) { 4680 throw new SecurityException("Package " + pkg.packageName 4681 + " has not requested permission " + bp.name); 4682 } 4683 if (!bp.isRuntime() && !bp.isDevelopment()) { 4684 throw new SecurityException("Permission " + bp.name 4685 + " is not a changeable permission type"); 4686 } 4687 } 4688 4689 @Override 4690 public void grantRuntimePermission(String packageName, String name, final int userId) { 4691 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4692 } 4693 4694 private void grantRuntimePermission(String packageName, String name, final int userId, 4695 boolean overridePolicy) { 4696 if (!sUserManager.exists(userId)) { 4697 Log.e(TAG, "No such user:" + userId); 4698 return; 4699 } 4700 4701 mContext.enforceCallingOrSelfPermission( 4702 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4703 "grantRuntimePermission"); 4704 4705 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4706 true /* requireFullPermission */, true /* checkShell */, 4707 "grantRuntimePermission"); 4708 4709 final int uid; 4710 final SettingBase sb; 4711 4712 synchronized (mPackages) { 4713 final PackageParser.Package pkg = mPackages.get(packageName); 4714 if (pkg == null) { 4715 throw new IllegalArgumentException("Unknown package: " + packageName); 4716 } 4717 4718 final BasePermission bp = mSettings.mPermissions.get(name); 4719 if (bp == null) { 4720 throw new IllegalArgumentException("Unknown permission: " + name); 4721 } 4722 4723 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4724 4725 // If a permission review is required for legacy apps we represent 4726 // their permissions as always granted runtime ones since we need 4727 // to keep the review required permission flag per user while an 4728 // install permission's state is shared across all users. 4729 if (mPermissionReviewRequired 4730 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4731 && bp.isRuntime()) { 4732 return; 4733 } 4734 4735 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4736 sb = (SettingBase) pkg.mExtras; 4737 if (sb == null) { 4738 throw new IllegalArgumentException("Unknown package: " + packageName); 4739 } 4740 4741 final PermissionsState permissionsState = sb.getPermissionsState(); 4742 4743 final int flags = permissionsState.getPermissionFlags(name, userId); 4744 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4745 throw new SecurityException("Cannot grant system fixed permission " 4746 + name + " for package " + packageName); 4747 } 4748 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4749 throw new SecurityException("Cannot grant policy fixed permission " 4750 + name + " for package " + packageName); 4751 } 4752 4753 if (bp.isDevelopment()) { 4754 // Development permissions must be handled specially, since they are not 4755 // normal runtime permissions. For now they apply to all users. 4756 if (permissionsState.grantInstallPermission(bp) != 4757 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4758 scheduleWriteSettingsLocked(); 4759 } 4760 return; 4761 } 4762 4763 final PackageSetting ps = mSettings.mPackages.get(packageName); 4764 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4765 throw new SecurityException("Cannot grant non-ephemeral permission" 4766 + name + " for package " + packageName); 4767 } 4768 4769 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4770 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4771 return; 4772 } 4773 4774 final int result = permissionsState.grantRuntimePermission(bp, userId); 4775 switch (result) { 4776 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4777 return; 4778 } 4779 4780 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4781 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4782 mHandler.post(new Runnable() { 4783 @Override 4784 public void run() { 4785 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4786 } 4787 }); 4788 } 4789 break; 4790 } 4791 4792 if (bp.isRuntime()) { 4793 logPermissionGranted(mContext, name, packageName); 4794 } 4795 4796 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4797 4798 // Not critical if that is lost - app has to request again. 4799 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4800 } 4801 4802 // Only need to do this if user is initialized. Otherwise it's a new user 4803 // and there are no processes running as the user yet and there's no need 4804 // to make an expensive call to remount processes for the changed permissions. 4805 if (READ_EXTERNAL_STORAGE.equals(name) 4806 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4807 final long token = Binder.clearCallingIdentity(); 4808 try { 4809 if (sUserManager.isInitialized(userId)) { 4810 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4811 StorageManagerInternal.class); 4812 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4813 } 4814 } finally { 4815 Binder.restoreCallingIdentity(token); 4816 } 4817 } 4818 } 4819 4820 @Override 4821 public void revokeRuntimePermission(String packageName, String name, int userId) { 4822 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4823 } 4824 4825 private void revokeRuntimePermission(String packageName, String name, int userId, 4826 boolean overridePolicy) { 4827 if (!sUserManager.exists(userId)) { 4828 Log.e(TAG, "No such user:" + userId); 4829 return; 4830 } 4831 4832 mContext.enforceCallingOrSelfPermission( 4833 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4834 "revokeRuntimePermission"); 4835 4836 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4837 true /* requireFullPermission */, true /* checkShell */, 4838 "revokeRuntimePermission"); 4839 4840 final int appId; 4841 4842 synchronized (mPackages) { 4843 final PackageParser.Package pkg = mPackages.get(packageName); 4844 if (pkg == null) { 4845 throw new IllegalArgumentException("Unknown package: " + packageName); 4846 } 4847 4848 final BasePermission bp = mSettings.mPermissions.get(name); 4849 if (bp == null) { 4850 throw new IllegalArgumentException("Unknown permission: " + name); 4851 } 4852 4853 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4854 4855 // If a permission review is required for legacy apps we represent 4856 // their permissions as always granted runtime ones since we need 4857 // to keep the review required permission flag per user while an 4858 // install permission's state is shared across all users. 4859 if (mPermissionReviewRequired 4860 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4861 && bp.isRuntime()) { 4862 return; 4863 } 4864 4865 SettingBase sb = (SettingBase) pkg.mExtras; 4866 if (sb == null) { 4867 throw new IllegalArgumentException("Unknown package: " + packageName); 4868 } 4869 4870 final PermissionsState permissionsState = sb.getPermissionsState(); 4871 4872 final int flags = permissionsState.getPermissionFlags(name, userId); 4873 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4874 throw new SecurityException("Cannot revoke system fixed permission " 4875 + name + " for package " + packageName); 4876 } 4877 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4878 throw new SecurityException("Cannot revoke policy fixed permission " 4879 + name + " for package " + packageName); 4880 } 4881 4882 if (bp.isDevelopment()) { 4883 // Development permissions must be handled specially, since they are not 4884 // normal runtime permissions. For now they apply to all users. 4885 if (permissionsState.revokeInstallPermission(bp) != 4886 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4887 scheduleWriteSettingsLocked(); 4888 } 4889 return; 4890 } 4891 4892 if (permissionsState.revokeRuntimePermission(bp, userId) == 4893 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4894 return; 4895 } 4896 4897 if (bp.isRuntime()) { 4898 logPermissionRevoked(mContext, name, packageName); 4899 } 4900 4901 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4902 4903 // Critical, after this call app should never have the permission. 4904 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4905 4906 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4907 } 4908 4909 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4910 } 4911 4912 /** 4913 * Get the first event id for the permission. 4914 * 4915 * <p>There are four events for each permission: <ul> 4916 * <li>Request permission: first id + 0</li> 4917 * <li>Grant permission: first id + 1</li> 4918 * <li>Request for permission denied: first id + 2</li> 4919 * <li>Revoke permission: first id + 3</li> 4920 * </ul></p> 4921 * 4922 * @param name name of the permission 4923 * 4924 * @return The first event id for the permission 4925 */ 4926 private static int getBaseEventId(@NonNull String name) { 4927 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4928 4929 if (eventIdIndex == -1) { 4930 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4931 || "user".equals(Build.TYPE)) { 4932 Log.i(TAG, "Unknown permission " + name); 4933 4934 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4935 } else { 4936 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4937 // 4938 // Also update 4939 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4940 // - metrics_constants.proto 4941 throw new IllegalStateException("Unknown permission " + name); 4942 } 4943 } 4944 4945 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4946 } 4947 4948 /** 4949 * Log that a permission was revoked. 4950 * 4951 * @param context Context of the caller 4952 * @param name name of the permission 4953 * @param packageName package permission if for 4954 */ 4955 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4956 @NonNull String packageName) { 4957 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4958 } 4959 4960 /** 4961 * Log that a permission request was granted. 4962 * 4963 * @param context Context of the caller 4964 * @param name name of the permission 4965 * @param packageName package permission if for 4966 */ 4967 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4968 @NonNull String packageName) { 4969 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4970 } 4971 4972 @Override 4973 public void resetRuntimePermissions() { 4974 mContext.enforceCallingOrSelfPermission( 4975 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4976 "revokeRuntimePermission"); 4977 4978 int callingUid = Binder.getCallingUid(); 4979 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4980 mContext.enforceCallingOrSelfPermission( 4981 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4982 "resetRuntimePermissions"); 4983 } 4984 4985 synchronized (mPackages) { 4986 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4987 for (int userId : UserManagerService.getInstance().getUserIds()) { 4988 final int packageCount = mPackages.size(); 4989 for (int i = 0; i < packageCount; i++) { 4990 PackageParser.Package pkg = mPackages.valueAt(i); 4991 if (!(pkg.mExtras instanceof PackageSetting)) { 4992 continue; 4993 } 4994 PackageSetting ps = (PackageSetting) pkg.mExtras; 4995 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4996 } 4997 } 4998 } 4999 } 5000 5001 @Override 5002 public int getPermissionFlags(String name, String packageName, int userId) { 5003 if (!sUserManager.exists(userId)) { 5004 return 0; 5005 } 5006 5007 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5008 5009 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5010 true /* requireFullPermission */, false /* checkShell */, 5011 "getPermissionFlags"); 5012 5013 synchronized (mPackages) { 5014 final PackageParser.Package pkg = mPackages.get(packageName); 5015 if (pkg == null) { 5016 return 0; 5017 } 5018 5019 final BasePermission bp = mSettings.mPermissions.get(name); 5020 if (bp == null) { 5021 return 0; 5022 } 5023 5024 SettingBase sb = (SettingBase) pkg.mExtras; 5025 if (sb == null) { 5026 return 0; 5027 } 5028 5029 PermissionsState permissionsState = sb.getPermissionsState(); 5030 return permissionsState.getPermissionFlags(name, userId); 5031 } 5032 } 5033 5034 @Override 5035 public void updatePermissionFlags(String name, String packageName, int flagMask, 5036 int flagValues, int userId) { 5037 if (!sUserManager.exists(userId)) { 5038 return; 5039 } 5040 5041 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5042 5043 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5044 true /* requireFullPermission */, true /* checkShell */, 5045 "updatePermissionFlags"); 5046 5047 // Only the system can change these flags and nothing else. 5048 if (getCallingUid() != Process.SYSTEM_UID) { 5049 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5050 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5051 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5052 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5053 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5054 } 5055 5056 synchronized (mPackages) { 5057 final PackageParser.Package pkg = mPackages.get(packageName); 5058 if (pkg == null) { 5059 throw new IllegalArgumentException("Unknown package: " + packageName); 5060 } 5061 5062 final BasePermission bp = mSettings.mPermissions.get(name); 5063 if (bp == null) { 5064 throw new IllegalArgumentException("Unknown permission: " + name); 5065 } 5066 5067 SettingBase sb = (SettingBase) pkg.mExtras; 5068 if (sb == null) { 5069 throw new IllegalArgumentException("Unknown package: " + packageName); 5070 } 5071 5072 PermissionsState permissionsState = sb.getPermissionsState(); 5073 5074 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5075 5076 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5077 // Install and runtime permissions are stored in different places, 5078 // so figure out what permission changed and persist the change. 5079 if (permissionsState.getInstallPermissionState(name) != null) { 5080 scheduleWriteSettingsLocked(); 5081 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5082 || hadState) { 5083 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5084 } 5085 } 5086 } 5087 } 5088 5089 /** 5090 * Update the permission flags for all packages and runtime permissions of a user in order 5091 * to allow device or profile owner to remove POLICY_FIXED. 5092 */ 5093 @Override 5094 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5095 if (!sUserManager.exists(userId)) { 5096 return; 5097 } 5098 5099 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5100 5101 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5102 true /* requireFullPermission */, true /* checkShell */, 5103 "updatePermissionFlagsForAllApps"); 5104 5105 // Only the system can change system fixed flags. 5106 if (getCallingUid() != Process.SYSTEM_UID) { 5107 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5108 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5109 } 5110 5111 synchronized (mPackages) { 5112 boolean changed = false; 5113 final int packageCount = mPackages.size(); 5114 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5115 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5116 SettingBase sb = (SettingBase) pkg.mExtras; 5117 if (sb == null) { 5118 continue; 5119 } 5120 PermissionsState permissionsState = sb.getPermissionsState(); 5121 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5122 userId, flagMask, flagValues); 5123 } 5124 if (changed) { 5125 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5126 } 5127 } 5128 } 5129 5130 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5131 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5132 != PackageManager.PERMISSION_GRANTED 5133 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5134 != PackageManager.PERMISSION_GRANTED) { 5135 throw new SecurityException(message + " requires " 5136 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5137 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5138 } 5139 } 5140 5141 @Override 5142 public boolean shouldShowRequestPermissionRationale(String permissionName, 5143 String packageName, int userId) { 5144 if (UserHandle.getCallingUserId() != userId) { 5145 mContext.enforceCallingPermission( 5146 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5147 "canShowRequestPermissionRationale for user " + userId); 5148 } 5149 5150 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5151 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5152 return false; 5153 } 5154 5155 if (checkPermission(permissionName, packageName, userId) 5156 == PackageManager.PERMISSION_GRANTED) { 5157 return false; 5158 } 5159 5160 final int flags; 5161 5162 final long identity = Binder.clearCallingIdentity(); 5163 try { 5164 flags = getPermissionFlags(permissionName, 5165 packageName, userId); 5166 } finally { 5167 Binder.restoreCallingIdentity(identity); 5168 } 5169 5170 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5171 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5172 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5173 5174 if ((flags & fixedFlags) != 0) { 5175 return false; 5176 } 5177 5178 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5179 } 5180 5181 @Override 5182 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5183 mContext.enforceCallingOrSelfPermission( 5184 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5185 "addOnPermissionsChangeListener"); 5186 5187 synchronized (mPackages) { 5188 mOnPermissionChangeListeners.addListenerLocked(listener); 5189 } 5190 } 5191 5192 @Override 5193 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5194 synchronized (mPackages) { 5195 mOnPermissionChangeListeners.removeListenerLocked(listener); 5196 } 5197 } 5198 5199 @Override 5200 public boolean isProtectedBroadcast(String actionName) { 5201 synchronized (mPackages) { 5202 if (mProtectedBroadcasts.contains(actionName)) { 5203 return true; 5204 } else if (actionName != null) { 5205 // TODO: remove these terrible hacks 5206 if (actionName.startsWith("android.net.netmon.lingerExpired") 5207 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5208 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5209 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5210 return true; 5211 } 5212 } 5213 } 5214 return false; 5215 } 5216 5217 @Override 5218 public int checkSignatures(String pkg1, String pkg2) { 5219 synchronized (mPackages) { 5220 final PackageParser.Package p1 = mPackages.get(pkg1); 5221 final PackageParser.Package p2 = mPackages.get(pkg2); 5222 if (p1 == null || p1.mExtras == null 5223 || p2 == null || p2.mExtras == null) { 5224 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5225 } 5226 return compareSignatures(p1.mSignatures, p2.mSignatures); 5227 } 5228 } 5229 5230 @Override 5231 public int checkUidSignatures(int uid1, int uid2) { 5232 // Map to base uids. 5233 uid1 = UserHandle.getAppId(uid1); 5234 uid2 = UserHandle.getAppId(uid2); 5235 // reader 5236 synchronized (mPackages) { 5237 Signature[] s1; 5238 Signature[] s2; 5239 Object obj = mSettings.getUserIdLPr(uid1); 5240 if (obj != null) { 5241 if (obj instanceof SharedUserSetting) { 5242 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5243 } else if (obj instanceof PackageSetting) { 5244 s1 = ((PackageSetting)obj).signatures.mSignatures; 5245 } else { 5246 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5247 } 5248 } else { 5249 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5250 } 5251 obj = mSettings.getUserIdLPr(uid2); 5252 if (obj != null) { 5253 if (obj instanceof SharedUserSetting) { 5254 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5255 } else if (obj instanceof PackageSetting) { 5256 s2 = ((PackageSetting)obj).signatures.mSignatures; 5257 } else { 5258 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5259 } 5260 } else { 5261 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5262 } 5263 return compareSignatures(s1, s2); 5264 } 5265 } 5266 5267 /** 5268 * This method should typically only be used when granting or revoking 5269 * permissions, since the app may immediately restart after this call. 5270 * <p> 5271 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5272 * guard your work against the app being relaunched. 5273 */ 5274 private void killUid(int appId, int userId, String reason) { 5275 final long identity = Binder.clearCallingIdentity(); 5276 try { 5277 IActivityManager am = ActivityManager.getService(); 5278 if (am != null) { 5279 try { 5280 am.killUid(appId, userId, reason); 5281 } catch (RemoteException e) { 5282 /* ignore - same process */ 5283 } 5284 } 5285 } finally { 5286 Binder.restoreCallingIdentity(identity); 5287 } 5288 } 5289 5290 /** 5291 * Compares two sets of signatures. Returns: 5292 * <br /> 5293 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5294 * <br /> 5295 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5296 * <br /> 5297 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5298 * <br /> 5299 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5300 * <br /> 5301 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5302 */ 5303 static int compareSignatures(Signature[] s1, Signature[] s2) { 5304 if (s1 == null) { 5305 return s2 == null 5306 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5307 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5308 } 5309 5310 if (s2 == null) { 5311 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5312 } 5313 5314 if (s1.length != s2.length) { 5315 return PackageManager.SIGNATURE_NO_MATCH; 5316 } 5317 5318 // Since both signature sets are of size 1, we can compare without HashSets. 5319 if (s1.length == 1) { 5320 return s1[0].equals(s2[0]) ? 5321 PackageManager.SIGNATURE_MATCH : 5322 PackageManager.SIGNATURE_NO_MATCH; 5323 } 5324 5325 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5326 for (Signature sig : s1) { 5327 set1.add(sig); 5328 } 5329 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5330 for (Signature sig : s2) { 5331 set2.add(sig); 5332 } 5333 // Make sure s2 contains all signatures in s1. 5334 if (set1.equals(set2)) { 5335 return PackageManager.SIGNATURE_MATCH; 5336 } 5337 return PackageManager.SIGNATURE_NO_MATCH; 5338 } 5339 5340 /** 5341 * If the database version for this type of package (internal storage or 5342 * external storage) is less than the version where package signatures 5343 * were updated, return true. 5344 */ 5345 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5346 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5347 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5348 } 5349 5350 /** 5351 * Used for backward compatibility to make sure any packages with 5352 * certificate chains get upgraded to the new style. {@code existingSigs} 5353 * will be in the old format (since they were stored on disk from before the 5354 * system upgrade) and {@code scannedSigs} will be in the newer format. 5355 */ 5356 private int compareSignaturesCompat(PackageSignatures existingSigs, 5357 PackageParser.Package scannedPkg) { 5358 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5359 return PackageManager.SIGNATURE_NO_MATCH; 5360 } 5361 5362 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5363 for (Signature sig : existingSigs.mSignatures) { 5364 existingSet.add(sig); 5365 } 5366 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5367 for (Signature sig : scannedPkg.mSignatures) { 5368 try { 5369 Signature[] chainSignatures = sig.getChainSignatures(); 5370 for (Signature chainSig : chainSignatures) { 5371 scannedCompatSet.add(chainSig); 5372 } 5373 } catch (CertificateEncodingException e) { 5374 scannedCompatSet.add(sig); 5375 } 5376 } 5377 /* 5378 * Make sure the expanded scanned set contains all signatures in the 5379 * existing one. 5380 */ 5381 if (scannedCompatSet.equals(existingSet)) { 5382 // Migrate the old signatures to the new scheme. 5383 existingSigs.assignSignatures(scannedPkg.mSignatures); 5384 // The new KeySets will be re-added later in the scanning process. 5385 synchronized (mPackages) { 5386 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5387 } 5388 return PackageManager.SIGNATURE_MATCH; 5389 } 5390 return PackageManager.SIGNATURE_NO_MATCH; 5391 } 5392 5393 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5394 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5395 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5396 } 5397 5398 private int compareSignaturesRecover(PackageSignatures existingSigs, 5399 PackageParser.Package scannedPkg) { 5400 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5401 return PackageManager.SIGNATURE_NO_MATCH; 5402 } 5403 5404 String msg = null; 5405 try { 5406 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5407 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5408 + scannedPkg.packageName); 5409 return PackageManager.SIGNATURE_MATCH; 5410 } 5411 } catch (CertificateException e) { 5412 msg = e.getMessage(); 5413 } 5414 5415 logCriticalInfo(Log.INFO, 5416 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5417 return PackageManager.SIGNATURE_NO_MATCH; 5418 } 5419 5420 @Override 5421 public List<String> getAllPackages() { 5422 synchronized (mPackages) { 5423 return new ArrayList<String>(mPackages.keySet()); 5424 } 5425 } 5426 5427 @Override 5428 public String[] getPackagesForUid(int uid) { 5429 final int userId = UserHandle.getUserId(uid); 5430 uid = UserHandle.getAppId(uid); 5431 // reader 5432 synchronized (mPackages) { 5433 Object obj = mSettings.getUserIdLPr(uid); 5434 if (obj instanceof SharedUserSetting) { 5435 final SharedUserSetting sus = (SharedUserSetting) obj; 5436 final int N = sus.packages.size(); 5437 String[] res = new String[N]; 5438 final Iterator<PackageSetting> it = sus.packages.iterator(); 5439 int i = 0; 5440 while (it.hasNext()) { 5441 PackageSetting ps = it.next(); 5442 if (ps.getInstalled(userId)) { 5443 res[i++] = ps.name; 5444 } else { 5445 res = ArrayUtils.removeElement(String.class, res, res[i]); 5446 } 5447 } 5448 return res; 5449 } else if (obj instanceof PackageSetting) { 5450 final PackageSetting ps = (PackageSetting) obj; 5451 if (ps.getInstalled(userId)) { 5452 return new String[]{ps.name}; 5453 } 5454 } 5455 } 5456 return null; 5457 } 5458 5459 @Override 5460 public String getNameForUid(int uid) { 5461 // reader 5462 synchronized (mPackages) { 5463 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5464 if (obj instanceof SharedUserSetting) { 5465 final SharedUserSetting sus = (SharedUserSetting) obj; 5466 return sus.name + ":" + sus.userId; 5467 } else if (obj instanceof PackageSetting) { 5468 final PackageSetting ps = (PackageSetting) obj; 5469 return ps.name; 5470 } 5471 } 5472 return null; 5473 } 5474 5475 @Override 5476 public int getUidForSharedUser(String sharedUserName) { 5477 if(sharedUserName == null) { 5478 return -1; 5479 } 5480 // reader 5481 synchronized (mPackages) { 5482 SharedUserSetting suid; 5483 try { 5484 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5485 if (suid != null) { 5486 return suid.userId; 5487 } 5488 } catch (PackageManagerException ignore) { 5489 // can't happen, but, still need to catch it 5490 } 5491 return -1; 5492 } 5493 } 5494 5495 @Override 5496 public int getFlagsForUid(int uid) { 5497 synchronized (mPackages) { 5498 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5499 if (obj instanceof SharedUserSetting) { 5500 final SharedUserSetting sus = (SharedUserSetting) obj; 5501 return sus.pkgFlags; 5502 } else if (obj instanceof PackageSetting) { 5503 final PackageSetting ps = (PackageSetting) obj; 5504 return ps.pkgFlags; 5505 } 5506 } 5507 return 0; 5508 } 5509 5510 @Override 5511 public int getPrivateFlagsForUid(int uid) { 5512 synchronized (mPackages) { 5513 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5514 if (obj instanceof SharedUserSetting) { 5515 final SharedUserSetting sus = (SharedUserSetting) obj; 5516 return sus.pkgPrivateFlags; 5517 } else if (obj instanceof PackageSetting) { 5518 final PackageSetting ps = (PackageSetting) obj; 5519 return ps.pkgPrivateFlags; 5520 } 5521 } 5522 return 0; 5523 } 5524 5525 @Override 5526 public boolean isUidPrivileged(int uid) { 5527 uid = UserHandle.getAppId(uid); 5528 // reader 5529 synchronized (mPackages) { 5530 Object obj = mSettings.getUserIdLPr(uid); 5531 if (obj instanceof SharedUserSetting) { 5532 final SharedUserSetting sus = (SharedUserSetting) obj; 5533 final Iterator<PackageSetting> it = sus.packages.iterator(); 5534 while (it.hasNext()) { 5535 if (it.next().isPrivileged()) { 5536 return true; 5537 } 5538 } 5539 } else if (obj instanceof PackageSetting) { 5540 final PackageSetting ps = (PackageSetting) obj; 5541 return ps.isPrivileged(); 5542 } 5543 } 5544 return false; 5545 } 5546 5547 @Override 5548 public String[] getAppOpPermissionPackages(String permissionName) { 5549 synchronized (mPackages) { 5550 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5551 if (pkgs == null) { 5552 return null; 5553 } 5554 return pkgs.toArray(new String[pkgs.size()]); 5555 } 5556 } 5557 5558 @Override 5559 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5560 int flags, int userId) { 5561 try { 5562 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5563 5564 if (!sUserManager.exists(userId)) return null; 5565 flags = updateFlagsForResolve(flags, userId, intent); 5566 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5567 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5568 5569 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5570 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5571 flags, userId); 5572 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5573 5574 final ResolveInfo bestChoice = 5575 chooseBestActivity(intent, resolvedType, flags, query, userId); 5576 return bestChoice; 5577 } finally { 5578 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5579 } 5580 } 5581 5582 @Override 5583 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5584 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5585 throw new SecurityException( 5586 "findPersistentPreferredActivity can only be run by the system"); 5587 } 5588 if (!sUserManager.exists(userId)) { 5589 return null; 5590 } 5591 intent = updateIntentForResolve(intent); 5592 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5593 final int flags = updateFlagsForResolve(0, userId, intent); 5594 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5595 userId); 5596 synchronized (mPackages) { 5597 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5598 userId); 5599 } 5600 } 5601 5602 @Override 5603 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5604 IntentFilter filter, int match, ComponentName activity) { 5605 final int userId = UserHandle.getCallingUserId(); 5606 if (DEBUG_PREFERRED) { 5607 Log.v(TAG, "setLastChosenActivity intent=" + intent 5608 + " resolvedType=" + resolvedType 5609 + " flags=" + flags 5610 + " filter=" + filter 5611 + " match=" + match 5612 + " activity=" + activity); 5613 filter.dump(new PrintStreamPrinter(System.out), " "); 5614 } 5615 intent.setComponent(null); 5616 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5617 userId); 5618 // Find any earlier preferred or last chosen entries and nuke them 5619 findPreferredActivity(intent, resolvedType, 5620 flags, query, 0, false, true, false, userId); 5621 // Add the new activity as the last chosen for this filter 5622 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5623 "Setting last chosen"); 5624 } 5625 5626 @Override 5627 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5628 final int userId = UserHandle.getCallingUserId(); 5629 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5630 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5631 userId); 5632 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5633 false, false, false, userId); 5634 } 5635 5636 private boolean isEphemeralDisabled() { 5637 // ephemeral apps have been disabled across the board 5638 if (DISABLE_EPHEMERAL_APPS) { 5639 return true; 5640 } 5641 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5642 if (!mSystemReady) { 5643 return true; 5644 } 5645 // we can't get a content resolver until the system is ready; these checks must happen last 5646 final ContentResolver resolver = mContext.getContentResolver(); 5647 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5648 return true; 5649 } 5650 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5651 } 5652 5653 private boolean isEphemeralAllowed( 5654 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5655 boolean skipPackageCheck) { 5656 // Short circuit and return early if possible. 5657 if (isEphemeralDisabled()) { 5658 return false; 5659 } 5660 final int callingUser = UserHandle.getCallingUserId(); 5661 if (callingUser != UserHandle.USER_SYSTEM) { 5662 return false; 5663 } 5664 if (mInstantAppResolverConnection == null) { 5665 return false; 5666 } 5667 if (mInstantAppInstallerComponent == null) { 5668 return false; 5669 } 5670 if (intent.getComponent() != null) { 5671 return false; 5672 } 5673 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5674 return false; 5675 } 5676 if (!skipPackageCheck && intent.getPackage() != null) { 5677 return false; 5678 } 5679 final boolean isWebUri = hasWebURI(intent); 5680 if (!isWebUri || intent.getData().getHost() == null) { 5681 return false; 5682 } 5683 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5684 // Or if there's already an ephemeral app installed that handles the action 5685 synchronized (mPackages) { 5686 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5687 for (int n = 0; n < count; n++) { 5688 ResolveInfo info = resolvedActivities.get(n); 5689 String packageName = info.activityInfo.packageName; 5690 PackageSetting ps = mSettings.mPackages.get(packageName); 5691 if (ps != null) { 5692 // Try to get the status from User settings first 5693 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5694 int status = (int) (packedStatus >> 32); 5695 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5696 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5697 if (DEBUG_EPHEMERAL) { 5698 Slog.v(TAG, "DENY ephemeral apps;" 5699 + " pkg: " + packageName + ", status: " + status); 5700 } 5701 return false; 5702 } 5703 if (ps.getInstantApp(userId)) { 5704 return false; 5705 } 5706 } 5707 } 5708 } 5709 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5710 return true; 5711 } 5712 5713 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5714 Intent origIntent, String resolvedType, String callingPackage, 5715 int userId) { 5716 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5717 new EphemeralRequest(responseObj, origIntent, resolvedType, 5718 callingPackage, userId)); 5719 mHandler.sendMessage(msg); 5720 } 5721 5722 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5723 int flags, List<ResolveInfo> query, int userId) { 5724 if (query != null) { 5725 final int N = query.size(); 5726 if (N == 1) { 5727 return query.get(0); 5728 } else if (N > 1) { 5729 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5730 // If there is more than one activity with the same priority, 5731 // then let the user decide between them. 5732 ResolveInfo r0 = query.get(0); 5733 ResolveInfo r1 = query.get(1); 5734 if (DEBUG_INTENT_MATCHING || debug) { 5735 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5736 + r1.activityInfo.name + "=" + r1.priority); 5737 } 5738 // If the first activity has a higher priority, or a different 5739 // default, then it is always desirable to pick it. 5740 if (r0.priority != r1.priority 5741 || r0.preferredOrder != r1.preferredOrder 5742 || r0.isDefault != r1.isDefault) { 5743 return query.get(0); 5744 } 5745 // If we have saved a preference for a preferred activity for 5746 // this Intent, use that. 5747 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5748 flags, query, r0.priority, true, false, debug, userId); 5749 if (ri != null) { 5750 return ri; 5751 } 5752 ri = new ResolveInfo(mResolveInfo); 5753 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5754 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5755 // If all of the options come from the same package, show the application's 5756 // label and icon instead of the generic resolver's. 5757 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5758 // and then throw away the ResolveInfo itself, meaning that the caller loses 5759 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5760 // a fallback for this case; we only set the target package's resources on 5761 // the ResolveInfo, not the ActivityInfo. 5762 final String intentPackage = intent.getPackage(); 5763 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5764 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5765 ri.resolvePackageName = intentPackage; 5766 if (userNeedsBadging(userId)) { 5767 ri.noResourceId = true; 5768 } else { 5769 ri.icon = appi.icon; 5770 } 5771 ri.iconResourceId = appi.icon; 5772 ri.labelRes = appi.labelRes; 5773 } 5774 ri.activityInfo.applicationInfo = new ApplicationInfo( 5775 ri.activityInfo.applicationInfo); 5776 if (userId != 0) { 5777 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5778 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5779 } 5780 // Make sure that the resolver is displayable in car mode 5781 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5782 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5783 return ri; 5784 } 5785 } 5786 return null; 5787 } 5788 5789 /** 5790 * Return true if the given list is not empty and all of its contents have 5791 * an activityInfo with the given package name. 5792 */ 5793 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5794 if (ArrayUtils.isEmpty(list)) { 5795 return false; 5796 } 5797 for (int i = 0, N = list.size(); i < N; i++) { 5798 final ResolveInfo ri = list.get(i); 5799 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5800 if (ai == null || !packageName.equals(ai.packageName)) { 5801 return false; 5802 } 5803 } 5804 return true; 5805 } 5806 5807 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5808 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5809 final int N = query.size(); 5810 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5811 .get(userId); 5812 // Get the list of persistent preferred activities that handle the intent 5813 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5814 List<PersistentPreferredActivity> pprefs = ppir != null 5815 ? ppir.queryIntent(intent, resolvedType, 5816 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5817 userId) 5818 : null; 5819 if (pprefs != null && pprefs.size() > 0) { 5820 final int M = pprefs.size(); 5821 for (int i=0; i<M; i++) { 5822 final PersistentPreferredActivity ppa = pprefs.get(i); 5823 if (DEBUG_PREFERRED || debug) { 5824 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5825 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5826 + "\n component=" + ppa.mComponent); 5827 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5828 } 5829 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5830 flags | MATCH_DISABLED_COMPONENTS, userId); 5831 if (DEBUG_PREFERRED || debug) { 5832 Slog.v(TAG, "Found persistent preferred activity:"); 5833 if (ai != null) { 5834 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5835 } else { 5836 Slog.v(TAG, " null"); 5837 } 5838 } 5839 if (ai == null) { 5840 // This previously registered persistent preferred activity 5841 // component is no longer known. Ignore it and do NOT remove it. 5842 continue; 5843 } 5844 for (int j=0; j<N; j++) { 5845 final ResolveInfo ri = query.get(j); 5846 if (!ri.activityInfo.applicationInfo.packageName 5847 .equals(ai.applicationInfo.packageName)) { 5848 continue; 5849 } 5850 if (!ri.activityInfo.name.equals(ai.name)) { 5851 continue; 5852 } 5853 // Found a persistent preference that can handle the intent. 5854 if (DEBUG_PREFERRED || debug) { 5855 Slog.v(TAG, "Returning persistent preferred activity: " + 5856 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5857 } 5858 return ri; 5859 } 5860 } 5861 } 5862 return null; 5863 } 5864 5865 // TODO: handle preferred activities missing while user has amnesia 5866 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5867 List<ResolveInfo> query, int priority, boolean always, 5868 boolean removeMatches, boolean debug, int userId) { 5869 if (!sUserManager.exists(userId)) return null; 5870 flags = updateFlagsForResolve(flags, userId, intent); 5871 intent = updateIntentForResolve(intent); 5872 // writer 5873 synchronized (mPackages) { 5874 // Try to find a matching persistent preferred activity. 5875 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5876 debug, userId); 5877 5878 // If a persistent preferred activity matched, use it. 5879 if (pri != null) { 5880 return pri; 5881 } 5882 5883 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5884 // Get the list of preferred activities that handle the intent 5885 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5886 List<PreferredActivity> prefs = pir != null 5887 ? pir.queryIntent(intent, resolvedType, 5888 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5889 userId) 5890 : null; 5891 if (prefs != null && prefs.size() > 0) { 5892 boolean changed = false; 5893 try { 5894 // First figure out how good the original match set is. 5895 // We will only allow preferred activities that came 5896 // from the same match quality. 5897 int match = 0; 5898 5899 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5900 5901 final int N = query.size(); 5902 for (int j=0; j<N; j++) { 5903 final ResolveInfo ri = query.get(j); 5904 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5905 + ": 0x" + Integer.toHexString(match)); 5906 if (ri.match > match) { 5907 match = ri.match; 5908 } 5909 } 5910 5911 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5912 + Integer.toHexString(match)); 5913 5914 match &= IntentFilter.MATCH_CATEGORY_MASK; 5915 final int M = prefs.size(); 5916 for (int i=0; i<M; i++) { 5917 final PreferredActivity pa = prefs.get(i); 5918 if (DEBUG_PREFERRED || debug) { 5919 Slog.v(TAG, "Checking PreferredActivity ds=" 5920 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5921 + "\n component=" + pa.mPref.mComponent); 5922 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5923 } 5924 if (pa.mPref.mMatch != match) { 5925 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5926 + Integer.toHexString(pa.mPref.mMatch)); 5927 continue; 5928 } 5929 // If it's not an "always" type preferred activity and that's what we're 5930 // looking for, skip it. 5931 if (always && !pa.mPref.mAlways) { 5932 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5933 continue; 5934 } 5935 final ActivityInfo ai = getActivityInfo( 5936 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5937 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5938 userId); 5939 if (DEBUG_PREFERRED || debug) { 5940 Slog.v(TAG, "Found preferred activity:"); 5941 if (ai != null) { 5942 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5943 } else { 5944 Slog.v(TAG, " null"); 5945 } 5946 } 5947 if (ai == null) { 5948 // This previously registered preferred activity 5949 // component is no longer known. Most likely an update 5950 // to the app was installed and in the new version this 5951 // component no longer exists. Clean it up by removing 5952 // it from the preferred activities list, and skip it. 5953 Slog.w(TAG, "Removing dangling preferred activity: " 5954 + pa.mPref.mComponent); 5955 pir.removeFilter(pa); 5956 changed = true; 5957 continue; 5958 } 5959 for (int j=0; j<N; j++) { 5960 final ResolveInfo ri = query.get(j); 5961 if (!ri.activityInfo.applicationInfo.packageName 5962 .equals(ai.applicationInfo.packageName)) { 5963 continue; 5964 } 5965 if (!ri.activityInfo.name.equals(ai.name)) { 5966 continue; 5967 } 5968 5969 if (removeMatches) { 5970 pir.removeFilter(pa); 5971 changed = true; 5972 if (DEBUG_PREFERRED) { 5973 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5974 } 5975 break; 5976 } 5977 5978 // Okay we found a previously set preferred or last chosen app. 5979 // If the result set is different from when this 5980 // was created, we need to clear it and re-ask the 5981 // user their preference, if we're looking for an "always" type entry. 5982 if (always && !pa.mPref.sameSet(query)) { 5983 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5984 + intent + " type " + resolvedType); 5985 if (DEBUG_PREFERRED) { 5986 Slog.v(TAG, "Removing preferred activity since set changed " 5987 + pa.mPref.mComponent); 5988 } 5989 pir.removeFilter(pa); 5990 // Re-add the filter as a "last chosen" entry (!always) 5991 PreferredActivity lastChosen = new PreferredActivity( 5992 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5993 pir.addFilter(lastChosen); 5994 changed = true; 5995 return null; 5996 } 5997 5998 // Yay! Either the set matched or we're looking for the last chosen 5999 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6000 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6001 return ri; 6002 } 6003 } 6004 } finally { 6005 if (changed) { 6006 if (DEBUG_PREFERRED) { 6007 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6008 } 6009 scheduleWritePackageRestrictionsLocked(userId); 6010 } 6011 } 6012 } 6013 } 6014 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6015 return null; 6016 } 6017 6018 /* 6019 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6020 */ 6021 @Override 6022 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6023 int targetUserId) { 6024 mContext.enforceCallingOrSelfPermission( 6025 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6026 List<CrossProfileIntentFilter> matches = 6027 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6028 if (matches != null) { 6029 int size = matches.size(); 6030 for (int i = 0; i < size; i++) { 6031 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6032 } 6033 } 6034 if (hasWebURI(intent)) { 6035 // cross-profile app linking works only towards the parent. 6036 final UserInfo parent = getProfileParent(sourceUserId); 6037 synchronized(mPackages) { 6038 int flags = updateFlagsForResolve(0, parent.id, intent); 6039 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6040 intent, resolvedType, flags, sourceUserId, parent.id); 6041 return xpDomainInfo != null; 6042 } 6043 } 6044 return false; 6045 } 6046 6047 private UserInfo getProfileParent(int userId) { 6048 final long identity = Binder.clearCallingIdentity(); 6049 try { 6050 return sUserManager.getProfileParent(userId); 6051 } finally { 6052 Binder.restoreCallingIdentity(identity); 6053 } 6054 } 6055 6056 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6057 String resolvedType, int userId) { 6058 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6059 if (resolver != null) { 6060 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6061 } 6062 return null; 6063 } 6064 6065 @Override 6066 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6067 String resolvedType, int flags, int userId) { 6068 try { 6069 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6070 6071 return new ParceledListSlice<>( 6072 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6073 } finally { 6074 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6075 } 6076 } 6077 6078 /** 6079 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6080 * instant, returns {@code null}. 6081 */ 6082 private String getInstantAppPackageName(int callingUid) { 6083 final int appId = UserHandle.getAppId(callingUid); 6084 synchronized (mPackages) { 6085 final Object obj = mSettings.getUserIdLPr(appId); 6086 if (obj instanceof PackageSetting) { 6087 final PackageSetting ps = (PackageSetting) obj; 6088 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6089 return isInstantApp ? ps.pkg.packageName : null; 6090 } 6091 } 6092 return null; 6093 } 6094 6095 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6096 String resolvedType, int flags, int userId) { 6097 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6098 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6099 flags = updateFlagsForResolve(flags, userId, intent); 6100 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6101 false /* requireFullPermission */, false /* checkShell */, 6102 "query intent activities"); 6103 ComponentName comp = intent.getComponent(); 6104 if (comp == null) { 6105 if (intent.getSelector() != null) { 6106 intent = intent.getSelector(); 6107 comp = intent.getComponent(); 6108 } 6109 } 6110 6111 if (comp != null) { 6112 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6113 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6114 if (ai != null) { 6115 // When specifying an explicit component, we prevent the activity from being 6116 // used when either 1) the calling package is normal and the activity is within 6117 // an ephemeral application or 2) the calling package is ephemeral and the 6118 // activity is not visible to ephemeral applications. 6119 final boolean matchInstantApp = 6120 (flags & PackageManager.MATCH_INSTANT) != 0; 6121 final boolean matchVisibleToInstantAppOnly = 6122 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6123 final boolean isCallerInstantApp = 6124 instantAppPkgName != null; 6125 final boolean isTargetSameInstantApp = 6126 comp.getPackageName().equals(instantAppPkgName); 6127 final boolean isTargetInstantApp = 6128 (ai.applicationInfo.privateFlags 6129 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6130 final boolean isTargetHiddenFromInstantApp = 6131 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6132 final boolean blockResolution = 6133 !isTargetSameInstantApp 6134 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6135 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6136 && isTargetHiddenFromInstantApp)); 6137 if (!blockResolution) { 6138 final ResolveInfo ri = new ResolveInfo(); 6139 ri.activityInfo = ai; 6140 list.add(ri); 6141 } 6142 } 6143 return applyPostResolutionFilter(list, instantAppPkgName); 6144 } 6145 6146 // reader 6147 boolean sortResult = false; 6148 boolean addEphemeral = false; 6149 List<ResolveInfo> result; 6150 final String pkgName = intent.getPackage(); 6151 synchronized (mPackages) { 6152 if (pkgName == null) { 6153 List<CrossProfileIntentFilter> matchingFilters = 6154 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6155 // Check for results that need to skip the current profile. 6156 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6157 resolvedType, flags, userId); 6158 if (xpResolveInfo != null) { 6159 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6160 xpResult.add(xpResolveInfo); 6161 return applyPostResolutionFilter( 6162 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6163 } 6164 6165 // Check for results in the current profile. 6166 result = filterIfNotSystemUser(mActivities.queryIntent( 6167 intent, resolvedType, flags, userId), userId); 6168 addEphemeral = 6169 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6170 6171 // Check for cross profile results. 6172 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6173 xpResolveInfo = queryCrossProfileIntents( 6174 matchingFilters, intent, resolvedType, flags, userId, 6175 hasNonNegativePriorityResult); 6176 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6177 boolean isVisibleToUser = filterIfNotSystemUser( 6178 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6179 if (isVisibleToUser) { 6180 result.add(xpResolveInfo); 6181 sortResult = true; 6182 } 6183 } 6184 if (hasWebURI(intent)) { 6185 CrossProfileDomainInfo xpDomainInfo = null; 6186 final UserInfo parent = getProfileParent(userId); 6187 if (parent != null) { 6188 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6189 flags, userId, parent.id); 6190 } 6191 if (xpDomainInfo != null) { 6192 if (xpResolveInfo != null) { 6193 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6194 // in the result. 6195 result.remove(xpResolveInfo); 6196 } 6197 if (result.size() == 0 && !addEphemeral) { 6198 // No result in current profile, but found candidate in parent user. 6199 // And we are not going to add emphemeral app, so we can return the 6200 // result straight away. 6201 result.add(xpDomainInfo.resolveInfo); 6202 return applyPostResolutionFilter(result, instantAppPkgName); 6203 } 6204 } else if (result.size() <= 1 && !addEphemeral) { 6205 // No result in parent user and <= 1 result in current profile, and we 6206 // are not going to add emphemeral app, so we can return the result without 6207 // further processing. 6208 return applyPostResolutionFilter(result, instantAppPkgName); 6209 } 6210 // We have more than one candidate (combining results from current and parent 6211 // profile), so we need filtering and sorting. 6212 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6213 intent, flags, result, xpDomainInfo, userId); 6214 sortResult = true; 6215 } 6216 } else { 6217 final PackageParser.Package pkg = mPackages.get(pkgName); 6218 if (pkg != null) { 6219 result = applyPostResolutionFilter(filterIfNotSystemUser( 6220 mActivities.queryIntentForPackage( 6221 intent, resolvedType, flags, pkg.activities, userId), 6222 userId), instantAppPkgName); 6223 } else { 6224 // the caller wants to resolve for a particular package; however, there 6225 // were no installed results, so, try to find an ephemeral result 6226 addEphemeral = isEphemeralAllowed( 6227 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6228 result = new ArrayList<ResolveInfo>(); 6229 } 6230 } 6231 } 6232 if (addEphemeral) { 6233 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6234 final EphemeralRequest requestObject = new EphemeralRequest( 6235 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6236 null /*callingPackage*/, userId); 6237 final AuxiliaryResolveInfo auxiliaryResponse = 6238 EphemeralResolver.doEphemeralResolutionPhaseOne( 6239 mContext, mInstantAppResolverConnection, requestObject); 6240 if (auxiliaryResponse != null) { 6241 if (DEBUG_EPHEMERAL) { 6242 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6243 } 6244 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6245 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6246 // make sure this resolver is the default 6247 ephemeralInstaller.isDefault = true; 6248 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6249 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6250 // add a non-generic filter 6251 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6252 ephemeralInstaller.filter.addDataPath( 6253 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6254 result.add(ephemeralInstaller); 6255 } 6256 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6257 } 6258 if (sortResult) { 6259 Collections.sort(result, mResolvePrioritySorter); 6260 } 6261 return applyPostResolutionFilter(result, instantAppPkgName); 6262 } 6263 6264 private static class CrossProfileDomainInfo { 6265 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6266 ResolveInfo resolveInfo; 6267 /* Best domain verification status of the activities found in the other profile */ 6268 int bestDomainVerificationStatus; 6269 } 6270 6271 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6272 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6273 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6274 sourceUserId)) { 6275 return null; 6276 } 6277 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6278 resolvedType, flags, parentUserId); 6279 6280 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6281 return null; 6282 } 6283 CrossProfileDomainInfo result = null; 6284 int size = resultTargetUser.size(); 6285 for (int i = 0; i < size; i++) { 6286 ResolveInfo riTargetUser = resultTargetUser.get(i); 6287 // Intent filter verification is only for filters that specify a host. So don't return 6288 // those that handle all web uris. 6289 if (riTargetUser.handleAllWebDataURI) { 6290 continue; 6291 } 6292 String packageName = riTargetUser.activityInfo.packageName; 6293 PackageSetting ps = mSettings.mPackages.get(packageName); 6294 if (ps == null) { 6295 continue; 6296 } 6297 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6298 int status = (int)(verificationState >> 32); 6299 if (result == null) { 6300 result = new CrossProfileDomainInfo(); 6301 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6302 sourceUserId, parentUserId); 6303 result.bestDomainVerificationStatus = status; 6304 } else { 6305 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6306 result.bestDomainVerificationStatus); 6307 } 6308 } 6309 // Don't consider matches with status NEVER across profiles. 6310 if (result != null && result.bestDomainVerificationStatus 6311 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6312 return null; 6313 } 6314 return result; 6315 } 6316 6317 /** 6318 * Verification statuses are ordered from the worse to the best, except for 6319 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6320 */ 6321 private int bestDomainVerificationStatus(int status1, int status2) { 6322 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6323 return status2; 6324 } 6325 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6326 return status1; 6327 } 6328 return (int) MathUtils.max(status1, status2); 6329 } 6330 6331 private boolean isUserEnabled(int userId) { 6332 long callingId = Binder.clearCallingIdentity(); 6333 try { 6334 UserInfo userInfo = sUserManager.getUserInfo(userId); 6335 return userInfo != null && userInfo.isEnabled(); 6336 } finally { 6337 Binder.restoreCallingIdentity(callingId); 6338 } 6339 } 6340 6341 /** 6342 * Filter out activities with systemUserOnly flag set, when current user is not System. 6343 * 6344 * @return filtered list 6345 */ 6346 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6347 if (userId == UserHandle.USER_SYSTEM) { 6348 return resolveInfos; 6349 } 6350 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6351 ResolveInfo info = resolveInfos.get(i); 6352 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6353 resolveInfos.remove(i); 6354 } 6355 } 6356 return resolveInfos; 6357 } 6358 6359 /** 6360 * Filters out ephemeral activities. 6361 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6362 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6363 * 6364 * @param resolveInfos The pre-filtered list of resolved activities 6365 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6366 * is performed. 6367 * @return A filtered list of resolved activities. 6368 */ 6369 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6370 String ephemeralPkgName) { 6371 // TODO: When adding on-demand split support for non-instant apps, remove this check 6372 // and always apply post filtering 6373 if (ephemeralPkgName == null) { 6374 return resolveInfos; 6375 } 6376 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6377 final ResolveInfo info = resolveInfos.get(i); 6378 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6379 // allow activities that are defined in the provided package 6380 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6381 if (info.activityInfo.splitName != null 6382 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6383 info.activityInfo.splitName)) { 6384 // requested activity is defined in a split that hasn't been installed yet. 6385 // add the installer to the resolve list 6386 if (DEBUG_EPHEMERAL) { 6387 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6388 } 6389 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6390 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6391 info.activityInfo.packageName, info.activityInfo.splitName, 6392 info.activityInfo.applicationInfo.versionCode); 6393 // make sure this resolver is the default 6394 installerInfo.isDefault = true; 6395 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6396 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6397 // add a non-generic filter 6398 installerInfo.filter = new IntentFilter(); 6399 // load resources from the correct package 6400 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6401 resolveInfos.set(i, installerInfo); 6402 } 6403 continue; 6404 } 6405 // allow activities that have been explicitly exposed to ephemeral apps 6406 if (!isEphemeralApp 6407 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6408 continue; 6409 } 6410 resolveInfos.remove(i); 6411 } 6412 return resolveInfos; 6413 } 6414 6415 /** 6416 * @param resolveInfos list of resolve infos in descending priority order 6417 * @return if the list contains a resolve info with non-negative priority 6418 */ 6419 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6420 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6421 } 6422 6423 private static boolean hasWebURI(Intent intent) { 6424 if (intent.getData() == null) { 6425 return false; 6426 } 6427 final String scheme = intent.getScheme(); 6428 if (TextUtils.isEmpty(scheme)) { 6429 return false; 6430 } 6431 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6432 } 6433 6434 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6435 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6436 int userId) { 6437 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6438 6439 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6440 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6441 candidates.size()); 6442 } 6443 6444 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6445 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6446 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6447 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6448 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6449 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6450 6451 synchronized (mPackages) { 6452 final int count = candidates.size(); 6453 // First, try to use linked apps. Partition the candidates into four lists: 6454 // one for the final results, one for the "do not use ever", one for "undefined status" 6455 // and finally one for "browser app type". 6456 for (int n=0; n<count; n++) { 6457 ResolveInfo info = candidates.get(n); 6458 String packageName = info.activityInfo.packageName; 6459 PackageSetting ps = mSettings.mPackages.get(packageName); 6460 if (ps != null) { 6461 // Add to the special match all list (Browser use case) 6462 if (info.handleAllWebDataURI) { 6463 matchAllList.add(info); 6464 continue; 6465 } 6466 // Try to get the status from User settings first 6467 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6468 int status = (int)(packedStatus >> 32); 6469 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6470 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6471 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6472 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6473 + " : linkgen=" + linkGeneration); 6474 } 6475 // Use link-enabled generation as preferredOrder, i.e. 6476 // prefer newly-enabled over earlier-enabled. 6477 info.preferredOrder = linkGeneration; 6478 alwaysList.add(info); 6479 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6480 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6481 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6482 } 6483 neverList.add(info); 6484 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6485 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6486 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6487 } 6488 alwaysAskList.add(info); 6489 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6490 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6491 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6492 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6493 } 6494 undefinedList.add(info); 6495 } 6496 } 6497 } 6498 6499 // We'll want to include browser possibilities in a few cases 6500 boolean includeBrowser = false; 6501 6502 // First try to add the "always" resolution(s) for the current user, if any 6503 if (alwaysList.size() > 0) { 6504 result.addAll(alwaysList); 6505 } else { 6506 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6507 result.addAll(undefinedList); 6508 // Maybe add one for the other profile. 6509 if (xpDomainInfo != null && ( 6510 xpDomainInfo.bestDomainVerificationStatus 6511 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6512 result.add(xpDomainInfo.resolveInfo); 6513 } 6514 includeBrowser = true; 6515 } 6516 6517 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6518 // If there were 'always' entries their preferred order has been set, so we also 6519 // back that off to make the alternatives equivalent 6520 if (alwaysAskList.size() > 0) { 6521 for (ResolveInfo i : result) { 6522 i.preferredOrder = 0; 6523 } 6524 result.addAll(alwaysAskList); 6525 includeBrowser = true; 6526 } 6527 6528 if (includeBrowser) { 6529 // Also add browsers (all of them or only the default one) 6530 if (DEBUG_DOMAIN_VERIFICATION) { 6531 Slog.v(TAG, " ...including browsers in candidate set"); 6532 } 6533 if ((matchFlags & MATCH_ALL) != 0) { 6534 result.addAll(matchAllList); 6535 } else { 6536 // Browser/generic handling case. If there's a default browser, go straight 6537 // to that (but only if there is no other higher-priority match). 6538 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6539 int maxMatchPrio = 0; 6540 ResolveInfo defaultBrowserMatch = null; 6541 final int numCandidates = matchAllList.size(); 6542 for (int n = 0; n < numCandidates; n++) { 6543 ResolveInfo info = matchAllList.get(n); 6544 // track the highest overall match priority... 6545 if (info.priority > maxMatchPrio) { 6546 maxMatchPrio = info.priority; 6547 } 6548 // ...and the highest-priority default browser match 6549 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6550 if (defaultBrowserMatch == null 6551 || (defaultBrowserMatch.priority < info.priority)) { 6552 if (debug) { 6553 Slog.v(TAG, "Considering default browser match " + info); 6554 } 6555 defaultBrowserMatch = info; 6556 } 6557 } 6558 } 6559 if (defaultBrowserMatch != null 6560 && defaultBrowserMatch.priority >= maxMatchPrio 6561 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6562 { 6563 if (debug) { 6564 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6565 } 6566 result.add(defaultBrowserMatch); 6567 } else { 6568 result.addAll(matchAllList); 6569 } 6570 } 6571 6572 // If there is nothing selected, add all candidates and remove the ones that the user 6573 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6574 if (result.size() == 0) { 6575 result.addAll(candidates); 6576 result.removeAll(neverList); 6577 } 6578 } 6579 } 6580 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6581 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6582 result.size()); 6583 for (ResolveInfo info : result) { 6584 Slog.v(TAG, " + " + info.activityInfo); 6585 } 6586 } 6587 return result; 6588 } 6589 6590 // Returns a packed value as a long: 6591 // 6592 // high 'int'-sized word: link status: undefined/ask/never/always. 6593 // low 'int'-sized word: relative priority among 'always' results. 6594 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6595 long result = ps.getDomainVerificationStatusForUser(userId); 6596 // if none available, get the master status 6597 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6598 if (ps.getIntentFilterVerificationInfo() != null) { 6599 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6600 } 6601 } 6602 return result; 6603 } 6604 6605 private ResolveInfo querySkipCurrentProfileIntents( 6606 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6607 int flags, int sourceUserId) { 6608 if (matchingFilters != null) { 6609 int size = matchingFilters.size(); 6610 for (int i = 0; i < size; i ++) { 6611 CrossProfileIntentFilter filter = matchingFilters.get(i); 6612 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6613 // Checking if there are activities in the target user that can handle the 6614 // intent. 6615 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6616 resolvedType, flags, sourceUserId); 6617 if (resolveInfo != null) { 6618 return resolveInfo; 6619 } 6620 } 6621 } 6622 } 6623 return null; 6624 } 6625 6626 // Return matching ResolveInfo in target user if any. 6627 private ResolveInfo queryCrossProfileIntents( 6628 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6629 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6630 if (matchingFilters != null) { 6631 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6632 // match the same intent. For performance reasons, it is better not to 6633 // run queryIntent twice for the same userId 6634 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6635 int size = matchingFilters.size(); 6636 for (int i = 0; i < size; i++) { 6637 CrossProfileIntentFilter filter = matchingFilters.get(i); 6638 int targetUserId = filter.getTargetUserId(); 6639 boolean skipCurrentProfile = 6640 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6641 boolean skipCurrentProfileIfNoMatchFound = 6642 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6643 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6644 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6645 // Checking if there are activities in the target user that can handle the 6646 // intent. 6647 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6648 resolvedType, flags, sourceUserId); 6649 if (resolveInfo != null) return resolveInfo; 6650 alreadyTriedUserIds.put(targetUserId, true); 6651 } 6652 } 6653 } 6654 return null; 6655 } 6656 6657 /** 6658 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6659 * will forward the intent to the filter's target user. 6660 * Otherwise, returns null. 6661 */ 6662 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6663 String resolvedType, int flags, int sourceUserId) { 6664 int targetUserId = filter.getTargetUserId(); 6665 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6666 resolvedType, flags, targetUserId); 6667 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6668 // If all the matches in the target profile are suspended, return null. 6669 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6670 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6671 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6672 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6673 targetUserId); 6674 } 6675 } 6676 } 6677 return null; 6678 } 6679 6680 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6681 int sourceUserId, int targetUserId) { 6682 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6683 long ident = Binder.clearCallingIdentity(); 6684 boolean targetIsProfile; 6685 try { 6686 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6687 } finally { 6688 Binder.restoreCallingIdentity(ident); 6689 } 6690 String className; 6691 if (targetIsProfile) { 6692 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6693 } else { 6694 className = FORWARD_INTENT_TO_PARENT; 6695 } 6696 ComponentName forwardingActivityComponentName = new ComponentName( 6697 mAndroidApplication.packageName, className); 6698 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6699 sourceUserId); 6700 if (!targetIsProfile) { 6701 forwardingActivityInfo.showUserIcon = targetUserId; 6702 forwardingResolveInfo.noResourceId = true; 6703 } 6704 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6705 forwardingResolveInfo.priority = 0; 6706 forwardingResolveInfo.preferredOrder = 0; 6707 forwardingResolveInfo.match = 0; 6708 forwardingResolveInfo.isDefault = true; 6709 forwardingResolveInfo.filter = filter; 6710 forwardingResolveInfo.targetUserId = targetUserId; 6711 return forwardingResolveInfo; 6712 } 6713 6714 @Override 6715 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6716 Intent[] specifics, String[] specificTypes, Intent intent, 6717 String resolvedType, int flags, int userId) { 6718 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6719 specificTypes, intent, resolvedType, flags, userId)); 6720 } 6721 6722 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6723 Intent[] specifics, String[] specificTypes, Intent intent, 6724 String resolvedType, int flags, int userId) { 6725 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6726 flags = updateFlagsForResolve(flags, userId, intent); 6727 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6728 false /* requireFullPermission */, false /* checkShell */, 6729 "query intent activity options"); 6730 final String resultsAction = intent.getAction(); 6731 6732 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6733 | PackageManager.GET_RESOLVED_FILTER, userId); 6734 6735 if (DEBUG_INTENT_MATCHING) { 6736 Log.v(TAG, "Query " + intent + ": " + results); 6737 } 6738 6739 int specificsPos = 0; 6740 int N; 6741 6742 // todo: note that the algorithm used here is O(N^2). This 6743 // isn't a problem in our current environment, but if we start running 6744 // into situations where we have more than 5 or 10 matches then this 6745 // should probably be changed to something smarter... 6746 6747 // First we go through and resolve each of the specific items 6748 // that were supplied, taking care of removing any corresponding 6749 // duplicate items in the generic resolve list. 6750 if (specifics != null) { 6751 for (int i=0; i<specifics.length; i++) { 6752 final Intent sintent = specifics[i]; 6753 if (sintent == null) { 6754 continue; 6755 } 6756 6757 if (DEBUG_INTENT_MATCHING) { 6758 Log.v(TAG, "Specific #" + i + ": " + sintent); 6759 } 6760 6761 String action = sintent.getAction(); 6762 if (resultsAction != null && resultsAction.equals(action)) { 6763 // If this action was explicitly requested, then don't 6764 // remove things that have it. 6765 action = null; 6766 } 6767 6768 ResolveInfo ri = null; 6769 ActivityInfo ai = null; 6770 6771 ComponentName comp = sintent.getComponent(); 6772 if (comp == null) { 6773 ri = resolveIntent( 6774 sintent, 6775 specificTypes != null ? specificTypes[i] : null, 6776 flags, userId); 6777 if (ri == null) { 6778 continue; 6779 } 6780 if (ri == mResolveInfo) { 6781 // ACK! Must do something better with this. 6782 } 6783 ai = ri.activityInfo; 6784 comp = new ComponentName(ai.applicationInfo.packageName, 6785 ai.name); 6786 } else { 6787 ai = getActivityInfo(comp, flags, userId); 6788 if (ai == null) { 6789 continue; 6790 } 6791 } 6792 6793 // Look for any generic query activities that are duplicates 6794 // of this specific one, and remove them from the results. 6795 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6796 N = results.size(); 6797 int j; 6798 for (j=specificsPos; j<N; j++) { 6799 ResolveInfo sri = results.get(j); 6800 if ((sri.activityInfo.name.equals(comp.getClassName()) 6801 && sri.activityInfo.applicationInfo.packageName.equals( 6802 comp.getPackageName())) 6803 || (action != null && sri.filter.matchAction(action))) { 6804 results.remove(j); 6805 if (DEBUG_INTENT_MATCHING) Log.v( 6806 TAG, "Removing duplicate item from " + j 6807 + " due to specific " + specificsPos); 6808 if (ri == null) { 6809 ri = sri; 6810 } 6811 j--; 6812 N--; 6813 } 6814 } 6815 6816 // Add this specific item to its proper place. 6817 if (ri == null) { 6818 ri = new ResolveInfo(); 6819 ri.activityInfo = ai; 6820 } 6821 results.add(specificsPos, ri); 6822 ri.specificIndex = i; 6823 specificsPos++; 6824 } 6825 } 6826 6827 // Now we go through the remaining generic results and remove any 6828 // duplicate actions that are found here. 6829 N = results.size(); 6830 for (int i=specificsPos; i<N-1; i++) { 6831 final ResolveInfo rii = results.get(i); 6832 if (rii.filter == null) { 6833 continue; 6834 } 6835 6836 // Iterate over all of the actions of this result's intent 6837 // filter... typically this should be just one. 6838 final Iterator<String> it = rii.filter.actionsIterator(); 6839 if (it == null) { 6840 continue; 6841 } 6842 while (it.hasNext()) { 6843 final String action = it.next(); 6844 if (resultsAction != null && resultsAction.equals(action)) { 6845 // If this action was explicitly requested, then don't 6846 // remove things that have it. 6847 continue; 6848 } 6849 for (int j=i+1; j<N; j++) { 6850 final ResolveInfo rij = results.get(j); 6851 if (rij.filter != null && rij.filter.hasAction(action)) { 6852 results.remove(j); 6853 if (DEBUG_INTENT_MATCHING) Log.v( 6854 TAG, "Removing duplicate item from " + j 6855 + " due to action " + action + " at " + i); 6856 j--; 6857 N--; 6858 } 6859 } 6860 } 6861 6862 // If the caller didn't request filter information, drop it now 6863 // so we don't have to marshall/unmarshall it. 6864 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6865 rii.filter = null; 6866 } 6867 } 6868 6869 // Filter out the caller activity if so requested. 6870 if (caller != null) { 6871 N = results.size(); 6872 for (int i=0; i<N; i++) { 6873 ActivityInfo ainfo = results.get(i).activityInfo; 6874 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6875 && caller.getClassName().equals(ainfo.name)) { 6876 results.remove(i); 6877 break; 6878 } 6879 } 6880 } 6881 6882 // If the caller didn't request filter information, 6883 // drop them now so we don't have to 6884 // marshall/unmarshall it. 6885 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6886 N = results.size(); 6887 for (int i=0; i<N; i++) { 6888 results.get(i).filter = null; 6889 } 6890 } 6891 6892 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6893 return results; 6894 } 6895 6896 @Override 6897 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6898 String resolvedType, int flags, int userId) { 6899 return new ParceledListSlice<>( 6900 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6901 } 6902 6903 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6904 String resolvedType, int flags, int userId) { 6905 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6906 flags = updateFlagsForResolve(flags, userId, intent); 6907 ComponentName comp = intent.getComponent(); 6908 if (comp == null) { 6909 if (intent.getSelector() != null) { 6910 intent = intent.getSelector(); 6911 comp = intent.getComponent(); 6912 } 6913 } 6914 if (comp != null) { 6915 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6916 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6917 if (ai != null) { 6918 ResolveInfo ri = new ResolveInfo(); 6919 ri.activityInfo = ai; 6920 list.add(ri); 6921 } 6922 return list; 6923 } 6924 6925 // reader 6926 synchronized (mPackages) { 6927 String pkgName = intent.getPackage(); 6928 if (pkgName == null) { 6929 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6930 } 6931 final PackageParser.Package pkg = mPackages.get(pkgName); 6932 if (pkg != null) { 6933 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6934 userId); 6935 } 6936 return Collections.emptyList(); 6937 } 6938 } 6939 6940 @Override 6941 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6942 if (!sUserManager.exists(userId)) return null; 6943 flags = updateFlagsForResolve(flags, userId, intent); 6944 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6945 if (query != null) { 6946 if (query.size() >= 1) { 6947 // If there is more than one service with the same priority, 6948 // just arbitrarily pick the first one. 6949 return query.get(0); 6950 } 6951 } 6952 return null; 6953 } 6954 6955 @Override 6956 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6957 String resolvedType, int flags, int userId) { 6958 return new ParceledListSlice<>( 6959 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6960 } 6961 6962 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6963 String resolvedType, int flags, int userId) { 6964 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6965 flags = updateFlagsForResolve(flags, userId, intent); 6966 ComponentName comp = intent.getComponent(); 6967 if (comp == null) { 6968 if (intent.getSelector() != null) { 6969 intent = intent.getSelector(); 6970 comp = intent.getComponent(); 6971 } 6972 } 6973 if (comp != null) { 6974 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6975 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6976 if (si != null) { 6977 final ResolveInfo ri = new ResolveInfo(); 6978 ri.serviceInfo = si; 6979 list.add(ri); 6980 } 6981 return list; 6982 } 6983 6984 // reader 6985 synchronized (mPackages) { 6986 String pkgName = intent.getPackage(); 6987 if (pkgName == null) { 6988 return mServices.queryIntent(intent, resolvedType, flags, userId); 6989 } 6990 final PackageParser.Package pkg = mPackages.get(pkgName); 6991 if (pkg != null) { 6992 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6993 userId); 6994 } 6995 return Collections.emptyList(); 6996 } 6997 } 6998 6999 @Override 7000 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7001 String resolvedType, int flags, int userId) { 7002 return new ParceledListSlice<>( 7003 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7004 } 7005 7006 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7007 Intent intent, String resolvedType, int flags, int userId) { 7008 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7009 flags = updateFlagsForResolve(flags, userId, intent); 7010 ComponentName comp = intent.getComponent(); 7011 if (comp == null) { 7012 if (intent.getSelector() != null) { 7013 intent = intent.getSelector(); 7014 comp = intent.getComponent(); 7015 } 7016 } 7017 if (comp != null) { 7018 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7019 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7020 if (pi != null) { 7021 final ResolveInfo ri = new ResolveInfo(); 7022 ri.providerInfo = pi; 7023 list.add(ri); 7024 } 7025 return list; 7026 } 7027 7028 // reader 7029 synchronized (mPackages) { 7030 String pkgName = intent.getPackage(); 7031 if (pkgName == null) { 7032 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7033 } 7034 final PackageParser.Package pkg = mPackages.get(pkgName); 7035 if (pkg != null) { 7036 return mProviders.queryIntentForPackage( 7037 intent, resolvedType, flags, pkg.providers, userId); 7038 } 7039 return Collections.emptyList(); 7040 } 7041 } 7042 7043 @Override 7044 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7045 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7046 flags = updateFlagsForPackage(flags, userId, null); 7047 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7048 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7049 true /* requireFullPermission */, false /* checkShell */, 7050 "get installed packages"); 7051 7052 // writer 7053 synchronized (mPackages) { 7054 ArrayList<PackageInfo> list; 7055 if (listUninstalled) { 7056 list = new ArrayList<>(mSettings.mPackages.size()); 7057 for (PackageSetting ps : mSettings.mPackages.values()) { 7058 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7059 continue; 7060 } 7061 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7062 if (pi != null) { 7063 list.add(pi); 7064 } 7065 } 7066 } else { 7067 list = new ArrayList<>(mPackages.size()); 7068 for (PackageParser.Package p : mPackages.values()) { 7069 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7070 Binder.getCallingUid(), userId)) { 7071 continue; 7072 } 7073 final PackageInfo pi = generatePackageInfo((PackageSetting) 7074 p.mExtras, flags, userId); 7075 if (pi != null) { 7076 list.add(pi); 7077 } 7078 } 7079 } 7080 7081 return new ParceledListSlice<>(list); 7082 } 7083 } 7084 7085 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7086 String[] permissions, boolean[] tmp, int flags, int userId) { 7087 int numMatch = 0; 7088 final PermissionsState permissionsState = ps.getPermissionsState(); 7089 for (int i=0; i<permissions.length; i++) { 7090 final String permission = permissions[i]; 7091 if (permissionsState.hasPermission(permission, userId)) { 7092 tmp[i] = true; 7093 numMatch++; 7094 } else { 7095 tmp[i] = false; 7096 } 7097 } 7098 if (numMatch == 0) { 7099 return; 7100 } 7101 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7102 7103 // The above might return null in cases of uninstalled apps or install-state 7104 // skew across users/profiles. 7105 if (pi != null) { 7106 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7107 if (numMatch == permissions.length) { 7108 pi.requestedPermissions = permissions; 7109 } else { 7110 pi.requestedPermissions = new String[numMatch]; 7111 numMatch = 0; 7112 for (int i=0; i<permissions.length; i++) { 7113 if (tmp[i]) { 7114 pi.requestedPermissions[numMatch] = permissions[i]; 7115 numMatch++; 7116 } 7117 } 7118 } 7119 } 7120 list.add(pi); 7121 } 7122 } 7123 7124 @Override 7125 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7126 String[] permissions, int flags, int userId) { 7127 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7128 flags = updateFlagsForPackage(flags, userId, permissions); 7129 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7130 true /* requireFullPermission */, false /* checkShell */, 7131 "get packages holding permissions"); 7132 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7133 7134 // writer 7135 synchronized (mPackages) { 7136 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7137 boolean[] tmpBools = new boolean[permissions.length]; 7138 if (listUninstalled) { 7139 for (PackageSetting ps : mSettings.mPackages.values()) { 7140 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7141 userId); 7142 } 7143 } else { 7144 for (PackageParser.Package pkg : mPackages.values()) { 7145 PackageSetting ps = (PackageSetting)pkg.mExtras; 7146 if (ps != null) { 7147 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7148 userId); 7149 } 7150 } 7151 } 7152 7153 return new ParceledListSlice<PackageInfo>(list); 7154 } 7155 } 7156 7157 @Override 7158 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7159 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7160 flags = updateFlagsForApplication(flags, userId, null); 7161 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7162 7163 // writer 7164 synchronized (mPackages) { 7165 ArrayList<ApplicationInfo> list; 7166 if (listUninstalled) { 7167 list = new ArrayList<>(mSettings.mPackages.size()); 7168 for (PackageSetting ps : mSettings.mPackages.values()) { 7169 ApplicationInfo ai; 7170 int effectiveFlags = flags; 7171 if (ps.isSystem()) { 7172 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7173 } 7174 if (ps.pkg != null) { 7175 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7176 continue; 7177 } 7178 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7179 ps.readUserState(userId), userId); 7180 if (ai != null) { 7181 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7182 } 7183 } else { 7184 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7185 // and already converts to externally visible package name 7186 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7187 Binder.getCallingUid(), effectiveFlags, userId); 7188 } 7189 if (ai != null) { 7190 list.add(ai); 7191 } 7192 } 7193 } else { 7194 list = new ArrayList<>(mPackages.size()); 7195 for (PackageParser.Package p : mPackages.values()) { 7196 if (p.mExtras != null) { 7197 PackageSetting ps = (PackageSetting) p.mExtras; 7198 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7199 continue; 7200 } 7201 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7202 ps.readUserState(userId), userId); 7203 if (ai != null) { 7204 ai.packageName = resolveExternalPackageNameLPr(p); 7205 list.add(ai); 7206 } 7207 } 7208 } 7209 } 7210 7211 return new ParceledListSlice<>(list); 7212 } 7213 } 7214 7215 @Override 7216 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7217 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7218 return null; 7219 } 7220 7221 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7222 "getEphemeralApplications"); 7223 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7224 true /* requireFullPermission */, false /* checkShell */, 7225 "getEphemeralApplications"); 7226 synchronized (mPackages) { 7227 List<InstantAppInfo> instantApps = mInstantAppRegistry 7228 .getInstantAppsLPr(userId); 7229 if (instantApps != null) { 7230 return new ParceledListSlice<>(instantApps); 7231 } 7232 } 7233 return null; 7234 } 7235 7236 @Override 7237 public boolean isInstantApp(String packageName, int userId) { 7238 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7239 true /* requireFullPermission */, false /* checkShell */, 7240 "isInstantApp"); 7241 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7242 return false; 7243 } 7244 7245 if (!isCallerSameApp(packageName)) { 7246 return false; 7247 } 7248 synchronized (mPackages) { 7249 final PackageSetting ps = mSettings.mPackages.get(packageName); 7250 if (ps != null) { 7251 return ps.getInstantApp(userId); 7252 } 7253 } 7254 return false; 7255 } 7256 7257 @Override 7258 public byte[] getInstantAppCookie(String packageName, int userId) { 7259 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7260 return null; 7261 } 7262 7263 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7264 true /* requireFullPermission */, false /* checkShell */, 7265 "getInstantAppCookie"); 7266 if (!isCallerSameApp(packageName)) { 7267 return null; 7268 } 7269 synchronized (mPackages) { 7270 return mInstantAppRegistry.getInstantAppCookieLPw( 7271 packageName, userId); 7272 } 7273 } 7274 7275 @Override 7276 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7277 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7278 return true; 7279 } 7280 7281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7282 true /* requireFullPermission */, true /* checkShell */, 7283 "setInstantAppCookie"); 7284 if (!isCallerSameApp(packageName)) { 7285 return false; 7286 } 7287 synchronized (mPackages) { 7288 return mInstantAppRegistry.setInstantAppCookieLPw( 7289 packageName, cookie, userId); 7290 } 7291 } 7292 7293 @Override 7294 public Bitmap getInstantAppIcon(String packageName, int userId) { 7295 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7296 return null; 7297 } 7298 7299 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7300 "getInstantAppIcon"); 7301 7302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7303 true /* requireFullPermission */, false /* checkShell */, 7304 "getInstantAppIcon"); 7305 7306 synchronized (mPackages) { 7307 return mInstantAppRegistry.getInstantAppIconLPw( 7308 packageName, userId); 7309 } 7310 } 7311 7312 private boolean isCallerSameApp(String packageName) { 7313 PackageParser.Package pkg = mPackages.get(packageName); 7314 return pkg != null 7315 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7316 } 7317 7318 @Override 7319 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7320 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7321 } 7322 7323 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7324 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7325 7326 // reader 7327 synchronized (mPackages) { 7328 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7329 final int userId = UserHandle.getCallingUserId(); 7330 while (i.hasNext()) { 7331 final PackageParser.Package p = i.next(); 7332 if (p.applicationInfo == null) continue; 7333 7334 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7335 && !p.applicationInfo.isDirectBootAware(); 7336 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7337 && p.applicationInfo.isDirectBootAware(); 7338 7339 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7340 && (!mSafeMode || isSystemApp(p)) 7341 && (matchesUnaware || matchesAware)) { 7342 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7343 if (ps != null) { 7344 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7345 ps.readUserState(userId), userId); 7346 if (ai != null) { 7347 finalList.add(ai); 7348 } 7349 } 7350 } 7351 } 7352 } 7353 7354 return finalList; 7355 } 7356 7357 @Override 7358 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7359 if (!sUserManager.exists(userId)) return null; 7360 flags = updateFlagsForComponent(flags, userId, name); 7361 // reader 7362 synchronized (mPackages) { 7363 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7364 PackageSetting ps = provider != null 7365 ? mSettings.mPackages.get(provider.owner.packageName) 7366 : null; 7367 return ps != null 7368 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7369 ? PackageParser.generateProviderInfo(provider, flags, 7370 ps.readUserState(userId), userId) 7371 : null; 7372 } 7373 } 7374 7375 /** 7376 * @deprecated 7377 */ 7378 @Deprecated 7379 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7380 // reader 7381 synchronized (mPackages) { 7382 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7383 .entrySet().iterator(); 7384 final int userId = UserHandle.getCallingUserId(); 7385 while (i.hasNext()) { 7386 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7387 PackageParser.Provider p = entry.getValue(); 7388 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7389 7390 if (ps != null && p.syncable 7391 && (!mSafeMode || (p.info.applicationInfo.flags 7392 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7393 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7394 ps.readUserState(userId), userId); 7395 if (info != null) { 7396 outNames.add(entry.getKey()); 7397 outInfo.add(info); 7398 } 7399 } 7400 } 7401 } 7402 } 7403 7404 @Override 7405 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7406 int uid, int flags) { 7407 final int userId = processName != null ? UserHandle.getUserId(uid) 7408 : UserHandle.getCallingUserId(); 7409 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7410 flags = updateFlagsForComponent(flags, userId, processName); 7411 7412 ArrayList<ProviderInfo> finalList = null; 7413 // reader 7414 synchronized (mPackages) { 7415 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7416 while (i.hasNext()) { 7417 final PackageParser.Provider p = i.next(); 7418 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7419 if (ps != null && p.info.authority != null 7420 && (processName == null 7421 || (p.info.processName.equals(processName) 7422 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7423 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7424 if (finalList == null) { 7425 finalList = new ArrayList<ProviderInfo>(3); 7426 } 7427 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7428 ps.readUserState(userId), userId); 7429 if (info != null) { 7430 finalList.add(info); 7431 } 7432 } 7433 } 7434 } 7435 7436 if (finalList != null) { 7437 Collections.sort(finalList, mProviderInitOrderSorter); 7438 return new ParceledListSlice<ProviderInfo>(finalList); 7439 } 7440 7441 return ParceledListSlice.emptyList(); 7442 } 7443 7444 @Override 7445 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7446 // reader 7447 synchronized (mPackages) { 7448 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7449 return PackageParser.generateInstrumentationInfo(i, flags); 7450 } 7451 } 7452 7453 @Override 7454 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7455 String targetPackage, int flags) { 7456 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7457 } 7458 7459 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7460 int flags) { 7461 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7462 7463 // reader 7464 synchronized (mPackages) { 7465 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7466 while (i.hasNext()) { 7467 final PackageParser.Instrumentation p = i.next(); 7468 if (targetPackage == null 7469 || targetPackage.equals(p.info.targetPackage)) { 7470 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7471 flags); 7472 if (ii != null) { 7473 finalList.add(ii); 7474 } 7475 } 7476 } 7477 } 7478 7479 return finalList; 7480 } 7481 7482 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 7483 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 7484 if (overlays == null) { 7485 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 7486 return; 7487 } 7488 for (PackageParser.Package opkg : overlays.values()) { 7489 // Not much to do if idmap fails: we already logged the error 7490 // and we certainly don't want to abort installation of pkg simply 7491 // because an overlay didn't fit properly. For these reasons, 7492 // ignore the return value of createIdmapForPackagePairLI. 7493 createIdmapForPackagePairLI(pkg, opkg); 7494 } 7495 } 7496 7497 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 7498 PackageParser.Package opkg) { 7499 if (!opkg.mTrustedOverlay) { 7500 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 7501 opkg.baseCodePath + ": overlay not trusted"); 7502 return false; 7503 } 7504 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 7505 if (overlaySet == null) { 7506 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 7507 opkg.baseCodePath + " but target package has no known overlays"); 7508 return false; 7509 } 7510 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7511 // TODO: generate idmap for split APKs 7512 try { 7513 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 7514 } catch (InstallerException e) { 7515 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 7516 + opkg.baseCodePath); 7517 return false; 7518 } 7519 PackageParser.Package[] overlayArray = 7520 overlaySet.values().toArray(new PackageParser.Package[0]); 7521 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 7522 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 7523 return p1.mOverlayPriority - p2.mOverlayPriority; 7524 } 7525 }; 7526 Arrays.sort(overlayArray, cmp); 7527 7528 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 7529 int i = 0; 7530 for (PackageParser.Package p : overlayArray) { 7531 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 7532 } 7533 return true; 7534 } 7535 7536 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7537 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7538 try { 7539 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7540 } finally { 7541 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7542 } 7543 } 7544 7545 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7546 final File[] files = dir.listFiles(); 7547 if (ArrayUtils.isEmpty(files)) { 7548 Log.d(TAG, "No files in app dir " + dir); 7549 return; 7550 } 7551 7552 if (DEBUG_PACKAGE_SCANNING) { 7553 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7554 + " flags=0x" + Integer.toHexString(parseFlags)); 7555 } 7556 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7557 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir); 7558 7559 // Submit files for parsing in parallel 7560 int fileCount = 0; 7561 for (File file : files) { 7562 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7563 && !PackageInstallerService.isStageName(file.getName()); 7564 if (!isPackage) { 7565 // Ignore entries which are not packages 7566 continue; 7567 } 7568 parallelPackageParser.submit(file, parseFlags); 7569 fileCount++; 7570 } 7571 7572 // Process results one by one 7573 for (; fileCount > 0; fileCount--) { 7574 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7575 Throwable throwable = parseResult.throwable; 7576 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7577 7578 if (throwable == null) { 7579 // Static shared libraries have synthetic package names 7580 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7581 renameStaticSharedLibraryPackage(parseResult.pkg); 7582 } 7583 try { 7584 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7585 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7586 currentTime, null); 7587 } 7588 } catch (PackageManagerException e) { 7589 errorCode = e.error; 7590 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7591 } 7592 } else if (throwable instanceof PackageParser.PackageParserException) { 7593 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7594 throwable; 7595 errorCode = e.error; 7596 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7597 } else { 7598 throw new IllegalStateException("Unexpected exception occurred while parsing " 7599 + parseResult.scanFile, throwable); 7600 } 7601 7602 // Delete invalid userdata apps 7603 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7604 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7605 logCriticalInfo(Log.WARN, 7606 "Deleting invalid package at " + parseResult.scanFile); 7607 removeCodePathLI(parseResult.scanFile); 7608 } 7609 } 7610 parallelPackageParser.close(); 7611 } 7612 7613 private static File getSettingsProblemFile() { 7614 File dataDir = Environment.getDataDirectory(); 7615 File systemDir = new File(dataDir, "system"); 7616 File fname = new File(systemDir, "uiderrors.txt"); 7617 return fname; 7618 } 7619 7620 static void reportSettingsProblem(int priority, String msg) { 7621 logCriticalInfo(priority, msg); 7622 } 7623 7624 static void logCriticalInfo(int priority, String msg) { 7625 Slog.println(priority, TAG, msg); 7626 EventLogTags.writePmCriticalInfo(msg); 7627 try { 7628 File fname = getSettingsProblemFile(); 7629 FileOutputStream out = new FileOutputStream(fname, true); 7630 PrintWriter pw = new FastPrintWriter(out); 7631 SimpleDateFormat formatter = new SimpleDateFormat(); 7632 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7633 pw.println(dateString + ": " + msg); 7634 pw.close(); 7635 FileUtils.setPermissions( 7636 fname.toString(), 7637 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7638 -1, -1); 7639 } catch (java.io.IOException e) { 7640 } 7641 } 7642 7643 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7644 if (srcFile.isDirectory()) { 7645 final File baseFile = new File(pkg.baseCodePath); 7646 long maxModifiedTime = baseFile.lastModified(); 7647 if (pkg.splitCodePaths != null) { 7648 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7649 final File splitFile = new File(pkg.splitCodePaths[i]); 7650 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7651 } 7652 } 7653 return maxModifiedTime; 7654 } 7655 return srcFile.lastModified(); 7656 } 7657 7658 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7659 final int policyFlags) throws PackageManagerException { 7660 // When upgrading from pre-N MR1, verify the package time stamp using the package 7661 // directory and not the APK file. 7662 final long lastModifiedTime = mIsPreNMR1Upgrade 7663 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7664 if (ps != null 7665 && ps.codePath.equals(srcFile) 7666 && ps.timeStamp == lastModifiedTime 7667 && !isCompatSignatureUpdateNeeded(pkg) 7668 && !isRecoverSignatureUpdateNeeded(pkg)) { 7669 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7670 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7671 ArraySet<PublicKey> signingKs; 7672 synchronized (mPackages) { 7673 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7674 } 7675 if (ps.signatures.mSignatures != null 7676 && ps.signatures.mSignatures.length != 0 7677 && signingKs != null) { 7678 // Optimization: reuse the existing cached certificates 7679 // if the package appears to be unchanged. 7680 pkg.mSignatures = ps.signatures.mSignatures; 7681 pkg.mSigningKeys = signingKs; 7682 return; 7683 } 7684 7685 Slog.w(TAG, "PackageSetting for " + ps.name 7686 + " is missing signatures. Collecting certs again to recover them."); 7687 } else { 7688 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7689 } 7690 7691 try { 7692 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7693 PackageParser.collectCertificates(pkg, policyFlags); 7694 } catch (PackageParserException e) { 7695 throw PackageManagerException.from(e); 7696 } finally { 7697 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7698 } 7699 } 7700 7701 /** 7702 * Traces a package scan. 7703 * @see #scanPackageLI(File, int, int, long, UserHandle) 7704 */ 7705 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7706 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7708 try { 7709 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7710 } finally { 7711 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7712 } 7713 } 7714 7715 /** 7716 * Scans a package and returns the newly parsed package. 7717 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7718 */ 7719 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7720 long currentTime, UserHandle user) throws PackageManagerException { 7721 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7722 PackageParser pp = new PackageParser(); 7723 pp.setSeparateProcesses(mSeparateProcesses); 7724 pp.setOnlyCoreApps(mOnlyCore); 7725 pp.setDisplayMetrics(mMetrics); 7726 7727 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7728 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7729 } 7730 7731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7732 final PackageParser.Package pkg; 7733 try { 7734 pkg = pp.parsePackage(scanFile, parseFlags); 7735 } catch (PackageParserException e) { 7736 throw PackageManagerException.from(e); 7737 } finally { 7738 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7739 } 7740 7741 // Static shared libraries have synthetic package names 7742 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7743 renameStaticSharedLibraryPackage(pkg); 7744 } 7745 7746 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7747 } 7748 7749 /** 7750 * Scans a package and returns the newly parsed package. 7751 * @throws PackageManagerException on a parse error. 7752 */ 7753 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7754 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7755 throws PackageManagerException { 7756 // If the package has children and this is the first dive in the function 7757 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7758 // packages (parent and children) would be successfully scanned before the 7759 // actual scan since scanning mutates internal state and we want to atomically 7760 // install the package and its children. 7761 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7762 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7763 scanFlags |= SCAN_CHECK_ONLY; 7764 } 7765 } else { 7766 scanFlags &= ~SCAN_CHECK_ONLY; 7767 } 7768 7769 // Scan the parent 7770 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7771 scanFlags, currentTime, user); 7772 7773 // Scan the children 7774 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7775 for (int i = 0; i < childCount; i++) { 7776 PackageParser.Package childPackage = pkg.childPackages.get(i); 7777 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7778 currentTime, user); 7779 } 7780 7781 7782 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7783 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7784 } 7785 7786 return scannedPkg; 7787 } 7788 7789 /** 7790 * Scans a package and returns the newly parsed package. 7791 * @throws PackageManagerException on a parse error. 7792 */ 7793 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7794 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7795 throws PackageManagerException { 7796 PackageSetting ps = null; 7797 PackageSetting updatedPkg; 7798 // reader 7799 synchronized (mPackages) { 7800 // Look to see if we already know about this package. 7801 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7802 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7803 // This package has been renamed to its original name. Let's 7804 // use that. 7805 ps = mSettings.getPackageLPr(oldName); 7806 } 7807 // If there was no original package, see one for the real package name. 7808 if (ps == null) { 7809 ps = mSettings.getPackageLPr(pkg.packageName); 7810 } 7811 // Check to see if this package could be hiding/updating a system 7812 // package. Must look for it either under the original or real 7813 // package name depending on our state. 7814 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7815 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7816 7817 // If this is a package we don't know about on the system partition, we 7818 // may need to remove disabled child packages on the system partition 7819 // or may need to not add child packages if the parent apk is updated 7820 // on the data partition and no longer defines this child package. 7821 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7822 // If this is a parent package for an updated system app and this system 7823 // app got an OTA update which no longer defines some of the child packages 7824 // we have to prune them from the disabled system packages. 7825 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7826 if (disabledPs != null) { 7827 final int scannedChildCount = (pkg.childPackages != null) 7828 ? pkg.childPackages.size() : 0; 7829 final int disabledChildCount = disabledPs.childPackageNames != null 7830 ? disabledPs.childPackageNames.size() : 0; 7831 for (int i = 0; i < disabledChildCount; i++) { 7832 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7833 boolean disabledPackageAvailable = false; 7834 for (int j = 0; j < scannedChildCount; j++) { 7835 PackageParser.Package childPkg = pkg.childPackages.get(j); 7836 if (childPkg.packageName.equals(disabledChildPackageName)) { 7837 disabledPackageAvailable = true; 7838 break; 7839 } 7840 } 7841 if (!disabledPackageAvailable) { 7842 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7843 } 7844 } 7845 } 7846 } 7847 } 7848 7849 boolean updatedPkgBetter = false; 7850 // First check if this is a system package that may involve an update 7851 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7852 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7853 // it needs to drop FLAG_PRIVILEGED. 7854 if (locationIsPrivileged(scanFile)) { 7855 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7856 } else { 7857 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7858 } 7859 7860 if (ps != null && !ps.codePath.equals(scanFile)) { 7861 // The path has changed from what was last scanned... check the 7862 // version of the new path against what we have stored to determine 7863 // what to do. 7864 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7865 if (pkg.mVersionCode <= ps.versionCode) { 7866 // The system package has been updated and the code path does not match 7867 // Ignore entry. Skip it. 7868 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7869 + " ignored: updated version " + ps.versionCode 7870 + " better than this " + pkg.mVersionCode); 7871 if (!updatedPkg.codePath.equals(scanFile)) { 7872 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7873 + ps.name + " changing from " + updatedPkg.codePathString 7874 + " to " + scanFile); 7875 updatedPkg.codePath = scanFile; 7876 updatedPkg.codePathString = scanFile.toString(); 7877 updatedPkg.resourcePath = scanFile; 7878 updatedPkg.resourcePathString = scanFile.toString(); 7879 } 7880 updatedPkg.pkg = pkg; 7881 updatedPkg.versionCode = pkg.mVersionCode; 7882 7883 // Update the disabled system child packages to point to the package too. 7884 final int childCount = updatedPkg.childPackageNames != null 7885 ? updatedPkg.childPackageNames.size() : 0; 7886 for (int i = 0; i < childCount; i++) { 7887 String childPackageName = updatedPkg.childPackageNames.get(i); 7888 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7889 childPackageName); 7890 if (updatedChildPkg != null) { 7891 updatedChildPkg.pkg = pkg; 7892 updatedChildPkg.versionCode = pkg.mVersionCode; 7893 } 7894 } 7895 7896 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7897 + scanFile + " ignored: updated version " + ps.versionCode 7898 + " better than this " + pkg.mVersionCode); 7899 } else { 7900 // The current app on the system partition is better than 7901 // what we have updated to on the data partition; switch 7902 // back to the system partition version. 7903 // At this point, its safely assumed that package installation for 7904 // apps in system partition will go through. If not there won't be a working 7905 // version of the app 7906 // writer 7907 synchronized (mPackages) { 7908 // Just remove the loaded entries from package lists. 7909 mPackages.remove(ps.name); 7910 } 7911 7912 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7913 + " reverting from " + ps.codePathString 7914 + ": new version " + pkg.mVersionCode 7915 + " better than installed " + ps.versionCode); 7916 7917 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7918 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7919 synchronized (mInstallLock) { 7920 args.cleanUpResourcesLI(); 7921 } 7922 synchronized (mPackages) { 7923 mSettings.enableSystemPackageLPw(ps.name); 7924 } 7925 updatedPkgBetter = true; 7926 } 7927 } 7928 } 7929 7930 if (updatedPkg != null) { 7931 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7932 // initially 7933 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7934 7935 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7936 // flag set initially 7937 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7938 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7939 } 7940 } 7941 7942 // Verify certificates against what was last scanned 7943 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7944 7945 /* 7946 * A new system app appeared, but we already had a non-system one of the 7947 * same name installed earlier. 7948 */ 7949 boolean shouldHideSystemApp = false; 7950 if (updatedPkg == null && ps != null 7951 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7952 /* 7953 * Check to make sure the signatures match first. If they don't, 7954 * wipe the installed application and its data. 7955 */ 7956 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7957 != PackageManager.SIGNATURE_MATCH) { 7958 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7959 + " signatures don't match existing userdata copy; removing"); 7960 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7961 "scanPackageInternalLI")) { 7962 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7963 } 7964 ps = null; 7965 } else { 7966 /* 7967 * If the newly-added system app is an older version than the 7968 * already installed version, hide it. It will be scanned later 7969 * and re-added like an update. 7970 */ 7971 if (pkg.mVersionCode <= ps.versionCode) { 7972 shouldHideSystemApp = true; 7973 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7974 + " but new version " + pkg.mVersionCode + " better than installed " 7975 + ps.versionCode + "; hiding system"); 7976 } else { 7977 /* 7978 * The newly found system app is a newer version that the 7979 * one previously installed. Simply remove the 7980 * already-installed application and replace it with our own 7981 * while keeping the application data. 7982 */ 7983 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7984 + " reverting from " + ps.codePathString + ": new version " 7985 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7986 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7987 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7988 synchronized (mInstallLock) { 7989 args.cleanUpResourcesLI(); 7990 } 7991 } 7992 } 7993 } 7994 7995 // The apk is forward locked (not public) if its code and resources 7996 // are kept in different files. (except for app in either system or 7997 // vendor path). 7998 // TODO grab this value from PackageSettings 7999 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8000 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8001 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8002 } 8003 } 8004 8005 // TODO: extend to support forward-locked splits 8006 String resourcePath = null; 8007 String baseResourcePath = null; 8008 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8009 if (ps != null && ps.resourcePathString != null) { 8010 resourcePath = ps.resourcePathString; 8011 baseResourcePath = ps.resourcePathString; 8012 } else { 8013 // Should not happen at all. Just log an error. 8014 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8015 } 8016 } else { 8017 resourcePath = pkg.codePath; 8018 baseResourcePath = pkg.baseCodePath; 8019 } 8020 8021 // Set application objects path explicitly. 8022 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8023 pkg.setApplicationInfoCodePath(pkg.codePath); 8024 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8025 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8026 pkg.setApplicationInfoResourcePath(resourcePath); 8027 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8028 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8029 8030 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8031 if (ps != null && ps.getInstantApp(userId)) { 8032 scanFlags |= SCAN_AS_INSTANT_APP; 8033 } 8034 8035 // Note that we invoke the following method only if we are about to unpack an application 8036 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8037 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8038 8039 /* 8040 * If the system app should be overridden by a previously installed 8041 * data, hide the system app now and let the /data/app scan pick it up 8042 * again. 8043 */ 8044 if (shouldHideSystemApp) { 8045 synchronized (mPackages) { 8046 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8047 } 8048 } 8049 8050 return scannedPkg; 8051 } 8052 8053 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8054 // Derive the new package synthetic package name 8055 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8056 + pkg.staticSharedLibVersion); 8057 } 8058 8059 private static String fixProcessName(String defProcessName, 8060 String processName) { 8061 if (processName == null) { 8062 return defProcessName; 8063 } 8064 return processName; 8065 } 8066 8067 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8068 throws PackageManagerException { 8069 if (pkgSetting.signatures.mSignatures != null) { 8070 // Already existing package. Make sure signatures match 8071 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8072 == PackageManager.SIGNATURE_MATCH; 8073 if (!match) { 8074 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8075 == PackageManager.SIGNATURE_MATCH; 8076 } 8077 if (!match) { 8078 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8079 == PackageManager.SIGNATURE_MATCH; 8080 } 8081 if (!match) { 8082 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8083 + pkg.packageName + " signatures do not match the " 8084 + "previously installed version; ignoring!"); 8085 } 8086 } 8087 8088 // Check for shared user signatures 8089 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8090 // Already existing package. Make sure signatures match 8091 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8092 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8093 if (!match) { 8094 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8095 == PackageManager.SIGNATURE_MATCH; 8096 } 8097 if (!match) { 8098 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8099 == PackageManager.SIGNATURE_MATCH; 8100 } 8101 if (!match) { 8102 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8103 "Package " + pkg.packageName 8104 + " has no signatures that match those in shared user " 8105 + pkgSetting.sharedUser.name + "; ignoring!"); 8106 } 8107 } 8108 } 8109 8110 /** 8111 * Enforces that only the system UID or root's UID can call a method exposed 8112 * via Binder. 8113 * 8114 * @param message used as message if SecurityException is thrown 8115 * @throws SecurityException if the caller is not system or root 8116 */ 8117 private static final void enforceSystemOrRoot(String message) { 8118 final int uid = Binder.getCallingUid(); 8119 if (uid != Process.SYSTEM_UID && uid != 0) { 8120 throw new SecurityException(message); 8121 } 8122 } 8123 8124 @Override 8125 public void performFstrimIfNeeded() { 8126 enforceSystemOrRoot("Only the system can request fstrim"); 8127 8128 // Before everything else, see whether we need to fstrim. 8129 try { 8130 IStorageManager sm = PackageHelper.getStorageManager(); 8131 if (sm != null) { 8132 boolean doTrim = false; 8133 final long interval = android.provider.Settings.Global.getLong( 8134 mContext.getContentResolver(), 8135 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8136 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8137 if (interval > 0) { 8138 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8139 if (timeSinceLast > interval) { 8140 doTrim = true; 8141 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8142 + "; running immediately"); 8143 } 8144 } 8145 if (doTrim) { 8146 final boolean dexOptDialogShown; 8147 synchronized (mPackages) { 8148 dexOptDialogShown = mDexOptDialogShown; 8149 } 8150 if (!isFirstBoot() && dexOptDialogShown) { 8151 try { 8152 ActivityManager.getService().showBootMessage( 8153 mContext.getResources().getString( 8154 R.string.android_upgrading_fstrim), true); 8155 } catch (RemoteException e) { 8156 } 8157 } 8158 sm.runMaintenance(); 8159 } 8160 } else { 8161 Slog.e(TAG, "storageManager service unavailable!"); 8162 } 8163 } catch (RemoteException e) { 8164 // Can't happen; StorageManagerService is local 8165 } 8166 } 8167 8168 @Override 8169 public void updatePackagesIfNeeded() { 8170 enforceSystemOrRoot("Only the system can request package update"); 8171 8172 // We need to re-extract after an OTA. 8173 boolean causeUpgrade = isUpgrade(); 8174 8175 // First boot or factory reset. 8176 // Note: we also handle devices that are upgrading to N right now as if it is their 8177 // first boot, as they do not have profile data. 8178 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8179 8180 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8181 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8182 8183 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8184 return; 8185 } 8186 8187 List<PackageParser.Package> pkgs; 8188 synchronized (mPackages) { 8189 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8190 } 8191 8192 final long startTime = System.nanoTime(); 8193 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8194 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8195 8196 final int elapsedTimeSeconds = 8197 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8198 8199 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8200 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8201 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8202 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8203 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8204 } 8205 8206 /** 8207 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8208 * containing statistics about the invocation. The array consists of three elements, 8209 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8210 * and {@code numberOfPackagesFailed}. 8211 */ 8212 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8213 String compilerFilter) { 8214 8215 int numberOfPackagesVisited = 0; 8216 int numberOfPackagesOptimized = 0; 8217 int numberOfPackagesSkipped = 0; 8218 int numberOfPackagesFailed = 0; 8219 final int numberOfPackagesToDexopt = pkgs.size(); 8220 8221 for (PackageParser.Package pkg : pkgs) { 8222 numberOfPackagesVisited++; 8223 8224 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8225 if (DEBUG_DEXOPT) { 8226 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8227 } 8228 numberOfPackagesSkipped++; 8229 continue; 8230 } 8231 8232 if (DEBUG_DEXOPT) { 8233 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8234 numberOfPackagesToDexopt + ": " + pkg.packageName); 8235 } 8236 8237 if (showDialog) { 8238 try { 8239 ActivityManager.getService().showBootMessage( 8240 mContext.getResources().getString(R.string.android_upgrading_apk, 8241 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8242 } catch (RemoteException e) { 8243 } 8244 synchronized (mPackages) { 8245 mDexOptDialogShown = true; 8246 } 8247 } 8248 8249 // If the OTA updates a system app which was previously preopted to a non-preopted state 8250 // the app might end up being verified at runtime. That's because by default the apps 8251 // are verify-profile but for preopted apps there's no profile. 8252 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8253 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8254 // filter (by default interpret-only). 8255 // Note that at this stage unused apps are already filtered. 8256 if (isSystemApp(pkg) && 8257 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8258 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8259 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8260 } 8261 8262 // checkProfiles is false to avoid merging profiles during boot which 8263 // might interfere with background compilation (b/28612421). 8264 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8265 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8266 // trade-off worth doing to save boot time work. 8267 int dexOptStatus = performDexOptTraced(pkg.packageName, 8268 false /* checkProfiles */, 8269 compilerFilter, 8270 false /* force */); 8271 switch (dexOptStatus) { 8272 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8273 numberOfPackagesOptimized++; 8274 break; 8275 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8276 numberOfPackagesSkipped++; 8277 break; 8278 case PackageDexOptimizer.DEX_OPT_FAILED: 8279 numberOfPackagesFailed++; 8280 break; 8281 default: 8282 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8283 break; 8284 } 8285 } 8286 8287 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8288 numberOfPackagesFailed }; 8289 } 8290 8291 @Override 8292 public void notifyPackageUse(String packageName, int reason) { 8293 synchronized (mPackages) { 8294 PackageParser.Package p = mPackages.get(packageName); 8295 if (p == null) { 8296 return; 8297 } 8298 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8299 } 8300 } 8301 8302 @Override 8303 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8304 int userId = UserHandle.getCallingUserId(); 8305 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8306 if (ai == null) { 8307 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8308 + loadingPackageName + ", user=" + userId); 8309 return; 8310 } 8311 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8312 } 8313 8314 // TODO: this is not used nor needed. Delete it. 8315 @Override 8316 public boolean performDexOptIfNeeded(String packageName) { 8317 int dexOptStatus = performDexOptTraced(packageName, 8318 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8319 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8320 } 8321 8322 @Override 8323 public boolean performDexOpt(String packageName, 8324 boolean checkProfiles, int compileReason, boolean force) { 8325 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8326 getCompilerFilterForReason(compileReason), force); 8327 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8328 } 8329 8330 @Override 8331 public boolean performDexOptMode(String packageName, 8332 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8333 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8334 targetCompilerFilter, force); 8335 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8336 } 8337 8338 private int performDexOptTraced(String packageName, 8339 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8340 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8341 try { 8342 return performDexOptInternal(packageName, checkProfiles, 8343 targetCompilerFilter, force); 8344 } finally { 8345 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8346 } 8347 } 8348 8349 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8350 // if the package can now be considered up to date for the given filter. 8351 private int performDexOptInternal(String packageName, 8352 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8353 PackageParser.Package p; 8354 synchronized (mPackages) { 8355 p = mPackages.get(packageName); 8356 if (p == null) { 8357 // Package could not be found. Report failure. 8358 return PackageDexOptimizer.DEX_OPT_FAILED; 8359 } 8360 mPackageUsage.maybeWriteAsync(mPackages); 8361 mCompilerStats.maybeWriteAsync(); 8362 } 8363 long callingId = Binder.clearCallingIdentity(); 8364 try { 8365 synchronized (mInstallLock) { 8366 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8367 targetCompilerFilter, force); 8368 } 8369 } finally { 8370 Binder.restoreCallingIdentity(callingId); 8371 } 8372 } 8373 8374 public ArraySet<String> getOptimizablePackages() { 8375 ArraySet<String> pkgs = new ArraySet<String>(); 8376 synchronized (mPackages) { 8377 for (PackageParser.Package p : mPackages.values()) { 8378 if (PackageDexOptimizer.canOptimizePackage(p)) { 8379 pkgs.add(p.packageName); 8380 } 8381 } 8382 } 8383 return pkgs; 8384 } 8385 8386 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8387 boolean checkProfiles, String targetCompilerFilter, 8388 boolean force) { 8389 // Select the dex optimizer based on the force parameter. 8390 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8391 // allocate an object here. 8392 PackageDexOptimizer pdo = force 8393 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8394 : mPackageDexOptimizer; 8395 8396 // Optimize all dependencies first. Note: we ignore the return value and march on 8397 // on errors. 8398 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8399 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8400 if (!deps.isEmpty()) { 8401 for (PackageParser.Package depPackage : deps) { 8402 // TODO: Analyze and investigate if we (should) profile libraries. 8403 // Currently this will do a full compilation of the library by default. 8404 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8405 false /* checkProfiles */, 8406 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8407 getOrCreateCompilerPackageStats(depPackage)); 8408 } 8409 } 8410 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8411 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 8412 } 8413 8414 // Performs dexopt on the used secondary dex files belonging to the given package. 8415 // Returns true if all dex files were process successfully (which could mean either dexopt or 8416 // skip). Returns false if any of the files caused errors. 8417 @Override 8418 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8419 boolean force) { 8420 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8421 } 8422 8423 /** 8424 * Reconcile the information we have about the secondary dex files belonging to 8425 * {@code packagName} and the actual dex files. For all dex files that were 8426 * deleted, update the internal records and delete the generated oat files. 8427 */ 8428 @Override 8429 public void reconcileSecondaryDexFiles(String packageName) { 8430 mDexManager.reconcileSecondaryDexFiles(packageName); 8431 } 8432 8433 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8434 // a reference there. 8435 /*package*/ DexManager getDexManager() { 8436 return mDexManager; 8437 } 8438 8439 /** 8440 * Execute the background dexopt job immediately. 8441 */ 8442 @Override 8443 public boolean runBackgroundDexoptJob() { 8444 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8445 } 8446 8447 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8448 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8449 || p.usesStaticLibraries != null) { 8450 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8451 Set<String> collectedNames = new HashSet<>(); 8452 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8453 8454 retValue.remove(p); 8455 8456 return retValue; 8457 } else { 8458 return Collections.emptyList(); 8459 } 8460 } 8461 8462 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8463 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8464 if (!collectedNames.contains(p.packageName)) { 8465 collectedNames.add(p.packageName); 8466 collected.add(p); 8467 8468 if (p.usesLibraries != null) { 8469 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8470 null, collected, collectedNames); 8471 } 8472 if (p.usesOptionalLibraries != null) { 8473 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8474 null, collected, collectedNames); 8475 } 8476 if (p.usesStaticLibraries != null) { 8477 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8478 p.usesStaticLibrariesVersions, collected, collectedNames); 8479 } 8480 } 8481 } 8482 8483 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8484 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8485 final int libNameCount = libs.size(); 8486 for (int i = 0; i < libNameCount; i++) { 8487 String libName = libs.get(i); 8488 int version = (versions != null && versions.length == libNameCount) 8489 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8490 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8491 if (libPkg != null) { 8492 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8493 } 8494 } 8495 } 8496 8497 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8498 synchronized (mPackages) { 8499 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8500 if (libEntry != null) { 8501 return mPackages.get(libEntry.apk); 8502 } 8503 return null; 8504 } 8505 } 8506 8507 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8508 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8509 if (versionedLib == null) { 8510 return null; 8511 } 8512 return versionedLib.get(version); 8513 } 8514 8515 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8516 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8517 pkg.staticSharedLibName); 8518 if (versionedLib == null) { 8519 return null; 8520 } 8521 int previousLibVersion = -1; 8522 final int versionCount = versionedLib.size(); 8523 for (int i = 0; i < versionCount; i++) { 8524 final int libVersion = versionedLib.keyAt(i); 8525 if (libVersion < pkg.staticSharedLibVersion) { 8526 previousLibVersion = Math.max(previousLibVersion, libVersion); 8527 } 8528 } 8529 if (previousLibVersion >= 0) { 8530 return versionedLib.get(previousLibVersion); 8531 } 8532 return null; 8533 } 8534 8535 public void shutdown() { 8536 mPackageUsage.writeNow(mPackages); 8537 mCompilerStats.writeNow(); 8538 } 8539 8540 @Override 8541 public void dumpProfiles(String packageName) { 8542 PackageParser.Package pkg; 8543 synchronized (mPackages) { 8544 pkg = mPackages.get(packageName); 8545 if (pkg == null) { 8546 throw new IllegalArgumentException("Unknown package: " + packageName); 8547 } 8548 } 8549 /* Only the shell, root, or the app user should be able to dump profiles. */ 8550 int callingUid = Binder.getCallingUid(); 8551 if (callingUid != Process.SHELL_UID && 8552 callingUid != Process.ROOT_UID && 8553 callingUid != pkg.applicationInfo.uid) { 8554 throw new SecurityException("dumpProfiles"); 8555 } 8556 8557 synchronized (mInstallLock) { 8558 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8559 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8560 try { 8561 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8562 String codePaths = TextUtils.join(";", allCodePaths); 8563 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8564 } catch (InstallerException e) { 8565 Slog.w(TAG, "Failed to dump profiles", e); 8566 } 8567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8568 } 8569 } 8570 8571 @Override 8572 public void forceDexOpt(String packageName) { 8573 enforceSystemOrRoot("forceDexOpt"); 8574 8575 PackageParser.Package pkg; 8576 synchronized (mPackages) { 8577 pkg = mPackages.get(packageName); 8578 if (pkg == null) { 8579 throw new IllegalArgumentException("Unknown package: " + packageName); 8580 } 8581 } 8582 8583 synchronized (mInstallLock) { 8584 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8585 8586 // Whoever is calling forceDexOpt wants a fully compiled package. 8587 // Don't use profiles since that may cause compilation to be skipped. 8588 final int res = performDexOptInternalWithDependenciesLI(pkg, 8589 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8590 true /* force */); 8591 8592 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8593 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8594 throw new IllegalStateException("Failed to dexopt: " + res); 8595 } 8596 } 8597 } 8598 8599 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8600 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8601 Slog.w(TAG, "Unable to update from " + oldPkg.name 8602 + " to " + newPkg.packageName 8603 + ": old package not in system partition"); 8604 return false; 8605 } else if (mPackages.get(oldPkg.name) != null) { 8606 Slog.w(TAG, "Unable to update from " + oldPkg.name 8607 + " to " + newPkg.packageName 8608 + ": old package still exists"); 8609 return false; 8610 } 8611 return true; 8612 } 8613 8614 void removeCodePathLI(File codePath) { 8615 if (codePath.isDirectory()) { 8616 try { 8617 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8618 } catch (InstallerException e) { 8619 Slog.w(TAG, "Failed to remove code path", e); 8620 } 8621 } else { 8622 codePath.delete(); 8623 } 8624 } 8625 8626 private int[] resolveUserIds(int userId) { 8627 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8628 } 8629 8630 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8631 if (pkg == null) { 8632 Slog.wtf(TAG, "Package was null!", new Throwable()); 8633 return; 8634 } 8635 clearAppDataLeafLIF(pkg, userId, flags); 8636 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8637 for (int i = 0; i < childCount; i++) { 8638 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8639 } 8640 } 8641 8642 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8643 final PackageSetting ps; 8644 synchronized (mPackages) { 8645 ps = mSettings.mPackages.get(pkg.packageName); 8646 } 8647 for (int realUserId : resolveUserIds(userId)) { 8648 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8649 try { 8650 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8651 ceDataInode); 8652 } catch (InstallerException e) { 8653 Slog.w(TAG, String.valueOf(e)); 8654 } 8655 } 8656 } 8657 8658 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8659 if (pkg == null) { 8660 Slog.wtf(TAG, "Package was null!", new Throwable()); 8661 return; 8662 } 8663 destroyAppDataLeafLIF(pkg, userId, flags); 8664 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8665 for (int i = 0; i < childCount; i++) { 8666 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8667 } 8668 } 8669 8670 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8671 final PackageSetting ps; 8672 synchronized (mPackages) { 8673 ps = mSettings.mPackages.get(pkg.packageName); 8674 } 8675 for (int realUserId : resolveUserIds(userId)) { 8676 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8677 try { 8678 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8679 ceDataInode); 8680 } catch (InstallerException e) { 8681 Slog.w(TAG, String.valueOf(e)); 8682 } 8683 } 8684 } 8685 8686 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8687 if (pkg == null) { 8688 Slog.wtf(TAG, "Package was null!", new Throwable()); 8689 return; 8690 } 8691 destroyAppProfilesLeafLIF(pkg); 8692 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8693 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8694 for (int i = 0; i < childCount; i++) { 8695 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8696 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8697 true /* removeBaseMarker */); 8698 } 8699 } 8700 8701 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8702 boolean removeBaseMarker) { 8703 if (pkg.isForwardLocked()) { 8704 return; 8705 } 8706 8707 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8708 try { 8709 path = PackageManagerServiceUtils.realpath(new File(path)); 8710 } catch (IOException e) { 8711 // TODO: Should we return early here ? 8712 Slog.w(TAG, "Failed to get canonical path", e); 8713 continue; 8714 } 8715 8716 final String useMarker = path.replace('/', '@'); 8717 for (int realUserId : resolveUserIds(userId)) { 8718 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8719 if (removeBaseMarker) { 8720 File foreignUseMark = new File(profileDir, useMarker); 8721 if (foreignUseMark.exists()) { 8722 if (!foreignUseMark.delete()) { 8723 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8724 + pkg.packageName); 8725 } 8726 } 8727 } 8728 8729 File[] markers = profileDir.listFiles(); 8730 if (markers != null) { 8731 final String searchString = "@" + pkg.packageName + "@"; 8732 // We also delete all markers that contain the package name we're 8733 // uninstalling. These are associated with secondary dex-files belonging 8734 // to the package. Reconstructing the path of these dex files is messy 8735 // in general. 8736 for (File marker : markers) { 8737 if (marker.getName().indexOf(searchString) > 0) { 8738 if (!marker.delete()) { 8739 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8740 + pkg.packageName); 8741 } 8742 } 8743 } 8744 } 8745 } 8746 } 8747 } 8748 8749 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8750 try { 8751 mInstaller.destroyAppProfiles(pkg.packageName); 8752 } catch (InstallerException e) { 8753 Slog.w(TAG, String.valueOf(e)); 8754 } 8755 } 8756 8757 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8758 if (pkg == null) { 8759 Slog.wtf(TAG, "Package was null!", new Throwable()); 8760 return; 8761 } 8762 clearAppProfilesLeafLIF(pkg); 8763 // We don't remove the base foreign use marker when clearing profiles because 8764 // we will rename it when the app is updated. Unlike the actual profile contents, 8765 // the foreign use marker is good across installs. 8766 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8767 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8768 for (int i = 0; i < childCount; i++) { 8769 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8770 } 8771 } 8772 8773 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8774 try { 8775 mInstaller.clearAppProfiles(pkg.packageName); 8776 } catch (InstallerException e) { 8777 Slog.w(TAG, String.valueOf(e)); 8778 } 8779 } 8780 8781 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8782 long lastUpdateTime) { 8783 // Set parent install/update time 8784 PackageSetting ps = (PackageSetting) pkg.mExtras; 8785 if (ps != null) { 8786 ps.firstInstallTime = firstInstallTime; 8787 ps.lastUpdateTime = lastUpdateTime; 8788 } 8789 // Set children install/update time 8790 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8791 for (int i = 0; i < childCount; i++) { 8792 PackageParser.Package childPkg = pkg.childPackages.get(i); 8793 ps = (PackageSetting) childPkg.mExtras; 8794 if (ps != null) { 8795 ps.firstInstallTime = firstInstallTime; 8796 ps.lastUpdateTime = lastUpdateTime; 8797 } 8798 } 8799 } 8800 8801 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8802 PackageParser.Package changingLib) { 8803 if (file.path != null) { 8804 usesLibraryFiles.add(file.path); 8805 return; 8806 } 8807 PackageParser.Package p = mPackages.get(file.apk); 8808 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8809 // If we are doing this while in the middle of updating a library apk, 8810 // then we need to make sure to use that new apk for determining the 8811 // dependencies here. (We haven't yet finished committing the new apk 8812 // to the package manager state.) 8813 if (p == null || p.packageName.equals(changingLib.packageName)) { 8814 p = changingLib; 8815 } 8816 } 8817 if (p != null) { 8818 usesLibraryFiles.addAll(p.getAllCodePaths()); 8819 } 8820 } 8821 8822 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8823 PackageParser.Package changingLib) throws PackageManagerException { 8824 if (pkg == null) { 8825 return; 8826 } 8827 ArraySet<String> usesLibraryFiles = null; 8828 if (pkg.usesLibraries != null) { 8829 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8830 null, null, pkg.packageName, changingLib, true, null); 8831 } 8832 if (pkg.usesStaticLibraries != null) { 8833 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8834 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8835 pkg.packageName, changingLib, true, usesLibraryFiles); 8836 } 8837 if (pkg.usesOptionalLibraries != null) { 8838 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8839 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8840 } 8841 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8842 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8843 } else { 8844 pkg.usesLibraryFiles = null; 8845 } 8846 } 8847 8848 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8849 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8850 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8851 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8852 throws PackageManagerException { 8853 final int libCount = requestedLibraries.size(); 8854 for (int i = 0; i < libCount; i++) { 8855 final String libName = requestedLibraries.get(i); 8856 final int libVersion = requiredVersions != null ? requiredVersions[i] 8857 : SharedLibraryInfo.VERSION_UNDEFINED; 8858 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8859 if (libEntry == null) { 8860 if (required) { 8861 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8862 "Package " + packageName + " requires unavailable shared library " 8863 + libName + "; failing!"); 8864 } else { 8865 Slog.w(TAG, "Package " + packageName 8866 + " desires unavailable shared library " 8867 + libName + "; ignoring!"); 8868 } 8869 } else { 8870 if (requiredVersions != null && requiredCertDigests != null) { 8871 if (libEntry.info.getVersion() != requiredVersions[i]) { 8872 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8873 "Package " + packageName + " requires unavailable static shared" 8874 + " library " + libName + " version " 8875 + libEntry.info.getVersion() + "; failing!"); 8876 } 8877 8878 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8879 if (libPkg == null) { 8880 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8881 "Package " + packageName + " requires unavailable static shared" 8882 + " library; failing!"); 8883 } 8884 8885 String expectedCertDigest = requiredCertDigests[i]; 8886 String libCertDigest = PackageUtils.computeCertSha256Digest( 8887 libPkg.mSignatures[0]); 8888 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8889 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8890 "Package " + packageName + " requires differently signed" + 8891 " static shared library; failing!"); 8892 } 8893 } 8894 8895 if (outUsedLibraries == null) { 8896 outUsedLibraries = new ArraySet<>(); 8897 } 8898 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8899 } 8900 } 8901 return outUsedLibraries; 8902 } 8903 8904 private static boolean hasString(List<String> list, List<String> which) { 8905 if (list == null) { 8906 return false; 8907 } 8908 for (int i=list.size()-1; i>=0; i--) { 8909 for (int j=which.size()-1; j>=0; j--) { 8910 if (which.get(j).equals(list.get(i))) { 8911 return true; 8912 } 8913 } 8914 } 8915 return false; 8916 } 8917 8918 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8919 PackageParser.Package changingPkg) { 8920 ArrayList<PackageParser.Package> res = null; 8921 for (PackageParser.Package pkg : mPackages.values()) { 8922 if (changingPkg != null 8923 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8924 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8925 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8926 changingPkg.staticSharedLibName)) { 8927 return null; 8928 } 8929 if (res == null) { 8930 res = new ArrayList<>(); 8931 } 8932 res.add(pkg); 8933 try { 8934 updateSharedLibrariesLPr(pkg, changingPkg); 8935 } catch (PackageManagerException e) { 8936 // If a system app update or an app and a required lib missing we 8937 // delete the package and for updated system apps keep the data as 8938 // it is better for the user to reinstall than to be in an limbo 8939 // state. Also libs disappearing under an app should never happen 8940 // - just in case. 8941 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8942 final int flags = pkg.isUpdatedSystemApp() 8943 ? PackageManager.DELETE_KEEP_DATA : 0; 8944 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8945 flags , null, true, null); 8946 } 8947 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8948 } 8949 } 8950 return res; 8951 } 8952 8953 /** 8954 * Derive the value of the {@code cpuAbiOverride} based on the provided 8955 * value and an optional stored value from the package settings. 8956 */ 8957 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8958 String cpuAbiOverride = null; 8959 8960 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8961 cpuAbiOverride = null; 8962 } else if (abiOverride != null) { 8963 cpuAbiOverride = abiOverride; 8964 } else if (settings != null) { 8965 cpuAbiOverride = settings.cpuAbiOverrideString; 8966 } 8967 8968 return cpuAbiOverride; 8969 } 8970 8971 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8972 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8973 throws PackageManagerException { 8974 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8975 // If the package has children and this is the first dive in the function 8976 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8977 // whether all packages (parent and children) would be successfully scanned 8978 // before the actual scan since scanning mutates internal state and we want 8979 // to atomically install the package and its children. 8980 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8981 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8982 scanFlags |= SCAN_CHECK_ONLY; 8983 } 8984 } else { 8985 scanFlags &= ~SCAN_CHECK_ONLY; 8986 } 8987 8988 final PackageParser.Package scannedPkg; 8989 try { 8990 // Scan the parent 8991 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8992 // Scan the children 8993 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8994 for (int i = 0; i < childCount; i++) { 8995 PackageParser.Package childPkg = pkg.childPackages.get(i); 8996 scanPackageLI(childPkg, policyFlags, 8997 scanFlags, currentTime, user); 8998 } 8999 } finally { 9000 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9001 } 9002 9003 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9004 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9005 } 9006 9007 return scannedPkg; 9008 } 9009 9010 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9011 int scanFlags, long currentTime, @Nullable UserHandle user) 9012 throws PackageManagerException { 9013 boolean success = false; 9014 try { 9015 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9016 currentTime, user); 9017 success = true; 9018 return res; 9019 } finally { 9020 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9021 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9022 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9023 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9024 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9025 } 9026 } 9027 } 9028 9029 /** 9030 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9031 */ 9032 private static boolean apkHasCode(String fileName) { 9033 StrictJarFile jarFile = null; 9034 try { 9035 jarFile = new StrictJarFile(fileName, 9036 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9037 return jarFile.findEntry("classes.dex") != null; 9038 } catch (IOException ignore) { 9039 } finally { 9040 try { 9041 if (jarFile != null) { 9042 jarFile.close(); 9043 } 9044 } catch (IOException ignore) {} 9045 } 9046 return false; 9047 } 9048 9049 /** 9050 * Enforces code policy for the package. This ensures that if an APK has 9051 * declared hasCode="true" in its manifest that the APK actually contains 9052 * code. 9053 * 9054 * @throws PackageManagerException If bytecode could not be found when it should exist 9055 */ 9056 private static void assertCodePolicy(PackageParser.Package pkg) 9057 throws PackageManagerException { 9058 final boolean shouldHaveCode = 9059 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9060 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9061 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9062 "Package " + pkg.baseCodePath + " code is missing"); 9063 } 9064 9065 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9066 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9067 final boolean splitShouldHaveCode = 9068 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9069 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9070 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9071 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9072 } 9073 } 9074 } 9075 } 9076 9077 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9078 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9079 throws PackageManagerException { 9080 if (DEBUG_PACKAGE_SCANNING) { 9081 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9082 Log.d(TAG, "Scanning package " + pkg.packageName); 9083 } 9084 9085 applyPolicy(pkg, policyFlags); 9086 9087 assertPackageIsValid(pkg, policyFlags, scanFlags); 9088 9089 // Initialize package source and resource directories 9090 final File scanFile = new File(pkg.codePath); 9091 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9092 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9093 9094 SharedUserSetting suid = null; 9095 PackageSetting pkgSetting = null; 9096 9097 // Getting the package setting may have a side-effect, so if we 9098 // are only checking if scan would succeed, stash a copy of the 9099 // old setting to restore at the end. 9100 PackageSetting nonMutatedPs = null; 9101 9102 // We keep references to the derived CPU Abis from settings in oder to reuse 9103 // them in the case where we're not upgrading or booting for the first time. 9104 String primaryCpuAbiFromSettings = null; 9105 String secondaryCpuAbiFromSettings = null; 9106 9107 // writer 9108 synchronized (mPackages) { 9109 if (pkg.mSharedUserId != null) { 9110 // SIDE EFFECTS; may potentially allocate a new shared user 9111 suid = mSettings.getSharedUserLPw( 9112 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9113 if (DEBUG_PACKAGE_SCANNING) { 9114 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9115 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9116 + "): packages=" + suid.packages); 9117 } 9118 } 9119 9120 // Check if we are renaming from an original package name. 9121 PackageSetting origPackage = null; 9122 String realName = null; 9123 if (pkg.mOriginalPackages != null) { 9124 // This package may need to be renamed to a previously 9125 // installed name. Let's check on that... 9126 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9127 if (pkg.mOriginalPackages.contains(renamed)) { 9128 // This package had originally been installed as the 9129 // original name, and we have already taken care of 9130 // transitioning to the new one. Just update the new 9131 // one to continue using the old name. 9132 realName = pkg.mRealPackage; 9133 if (!pkg.packageName.equals(renamed)) { 9134 // Callers into this function may have already taken 9135 // care of renaming the package; only do it here if 9136 // it is not already done. 9137 pkg.setPackageName(renamed); 9138 } 9139 } else { 9140 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9141 if ((origPackage = mSettings.getPackageLPr( 9142 pkg.mOriginalPackages.get(i))) != null) { 9143 // We do have the package already installed under its 9144 // original name... should we use it? 9145 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9146 // New package is not compatible with original. 9147 origPackage = null; 9148 continue; 9149 } else if (origPackage.sharedUser != null) { 9150 // Make sure uid is compatible between packages. 9151 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9152 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9153 + " to " + pkg.packageName + ": old uid " 9154 + origPackage.sharedUser.name 9155 + " differs from " + pkg.mSharedUserId); 9156 origPackage = null; 9157 continue; 9158 } 9159 // TODO: Add case when shared user id is added [b/28144775] 9160 } else { 9161 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9162 + pkg.packageName + " to old name " + origPackage.name); 9163 } 9164 break; 9165 } 9166 } 9167 } 9168 } 9169 9170 if (mTransferedPackages.contains(pkg.packageName)) { 9171 Slog.w(TAG, "Package " + pkg.packageName 9172 + " was transferred to another, but its .apk remains"); 9173 } 9174 9175 // See comments in nonMutatedPs declaration 9176 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9177 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9178 if (foundPs != null) { 9179 nonMutatedPs = new PackageSetting(foundPs); 9180 } 9181 } 9182 9183 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9184 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9185 if (foundPs != null) { 9186 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9187 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9188 } 9189 } 9190 9191 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9192 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9193 PackageManagerService.reportSettingsProblem(Log.WARN, 9194 "Package " + pkg.packageName + " shared user changed from " 9195 + (pkgSetting.sharedUser != null 9196 ? pkgSetting.sharedUser.name : "<nothing>") 9197 + " to " 9198 + (suid != null ? suid.name : "<nothing>") 9199 + "; replacing with new"); 9200 pkgSetting = null; 9201 } 9202 final PackageSetting oldPkgSetting = 9203 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9204 final PackageSetting disabledPkgSetting = 9205 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9206 9207 String[] usesStaticLibraries = null; 9208 if (pkg.usesStaticLibraries != null) { 9209 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9210 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9211 } 9212 9213 if (pkgSetting == null) { 9214 final String parentPackageName = (pkg.parentPackage != null) 9215 ? pkg.parentPackage.packageName : null; 9216 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9217 // REMOVE SharedUserSetting from method; update in a separate call 9218 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9219 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9220 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9221 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9222 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9223 true /*allowInstall*/, instantApp, parentPackageName, 9224 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9225 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9226 // SIDE EFFECTS; updates system state; move elsewhere 9227 if (origPackage != null) { 9228 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9229 } 9230 mSettings.addUserToSettingLPw(pkgSetting); 9231 } else { 9232 // REMOVE SharedUserSetting from method; update in a separate call. 9233 // 9234 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9235 // secondaryCpuAbi are not known at this point so we always update them 9236 // to null here, only to reset them at a later point. 9237 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9238 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9239 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9240 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9241 UserManagerService.getInstance(), usesStaticLibraries, 9242 pkg.usesStaticLibrariesVersions); 9243 } 9244 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9245 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9246 9247 // SIDE EFFECTS; modifies system state; move elsewhere 9248 if (pkgSetting.origPackage != null) { 9249 // If we are first transitioning from an original package, 9250 // fix up the new package's name now. We need to do this after 9251 // looking up the package under its new name, so getPackageLP 9252 // can take care of fiddling things correctly. 9253 pkg.setPackageName(origPackage.name); 9254 9255 // File a report about this. 9256 String msg = "New package " + pkgSetting.realName 9257 + " renamed to replace old package " + pkgSetting.name; 9258 reportSettingsProblem(Log.WARN, msg); 9259 9260 // Make a note of it. 9261 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9262 mTransferedPackages.add(origPackage.name); 9263 } 9264 9265 // No longer need to retain this. 9266 pkgSetting.origPackage = null; 9267 } 9268 9269 // SIDE EFFECTS; modifies system state; move elsewhere 9270 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9271 // Make a note of it. 9272 mTransferedPackages.add(pkg.packageName); 9273 } 9274 9275 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9276 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9277 } 9278 9279 if ((scanFlags & SCAN_BOOTING) == 0 9280 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9281 // Check all shared libraries and map to their actual file path. 9282 // We only do this here for apps not on a system dir, because those 9283 // are the only ones that can fail an install due to this. We 9284 // will take care of the system apps by updating all of their 9285 // library paths after the scan is done. Also during the initial 9286 // scan don't update any libs as we do this wholesale after all 9287 // apps are scanned to avoid dependency based scanning. 9288 updateSharedLibrariesLPr(pkg, null); 9289 } 9290 9291 if (mFoundPolicyFile) { 9292 SELinuxMMAC.assignSeInfoValue(pkg); 9293 } 9294 pkg.applicationInfo.uid = pkgSetting.appId; 9295 pkg.mExtras = pkgSetting; 9296 9297 9298 // Static shared libs have same package with different versions where 9299 // we internally use a synthetic package name to allow multiple versions 9300 // of the same package, therefore we need to compare signatures against 9301 // the package setting for the latest library version. 9302 PackageSetting signatureCheckPs = pkgSetting; 9303 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9304 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9305 if (libraryEntry != null) { 9306 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9307 } 9308 } 9309 9310 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9311 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9312 // We just determined the app is signed correctly, so bring 9313 // over the latest parsed certs. 9314 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9315 } else { 9316 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9317 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9318 "Package " + pkg.packageName + " upgrade keys do not match the " 9319 + "previously installed version"); 9320 } else { 9321 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9322 String msg = "System package " + pkg.packageName 9323 + " signature changed; retaining data."; 9324 reportSettingsProblem(Log.WARN, msg); 9325 } 9326 } 9327 } else { 9328 try { 9329 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9330 verifySignaturesLP(signatureCheckPs, pkg); 9331 // We just determined the app is signed correctly, so bring 9332 // over the latest parsed certs. 9333 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9334 } catch (PackageManagerException e) { 9335 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9336 throw e; 9337 } 9338 // The signature has changed, but this package is in the system 9339 // image... let's recover! 9340 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9341 // However... if this package is part of a shared user, but it 9342 // doesn't match the signature of the shared user, let's fail. 9343 // What this means is that you can't change the signatures 9344 // associated with an overall shared user, which doesn't seem all 9345 // that unreasonable. 9346 if (signatureCheckPs.sharedUser != null) { 9347 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9348 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9349 throw new PackageManagerException( 9350 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9351 "Signature mismatch for shared user: " 9352 + pkgSetting.sharedUser); 9353 } 9354 } 9355 // File a report about this. 9356 String msg = "System package " + pkg.packageName 9357 + " signature changed; retaining data."; 9358 reportSettingsProblem(Log.WARN, msg); 9359 } 9360 } 9361 9362 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9363 // This package wants to adopt ownership of permissions from 9364 // another package. 9365 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9366 final String origName = pkg.mAdoptPermissions.get(i); 9367 final PackageSetting orig = mSettings.getPackageLPr(origName); 9368 if (orig != null) { 9369 if (verifyPackageUpdateLPr(orig, pkg)) { 9370 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9371 + pkg.packageName); 9372 // SIDE EFFECTS; updates permissions system state; move elsewhere 9373 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9374 } 9375 } 9376 } 9377 } 9378 } 9379 9380 pkg.applicationInfo.processName = fixProcessName( 9381 pkg.applicationInfo.packageName, 9382 pkg.applicationInfo.processName); 9383 9384 if (pkg != mPlatformPackage) { 9385 // Get all of our default paths setup 9386 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9387 } 9388 9389 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9390 9391 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9392 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9393 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9394 derivePackageAbi( 9395 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9396 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9397 9398 // Some system apps still use directory structure for native libraries 9399 // in which case we might end up not detecting abi solely based on apk 9400 // structure. Try to detect abi based on directory structure. 9401 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9402 pkg.applicationInfo.primaryCpuAbi == null) { 9403 setBundledAppAbisAndRoots(pkg, pkgSetting); 9404 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9405 } 9406 } else { 9407 // This is not a first boot or an upgrade, don't bother deriving the 9408 // ABI during the scan. Instead, trust the value that was stored in the 9409 // package setting. 9410 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9411 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9412 9413 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9414 9415 if (DEBUG_ABI_SELECTION) { 9416 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9417 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9418 pkg.applicationInfo.secondaryCpuAbi); 9419 } 9420 } 9421 } else { 9422 if ((scanFlags & SCAN_MOVE) != 0) { 9423 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9424 // but we already have this packages package info in the PackageSetting. We just 9425 // use that and derive the native library path based on the new codepath. 9426 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9427 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9428 } 9429 9430 // Set native library paths again. For moves, the path will be updated based on the 9431 // ABIs we've determined above. For non-moves, the path will be updated based on the 9432 // ABIs we determined during compilation, but the path will depend on the final 9433 // package path (after the rename away from the stage path). 9434 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9435 } 9436 9437 // This is a special case for the "system" package, where the ABI is 9438 // dictated by the zygote configuration (and init.rc). We should keep track 9439 // of this ABI so that we can deal with "normal" applications that run under 9440 // the same UID correctly. 9441 if (mPlatformPackage == pkg) { 9442 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9443 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9444 } 9445 9446 // If there's a mismatch between the abi-override in the package setting 9447 // and the abiOverride specified for the install. Warn about this because we 9448 // would've already compiled the app without taking the package setting into 9449 // account. 9450 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9451 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9452 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9453 " for package " + pkg.packageName); 9454 } 9455 } 9456 9457 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9458 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9459 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9460 9461 // Copy the derived override back to the parsed package, so that we can 9462 // update the package settings accordingly. 9463 pkg.cpuAbiOverride = cpuAbiOverride; 9464 9465 if (DEBUG_ABI_SELECTION) { 9466 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9467 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9468 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9469 } 9470 9471 // Push the derived path down into PackageSettings so we know what to 9472 // clean up at uninstall time. 9473 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9474 9475 if (DEBUG_ABI_SELECTION) { 9476 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9477 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9478 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9479 } 9480 9481 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9482 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9483 // We don't do this here during boot because we can do it all 9484 // at once after scanning all existing packages. 9485 // 9486 // We also do this *before* we perform dexopt on this package, so that 9487 // we can avoid redundant dexopts, and also to make sure we've got the 9488 // code and package path correct. 9489 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9490 } 9491 9492 if (mFactoryTest && pkg.requestedPermissions.contains( 9493 android.Manifest.permission.FACTORY_TEST)) { 9494 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9495 } 9496 9497 if (isSystemApp(pkg)) { 9498 pkgSetting.isOrphaned = true; 9499 } 9500 9501 // Take care of first install / last update times. 9502 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9503 if (currentTime != 0) { 9504 if (pkgSetting.firstInstallTime == 0) { 9505 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9506 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9507 pkgSetting.lastUpdateTime = currentTime; 9508 } 9509 } else if (pkgSetting.firstInstallTime == 0) { 9510 // We need *something*. Take time time stamp of the file. 9511 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9512 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9513 if (scanFileTime != pkgSetting.timeStamp) { 9514 // A package on the system image has changed; consider this 9515 // to be an update. 9516 pkgSetting.lastUpdateTime = scanFileTime; 9517 } 9518 } 9519 pkgSetting.setTimeStamp(scanFileTime); 9520 9521 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9522 if (nonMutatedPs != null) { 9523 synchronized (mPackages) { 9524 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9525 } 9526 } 9527 } else { 9528 final int userId = user == null ? 0 : user.getIdentifier(); 9529 // Modify state for the given package setting 9530 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9531 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9532 if (pkgSetting.getInstantApp(userId)) { 9533 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9534 } 9535 } 9536 return pkg; 9537 } 9538 9539 /** 9540 * Applies policy to the parsed package based upon the given policy flags. 9541 * Ensures the package is in a good state. 9542 * <p> 9543 * Implementation detail: This method must NOT have any side effect. It would 9544 * ideally be static, but, it requires locks to read system state. 9545 */ 9546 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9547 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9548 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9549 if (pkg.applicationInfo.isDirectBootAware()) { 9550 // we're direct boot aware; set for all components 9551 for (PackageParser.Service s : pkg.services) { 9552 s.info.encryptionAware = s.info.directBootAware = true; 9553 } 9554 for (PackageParser.Provider p : pkg.providers) { 9555 p.info.encryptionAware = p.info.directBootAware = true; 9556 } 9557 for (PackageParser.Activity a : pkg.activities) { 9558 a.info.encryptionAware = a.info.directBootAware = true; 9559 } 9560 for (PackageParser.Activity r : pkg.receivers) { 9561 r.info.encryptionAware = r.info.directBootAware = true; 9562 } 9563 } 9564 } else { 9565 // Only allow system apps to be flagged as core apps. 9566 pkg.coreApp = false; 9567 // clear flags not applicable to regular apps 9568 pkg.applicationInfo.privateFlags &= 9569 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9570 pkg.applicationInfo.privateFlags &= 9571 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9572 } 9573 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9574 9575 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9576 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9577 } 9578 9579 if (!isSystemApp(pkg)) { 9580 // Only system apps can use these features. 9581 pkg.mOriginalPackages = null; 9582 pkg.mRealPackage = null; 9583 pkg.mAdoptPermissions = null; 9584 } 9585 } 9586 9587 /** 9588 * Asserts the parsed package is valid according to the given policy. If the 9589 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 9590 * <p> 9591 * Implementation detail: This method must NOT have any side effects. It would 9592 * ideally be static, but, it requires locks to read system state. 9593 * 9594 * @throws PackageManagerException If the package fails any of the validation checks 9595 */ 9596 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9597 throws PackageManagerException { 9598 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9599 assertCodePolicy(pkg); 9600 } 9601 9602 if (pkg.applicationInfo.getCodePath() == null || 9603 pkg.applicationInfo.getResourcePath() == null) { 9604 // Bail out. The resource and code paths haven't been set. 9605 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9606 "Code and resource paths haven't been set correctly"); 9607 } 9608 9609 // Make sure we're not adding any bogus keyset info 9610 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9611 ksms.assertScannedPackageValid(pkg); 9612 9613 synchronized (mPackages) { 9614 // The special "android" package can only be defined once 9615 if (pkg.packageName.equals("android")) { 9616 if (mAndroidApplication != null) { 9617 Slog.w(TAG, "*************************************************"); 9618 Slog.w(TAG, "Core android package being redefined. Skipping."); 9619 Slog.w(TAG, " codePath=" + pkg.codePath); 9620 Slog.w(TAG, "*************************************************"); 9621 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9622 "Core android package being redefined. Skipping."); 9623 } 9624 } 9625 9626 // A package name must be unique; don't allow duplicates 9627 if (mPackages.containsKey(pkg.packageName)) { 9628 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9629 "Application package " + pkg.packageName 9630 + " already installed. Skipping duplicate."); 9631 } 9632 9633 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9634 // Static libs have a synthetic package name containing the version 9635 // but we still want the base name to be unique. 9636 if (mPackages.containsKey(pkg.manifestPackageName)) { 9637 throw new PackageManagerException( 9638 "Duplicate static shared lib provider package"); 9639 } 9640 9641 // Static shared libraries should have at least O target SDK 9642 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9643 throw new PackageManagerException( 9644 "Packages declaring static-shared libs must target O SDK or higher"); 9645 } 9646 9647 // Package declaring static a shared lib cannot be instant apps 9648 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9649 throw new PackageManagerException( 9650 "Packages declaring static-shared libs cannot be instant apps"); 9651 } 9652 9653 // Package declaring static a shared lib cannot be renamed since the package 9654 // name is synthetic and apps can't code around package manager internals. 9655 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9656 throw new PackageManagerException( 9657 "Packages declaring static-shared libs cannot be renamed"); 9658 } 9659 9660 // Package declaring static a shared lib cannot declare child packages 9661 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9662 throw new PackageManagerException( 9663 "Packages declaring static-shared libs cannot have child packages"); 9664 } 9665 9666 // Package declaring static a shared lib cannot declare dynamic libs 9667 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9668 throw new PackageManagerException( 9669 "Packages declaring static-shared libs cannot declare dynamic libs"); 9670 } 9671 9672 // Package declaring static a shared lib cannot declare shared users 9673 if (pkg.mSharedUserId != null) { 9674 throw new PackageManagerException( 9675 "Packages declaring static-shared libs cannot declare shared users"); 9676 } 9677 9678 // Static shared libs cannot declare activities 9679 if (!pkg.activities.isEmpty()) { 9680 throw new PackageManagerException( 9681 "Static shared libs cannot declare activities"); 9682 } 9683 9684 // Static shared libs cannot declare services 9685 if (!pkg.services.isEmpty()) { 9686 throw new PackageManagerException( 9687 "Static shared libs cannot declare services"); 9688 } 9689 9690 // Static shared libs cannot declare providers 9691 if (!pkg.providers.isEmpty()) { 9692 throw new PackageManagerException( 9693 "Static shared libs cannot declare content providers"); 9694 } 9695 9696 // Static shared libs cannot declare receivers 9697 if (!pkg.receivers.isEmpty()) { 9698 throw new PackageManagerException( 9699 "Static shared libs cannot declare broadcast receivers"); 9700 } 9701 9702 // Static shared libs cannot declare permission groups 9703 if (!pkg.permissionGroups.isEmpty()) { 9704 throw new PackageManagerException( 9705 "Static shared libs cannot declare permission groups"); 9706 } 9707 9708 // Static shared libs cannot declare permissions 9709 if (!pkg.permissions.isEmpty()) { 9710 throw new PackageManagerException( 9711 "Static shared libs cannot declare permissions"); 9712 } 9713 9714 // Static shared libs cannot declare protected broadcasts 9715 if (pkg.protectedBroadcasts != null) { 9716 throw new PackageManagerException( 9717 "Static shared libs cannot declare protected broadcasts"); 9718 } 9719 9720 // Static shared libs cannot be overlay targets 9721 if (pkg.mOverlayTarget != null) { 9722 throw new PackageManagerException( 9723 "Static shared libs cannot be overlay targets"); 9724 } 9725 9726 // The version codes must be ordered as lib versions 9727 int minVersionCode = Integer.MIN_VALUE; 9728 int maxVersionCode = Integer.MAX_VALUE; 9729 9730 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9731 pkg.staticSharedLibName); 9732 if (versionedLib != null) { 9733 final int versionCount = versionedLib.size(); 9734 for (int i = 0; i < versionCount; i++) { 9735 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9736 // TODO: We will change version code to long, so in the new API it is long 9737 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9738 .getVersionCode(); 9739 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9740 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9741 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9742 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9743 } else { 9744 minVersionCode = maxVersionCode = libVersionCode; 9745 break; 9746 } 9747 } 9748 } 9749 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9750 throw new PackageManagerException("Static shared" 9751 + " lib version codes must be ordered as lib versions"); 9752 } 9753 } 9754 9755 // Only privileged apps and updated privileged apps can add child packages. 9756 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9757 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9758 throw new PackageManagerException("Only privileged apps can add child " 9759 + "packages. Ignoring package " + pkg.packageName); 9760 } 9761 final int childCount = pkg.childPackages.size(); 9762 for (int i = 0; i < childCount; i++) { 9763 PackageParser.Package childPkg = pkg.childPackages.get(i); 9764 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9765 childPkg.packageName)) { 9766 throw new PackageManagerException("Can't override child of " 9767 + "another disabled app. Ignoring package " + pkg.packageName); 9768 } 9769 } 9770 } 9771 9772 // If we're only installing presumed-existing packages, require that the 9773 // scanned APK is both already known and at the path previously established 9774 // for it. Previously unknown packages we pick up normally, but if we have an 9775 // a priori expectation about this package's install presence, enforce it. 9776 // With a singular exception for new system packages. When an OTA contains 9777 // a new system package, we allow the codepath to change from a system location 9778 // to the user-installed location. If we don't allow this change, any newer, 9779 // user-installed version of the application will be ignored. 9780 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9781 if (mExpectingBetter.containsKey(pkg.packageName)) { 9782 logCriticalInfo(Log.WARN, 9783 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9784 } else { 9785 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9786 if (known != null) { 9787 if (DEBUG_PACKAGE_SCANNING) { 9788 Log.d(TAG, "Examining " + pkg.codePath 9789 + " and requiring known paths " + known.codePathString 9790 + " & " + known.resourcePathString); 9791 } 9792 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9793 || !pkg.applicationInfo.getResourcePath().equals( 9794 known.resourcePathString)) { 9795 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9796 "Application package " + pkg.packageName 9797 + " found at " + pkg.applicationInfo.getCodePath() 9798 + " but expected at " + known.codePathString 9799 + "; ignoring."); 9800 } 9801 } 9802 } 9803 } 9804 9805 // Verify that this new package doesn't have any content providers 9806 // that conflict with existing packages. Only do this if the 9807 // package isn't already installed, since we don't want to break 9808 // things that are installed. 9809 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9810 final int N = pkg.providers.size(); 9811 int i; 9812 for (i=0; i<N; i++) { 9813 PackageParser.Provider p = pkg.providers.get(i); 9814 if (p.info.authority != null) { 9815 String names[] = p.info.authority.split(";"); 9816 for (int j = 0; j < names.length; j++) { 9817 if (mProvidersByAuthority.containsKey(names[j])) { 9818 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9819 final String otherPackageName = 9820 ((other != null && other.getComponentName() != null) ? 9821 other.getComponentName().getPackageName() : "?"); 9822 throw new PackageManagerException( 9823 INSTALL_FAILED_CONFLICTING_PROVIDER, 9824 "Can't install because provider name " + names[j] 9825 + " (in package " + pkg.applicationInfo.packageName 9826 + ") is already used by " + otherPackageName); 9827 } 9828 } 9829 } 9830 } 9831 } 9832 } 9833 } 9834 9835 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9836 int type, String declaringPackageName, int declaringVersionCode) { 9837 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9838 if (versionedLib == null) { 9839 versionedLib = new SparseArray<>(); 9840 mSharedLibraries.put(name, versionedLib); 9841 if (type == SharedLibraryInfo.TYPE_STATIC) { 9842 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9843 } 9844 } else if (versionedLib.indexOfKey(version) >= 0) { 9845 return false; 9846 } 9847 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9848 version, type, declaringPackageName, declaringVersionCode); 9849 versionedLib.put(version, libEntry); 9850 return true; 9851 } 9852 9853 private boolean removeSharedLibraryLPw(String name, int version) { 9854 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9855 if (versionedLib == null) { 9856 return false; 9857 } 9858 final int libIdx = versionedLib.indexOfKey(version); 9859 if (libIdx < 0) { 9860 return false; 9861 } 9862 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9863 versionedLib.remove(version); 9864 if (versionedLib.size() <= 0) { 9865 mSharedLibraries.remove(name); 9866 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9867 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9868 .getPackageName()); 9869 } 9870 } 9871 return true; 9872 } 9873 9874 /** 9875 * Adds a scanned package to the system. When this method is finished, the package will 9876 * be available for query, resolution, etc... 9877 */ 9878 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9879 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9880 final String pkgName = pkg.packageName; 9881 if (mCustomResolverComponentName != null && 9882 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9883 setUpCustomResolverActivity(pkg); 9884 } 9885 9886 if (pkg.packageName.equals("android")) { 9887 synchronized (mPackages) { 9888 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9889 // Set up information for our fall-back user intent resolution activity. 9890 mPlatformPackage = pkg; 9891 pkg.mVersionCode = mSdkVersion; 9892 mAndroidApplication = pkg.applicationInfo; 9893 if (!mResolverReplaced) { 9894 mResolveActivity.applicationInfo = mAndroidApplication; 9895 mResolveActivity.name = ResolverActivity.class.getName(); 9896 mResolveActivity.packageName = mAndroidApplication.packageName; 9897 mResolveActivity.processName = "system:ui"; 9898 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9899 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9900 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9901 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9902 mResolveActivity.exported = true; 9903 mResolveActivity.enabled = true; 9904 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9905 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9906 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9907 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9908 | ActivityInfo.CONFIG_ORIENTATION 9909 | ActivityInfo.CONFIG_KEYBOARD 9910 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9911 mResolveInfo.activityInfo = mResolveActivity; 9912 mResolveInfo.priority = 0; 9913 mResolveInfo.preferredOrder = 0; 9914 mResolveInfo.match = 0; 9915 mResolveComponentName = new ComponentName( 9916 mAndroidApplication.packageName, mResolveActivity.name); 9917 } 9918 } 9919 } 9920 } 9921 9922 ArrayList<PackageParser.Package> clientLibPkgs = null; 9923 // writer 9924 synchronized (mPackages) { 9925 boolean hasStaticSharedLibs = false; 9926 9927 // Any app can add new static shared libraries 9928 if (pkg.staticSharedLibName != null) { 9929 // Static shared libs don't allow renaming as they have synthetic package 9930 // names to allow install of multiple versions, so use name from manifest. 9931 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9932 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9933 pkg.manifestPackageName, pkg.mVersionCode)) { 9934 hasStaticSharedLibs = true; 9935 } else { 9936 Slog.w(TAG, "Package " + pkg.packageName + " library " 9937 + pkg.staticSharedLibName + " already exists; skipping"); 9938 } 9939 // Static shared libs cannot be updated once installed since they 9940 // use synthetic package name which includes the version code, so 9941 // not need to update other packages's shared lib dependencies. 9942 } 9943 9944 if (!hasStaticSharedLibs 9945 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9946 // Only system apps can add new dynamic shared libraries. 9947 if (pkg.libraryNames != null) { 9948 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9949 String name = pkg.libraryNames.get(i); 9950 boolean allowed = false; 9951 if (pkg.isUpdatedSystemApp()) { 9952 // New library entries can only be added through the 9953 // system image. This is important to get rid of a lot 9954 // of nasty edge cases: for example if we allowed a non- 9955 // system update of the app to add a library, then uninstalling 9956 // the update would make the library go away, and assumptions 9957 // we made such as through app install filtering would now 9958 // have allowed apps on the device which aren't compatible 9959 // with it. Better to just have the restriction here, be 9960 // conservative, and create many fewer cases that can negatively 9961 // impact the user experience. 9962 final PackageSetting sysPs = mSettings 9963 .getDisabledSystemPkgLPr(pkg.packageName); 9964 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9965 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9966 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9967 allowed = true; 9968 break; 9969 } 9970 } 9971 } 9972 } else { 9973 allowed = true; 9974 } 9975 if (allowed) { 9976 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9977 SharedLibraryInfo.VERSION_UNDEFINED, 9978 SharedLibraryInfo.TYPE_DYNAMIC, 9979 pkg.packageName, pkg.mVersionCode)) { 9980 Slog.w(TAG, "Package " + pkg.packageName + " library " 9981 + name + " already exists; skipping"); 9982 } 9983 } else { 9984 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9985 + name + " that is not declared on system image; skipping"); 9986 } 9987 } 9988 9989 if ((scanFlags & SCAN_BOOTING) == 0) { 9990 // If we are not booting, we need to update any applications 9991 // that are clients of our shared library. If we are booting, 9992 // this will all be done once the scan is complete. 9993 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9994 } 9995 } 9996 } 9997 } 9998 9999 if ((scanFlags & SCAN_BOOTING) != 0) { 10000 // No apps can run during boot scan, so they don't need to be frozen 10001 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10002 // Caller asked to not kill app, so it's probably not frozen 10003 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10004 // Caller asked us to ignore frozen check for some reason; they 10005 // probably didn't know the package name 10006 } else { 10007 // We're doing major surgery on this package, so it better be frozen 10008 // right now to keep it from launching 10009 checkPackageFrozen(pkgName); 10010 } 10011 10012 // Also need to kill any apps that are dependent on the library. 10013 if (clientLibPkgs != null) { 10014 for (int i=0; i<clientLibPkgs.size(); i++) { 10015 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10016 killApplication(clientPkg.applicationInfo.packageName, 10017 clientPkg.applicationInfo.uid, "update lib"); 10018 } 10019 } 10020 10021 // writer 10022 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10023 10024 boolean createIdmapFailed = false; 10025 synchronized (mPackages) { 10026 // We don't expect installation to fail beyond this point 10027 10028 if (pkgSetting.pkg != null) { 10029 // Note that |user| might be null during the initial boot scan. If a codePath 10030 // for an app has changed during a boot scan, it's due to an app update that's 10031 // part of the system partition and marker changes must be applied to all users. 10032 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 10033 final int[] userIds = resolveUserIds(userId); 10034 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 10035 } 10036 10037 // Add the new setting to mSettings 10038 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10039 // Add the new setting to mPackages 10040 mPackages.put(pkg.applicationInfo.packageName, pkg); 10041 // Make sure we don't accidentally delete its data. 10042 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10043 while (iter.hasNext()) { 10044 PackageCleanItem item = iter.next(); 10045 if (pkgName.equals(item.packageName)) { 10046 iter.remove(); 10047 } 10048 } 10049 10050 // Add the package's KeySets to the global KeySetManagerService 10051 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10052 ksms.addScannedPackageLPw(pkg); 10053 10054 int N = pkg.providers.size(); 10055 StringBuilder r = null; 10056 int i; 10057 for (i=0; i<N; i++) { 10058 PackageParser.Provider p = pkg.providers.get(i); 10059 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10060 p.info.processName); 10061 mProviders.addProvider(p); 10062 p.syncable = p.info.isSyncable; 10063 if (p.info.authority != null) { 10064 String names[] = p.info.authority.split(";"); 10065 p.info.authority = null; 10066 for (int j = 0; j < names.length; j++) { 10067 if (j == 1 && p.syncable) { 10068 // We only want the first authority for a provider to possibly be 10069 // syncable, so if we already added this provider using a different 10070 // authority clear the syncable flag. We copy the provider before 10071 // changing it because the mProviders object contains a reference 10072 // to a provider that we don't want to change. 10073 // Only do this for the second authority since the resulting provider 10074 // object can be the same for all future authorities for this provider. 10075 p = new PackageParser.Provider(p); 10076 p.syncable = false; 10077 } 10078 if (!mProvidersByAuthority.containsKey(names[j])) { 10079 mProvidersByAuthority.put(names[j], p); 10080 if (p.info.authority == null) { 10081 p.info.authority = names[j]; 10082 } else { 10083 p.info.authority = p.info.authority + ";" + names[j]; 10084 } 10085 if (DEBUG_PACKAGE_SCANNING) { 10086 if (chatty) 10087 Log.d(TAG, "Registered content provider: " + names[j] 10088 + ", className = " + p.info.name + ", isSyncable = " 10089 + p.info.isSyncable); 10090 } 10091 } else { 10092 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10093 Slog.w(TAG, "Skipping provider name " + names[j] + 10094 " (in package " + pkg.applicationInfo.packageName + 10095 "): name already used by " 10096 + ((other != null && other.getComponentName() != null) 10097 ? other.getComponentName().getPackageName() : "?")); 10098 } 10099 } 10100 } 10101 if (chatty) { 10102 if (r == null) { 10103 r = new StringBuilder(256); 10104 } else { 10105 r.append(' '); 10106 } 10107 r.append(p.info.name); 10108 } 10109 } 10110 if (r != null) { 10111 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10112 } 10113 10114 N = pkg.services.size(); 10115 r = null; 10116 for (i=0; i<N; i++) { 10117 PackageParser.Service s = pkg.services.get(i); 10118 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10119 s.info.processName); 10120 mServices.addService(s); 10121 if (chatty) { 10122 if (r == null) { 10123 r = new StringBuilder(256); 10124 } else { 10125 r.append(' '); 10126 } 10127 r.append(s.info.name); 10128 } 10129 } 10130 if (r != null) { 10131 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10132 } 10133 10134 N = pkg.receivers.size(); 10135 r = null; 10136 for (i=0; i<N; i++) { 10137 PackageParser.Activity a = pkg.receivers.get(i); 10138 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10139 a.info.processName); 10140 mReceivers.addActivity(a, "receiver"); 10141 if (chatty) { 10142 if (r == null) { 10143 r = new StringBuilder(256); 10144 } else { 10145 r.append(' '); 10146 } 10147 r.append(a.info.name); 10148 } 10149 } 10150 if (r != null) { 10151 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10152 } 10153 10154 N = pkg.activities.size(); 10155 r = null; 10156 for (i=0; i<N; i++) { 10157 PackageParser.Activity a = pkg.activities.get(i); 10158 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10159 a.info.processName); 10160 mActivities.addActivity(a, "activity"); 10161 if (chatty) { 10162 if (r == null) { 10163 r = new StringBuilder(256); 10164 } else { 10165 r.append(' '); 10166 } 10167 r.append(a.info.name); 10168 } 10169 } 10170 if (r != null) { 10171 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10172 } 10173 10174 N = pkg.permissionGroups.size(); 10175 r = null; 10176 for (i=0; i<N; i++) { 10177 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10178 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10179 final String curPackageName = cur == null ? null : cur.info.packageName; 10180 // Dont allow ephemeral apps to define new permission groups. 10181 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10182 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10183 + pg.info.packageName 10184 + " ignored: instant apps cannot define new permission groups."); 10185 continue; 10186 } 10187 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10188 if (cur == null || isPackageUpdate) { 10189 mPermissionGroups.put(pg.info.name, pg); 10190 if (chatty) { 10191 if (r == null) { 10192 r = new StringBuilder(256); 10193 } else { 10194 r.append(' '); 10195 } 10196 if (isPackageUpdate) { 10197 r.append("UPD:"); 10198 } 10199 r.append(pg.info.name); 10200 } 10201 } else { 10202 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10203 + pg.info.packageName + " ignored: original from " 10204 + cur.info.packageName); 10205 if (chatty) { 10206 if (r == null) { 10207 r = new StringBuilder(256); 10208 } else { 10209 r.append(' '); 10210 } 10211 r.append("DUP:"); 10212 r.append(pg.info.name); 10213 } 10214 } 10215 } 10216 if (r != null) { 10217 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10218 } 10219 10220 N = pkg.permissions.size(); 10221 r = null; 10222 for (i=0; i<N; i++) { 10223 PackageParser.Permission p = pkg.permissions.get(i); 10224 10225 // Dont allow ephemeral apps to define new permissions. 10226 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10227 Slog.w(TAG, "Permission " + p.info.name + " from package " 10228 + p.info.packageName 10229 + " ignored: instant apps cannot define new permissions."); 10230 continue; 10231 } 10232 10233 // Assume by default that we did not install this permission into the system. 10234 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10235 10236 // Now that permission groups have a special meaning, we ignore permission 10237 // groups for legacy apps to prevent unexpected behavior. In particular, 10238 // permissions for one app being granted to someone just becase they happen 10239 // to be in a group defined by another app (before this had no implications). 10240 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10241 p.group = mPermissionGroups.get(p.info.group); 10242 // Warn for a permission in an unknown group. 10243 if (p.info.group != null && p.group == null) { 10244 Slog.w(TAG, "Permission " + p.info.name + " from package " 10245 + p.info.packageName + " in an unknown group " + p.info.group); 10246 } 10247 } 10248 10249 ArrayMap<String, BasePermission> permissionMap = 10250 p.tree ? mSettings.mPermissionTrees 10251 : mSettings.mPermissions; 10252 BasePermission bp = permissionMap.get(p.info.name); 10253 10254 // Allow system apps to redefine non-system permissions 10255 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10256 final boolean currentOwnerIsSystem = (bp.perm != null 10257 && isSystemApp(bp.perm.owner)); 10258 if (isSystemApp(p.owner)) { 10259 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10260 // It's a built-in permission and no owner, take ownership now 10261 bp.packageSetting = pkgSetting; 10262 bp.perm = p; 10263 bp.uid = pkg.applicationInfo.uid; 10264 bp.sourcePackage = p.info.packageName; 10265 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10266 } else if (!currentOwnerIsSystem) { 10267 String msg = "New decl " + p.owner + " of permission " 10268 + p.info.name + " is system; overriding " + bp.sourcePackage; 10269 reportSettingsProblem(Log.WARN, msg); 10270 bp = null; 10271 } 10272 } 10273 } 10274 10275 if (bp == null) { 10276 bp = new BasePermission(p.info.name, p.info.packageName, 10277 BasePermission.TYPE_NORMAL); 10278 permissionMap.put(p.info.name, bp); 10279 } 10280 10281 if (bp.perm == null) { 10282 if (bp.sourcePackage == null 10283 || bp.sourcePackage.equals(p.info.packageName)) { 10284 BasePermission tree = findPermissionTreeLP(p.info.name); 10285 if (tree == null 10286 || tree.sourcePackage.equals(p.info.packageName)) { 10287 bp.packageSetting = pkgSetting; 10288 bp.perm = p; 10289 bp.uid = pkg.applicationInfo.uid; 10290 bp.sourcePackage = p.info.packageName; 10291 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10292 if (chatty) { 10293 if (r == null) { 10294 r = new StringBuilder(256); 10295 } else { 10296 r.append(' '); 10297 } 10298 r.append(p.info.name); 10299 } 10300 } else { 10301 Slog.w(TAG, "Permission " + p.info.name + " from package " 10302 + p.info.packageName + " ignored: base tree " 10303 + tree.name + " is from package " 10304 + tree.sourcePackage); 10305 } 10306 } else { 10307 Slog.w(TAG, "Permission " + p.info.name + " from package " 10308 + p.info.packageName + " ignored: original from " 10309 + bp.sourcePackage); 10310 } 10311 } else if (chatty) { 10312 if (r == null) { 10313 r = new StringBuilder(256); 10314 } else { 10315 r.append(' '); 10316 } 10317 r.append("DUP:"); 10318 r.append(p.info.name); 10319 } 10320 if (bp.perm == p) { 10321 bp.protectionLevel = p.info.protectionLevel; 10322 } 10323 } 10324 10325 if (r != null) { 10326 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10327 } 10328 10329 N = pkg.instrumentation.size(); 10330 r = null; 10331 for (i=0; i<N; i++) { 10332 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10333 a.info.packageName = pkg.applicationInfo.packageName; 10334 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10335 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10336 a.info.splitNames = pkg.splitNames; 10337 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10338 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10339 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10340 a.info.dataDir = pkg.applicationInfo.dataDir; 10341 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10342 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10343 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10344 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10345 mInstrumentation.put(a.getComponentName(), a); 10346 if (chatty) { 10347 if (r == null) { 10348 r = new StringBuilder(256); 10349 } else { 10350 r.append(' '); 10351 } 10352 r.append(a.info.name); 10353 } 10354 } 10355 if (r != null) { 10356 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10357 } 10358 10359 if (pkg.protectedBroadcasts != null) { 10360 N = pkg.protectedBroadcasts.size(); 10361 for (i=0; i<N; i++) { 10362 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10363 } 10364 } 10365 10366 // Create idmap files for pairs of (packages, overlay packages). 10367 // Note: "android", ie framework-res.apk, is handled by native layers. 10368 if (pkg.mOverlayTarget != null) { 10369 // This is an overlay package. 10370 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 10371 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 10372 mOverlays.put(pkg.mOverlayTarget, 10373 new ArrayMap<String, PackageParser.Package>()); 10374 } 10375 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 10376 map.put(pkg.packageName, pkg); 10377 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 10378 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 10379 createIdmapFailed = true; 10380 } 10381 } 10382 } else if (mOverlays.containsKey(pkg.packageName) && 10383 !pkg.packageName.equals("android")) { 10384 // This is a regular package, with one or more known overlay packages. 10385 createIdmapsForPackageLI(pkg); 10386 } 10387 } 10388 10389 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10390 10391 if (createIdmapFailed) { 10392 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10393 "scanPackageLI failed to createIdmap"); 10394 } 10395 } 10396 10397 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10398 PackageParser.Package update, int[] userIds) { 10399 if (existing.applicationInfo == null || update.applicationInfo == null) { 10400 // This isn't due to an app installation. 10401 return; 10402 } 10403 10404 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10405 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10406 10407 // The codePath hasn't changed, so there's nothing for us to do. 10408 if (Objects.equals(oldCodePath, newCodePath)) { 10409 return; 10410 } 10411 10412 File canonicalNewCodePath; 10413 try { 10414 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10415 } catch (IOException e) { 10416 Slog.w(TAG, "Failed to get canonical path.", e); 10417 return; 10418 } 10419 10420 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10421 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10422 // that the last component of the path (i.e, the name) doesn't need canonicalization 10423 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10424 // but may change in the future. Hopefully this function won't exist at that point. 10425 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10426 oldCodePath.getName()); 10427 10428 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10429 // with "@". 10430 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10431 if (!oldMarkerPrefix.endsWith("@")) { 10432 oldMarkerPrefix += "@"; 10433 } 10434 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10435 if (!newMarkerPrefix.endsWith("@")) { 10436 newMarkerPrefix += "@"; 10437 } 10438 10439 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10440 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10441 for (String updatedPath : updatedPaths) { 10442 String updatedPathName = new File(updatedPath).getName(); 10443 markerSuffixes.add(updatedPathName.replace('/', '@')); 10444 } 10445 10446 for (int userId : userIds) { 10447 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10448 10449 for (String markerSuffix : markerSuffixes) { 10450 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10451 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10452 if (oldForeignUseMark.exists()) { 10453 try { 10454 Os.rename(oldForeignUseMark.getAbsolutePath(), 10455 newForeignUseMark.getAbsolutePath()); 10456 } catch (ErrnoException e) { 10457 Slog.w(TAG, "Failed to rename foreign use marker", e); 10458 oldForeignUseMark.delete(); 10459 } 10460 } 10461 } 10462 } 10463 } 10464 10465 /** 10466 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10467 * is derived purely on the basis of the contents of {@code scanFile} and 10468 * {@code cpuAbiOverride}. 10469 * 10470 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10471 */ 10472 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10473 String cpuAbiOverride, boolean extractLibs, 10474 File appLib32InstallDir) 10475 throws PackageManagerException { 10476 // Give ourselves some initial paths; we'll come back for another 10477 // pass once we've determined ABI below. 10478 setNativeLibraryPaths(pkg, appLib32InstallDir); 10479 10480 // We would never need to extract libs for forward-locked and external packages, 10481 // since the container service will do it for us. We shouldn't attempt to 10482 // extract libs from system app when it was not updated. 10483 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10484 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10485 extractLibs = false; 10486 } 10487 10488 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10489 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10490 10491 NativeLibraryHelper.Handle handle = null; 10492 try { 10493 handle = NativeLibraryHelper.Handle.create(pkg); 10494 // TODO(multiArch): This can be null for apps that didn't go through the 10495 // usual installation process. We can calculate it again, like we 10496 // do during install time. 10497 // 10498 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10499 // unnecessary. 10500 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10501 10502 // Null out the abis so that they can be recalculated. 10503 pkg.applicationInfo.primaryCpuAbi = null; 10504 pkg.applicationInfo.secondaryCpuAbi = null; 10505 if (isMultiArch(pkg.applicationInfo)) { 10506 // Warn if we've set an abiOverride for multi-lib packages.. 10507 // By definition, we need to copy both 32 and 64 bit libraries for 10508 // such packages. 10509 if (pkg.cpuAbiOverride != null 10510 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10511 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10512 } 10513 10514 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10515 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10516 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10517 if (extractLibs) { 10518 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10519 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10520 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10521 useIsaSpecificSubdirs); 10522 } else { 10523 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10524 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10525 } 10526 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10527 } 10528 10529 maybeThrowExceptionForMultiArchCopy( 10530 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10531 10532 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10533 if (extractLibs) { 10534 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10535 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10536 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10537 useIsaSpecificSubdirs); 10538 } else { 10539 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10540 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10541 } 10542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10543 } 10544 10545 maybeThrowExceptionForMultiArchCopy( 10546 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10547 10548 if (abi64 >= 0) { 10549 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10550 } 10551 10552 if (abi32 >= 0) { 10553 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10554 if (abi64 >= 0) { 10555 if (pkg.use32bitAbi) { 10556 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10557 pkg.applicationInfo.primaryCpuAbi = abi; 10558 } else { 10559 pkg.applicationInfo.secondaryCpuAbi = abi; 10560 } 10561 } else { 10562 pkg.applicationInfo.primaryCpuAbi = abi; 10563 } 10564 } 10565 10566 } else { 10567 String[] abiList = (cpuAbiOverride != null) ? 10568 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10569 10570 // Enable gross and lame hacks for apps that are built with old 10571 // SDK tools. We must scan their APKs for renderscript bitcode and 10572 // not launch them if it's present. Don't bother checking on devices 10573 // that don't have 64 bit support. 10574 boolean needsRenderScriptOverride = false; 10575 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10576 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10577 abiList = Build.SUPPORTED_32_BIT_ABIS; 10578 needsRenderScriptOverride = true; 10579 } 10580 10581 final int copyRet; 10582 if (extractLibs) { 10583 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10584 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10585 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10586 } else { 10587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10588 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10589 } 10590 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10591 10592 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10593 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10594 "Error unpackaging native libs for app, errorCode=" + copyRet); 10595 } 10596 10597 if (copyRet >= 0) { 10598 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10599 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10600 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10601 } else if (needsRenderScriptOverride) { 10602 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10603 } 10604 } 10605 } catch (IOException ioe) { 10606 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10607 } finally { 10608 IoUtils.closeQuietly(handle); 10609 } 10610 10611 // Now that we've calculated the ABIs and determined if it's an internal app, 10612 // we will go ahead and populate the nativeLibraryPath. 10613 setNativeLibraryPaths(pkg, appLib32InstallDir); 10614 } 10615 10616 /** 10617 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10618 * i.e, so that all packages can be run inside a single process if required. 10619 * 10620 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10621 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10622 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10623 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10624 * updating a package that belongs to a shared user. 10625 * 10626 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10627 * adds unnecessary complexity. 10628 */ 10629 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10630 PackageParser.Package scannedPackage) { 10631 String requiredInstructionSet = null; 10632 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10633 requiredInstructionSet = VMRuntime.getInstructionSet( 10634 scannedPackage.applicationInfo.primaryCpuAbi); 10635 } 10636 10637 PackageSetting requirer = null; 10638 for (PackageSetting ps : packagesForUser) { 10639 // If packagesForUser contains scannedPackage, we skip it. This will happen 10640 // when scannedPackage is an update of an existing package. Without this check, 10641 // we will never be able to change the ABI of any package belonging to a shared 10642 // user, even if it's compatible with other packages. 10643 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10644 if (ps.primaryCpuAbiString == null) { 10645 continue; 10646 } 10647 10648 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10649 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10650 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10651 // this but there's not much we can do. 10652 String errorMessage = "Instruction set mismatch, " 10653 + ((requirer == null) ? "[caller]" : requirer) 10654 + " requires " + requiredInstructionSet + " whereas " + ps 10655 + " requires " + instructionSet; 10656 Slog.w(TAG, errorMessage); 10657 } 10658 10659 if (requiredInstructionSet == null) { 10660 requiredInstructionSet = instructionSet; 10661 requirer = ps; 10662 } 10663 } 10664 } 10665 10666 if (requiredInstructionSet != null) { 10667 String adjustedAbi; 10668 if (requirer != null) { 10669 // requirer != null implies that either scannedPackage was null or that scannedPackage 10670 // did not require an ABI, in which case we have to adjust scannedPackage to match 10671 // the ABI of the set (which is the same as requirer's ABI) 10672 adjustedAbi = requirer.primaryCpuAbiString; 10673 if (scannedPackage != null) { 10674 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10675 } 10676 } else { 10677 // requirer == null implies that we're updating all ABIs in the set to 10678 // match scannedPackage. 10679 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10680 } 10681 10682 for (PackageSetting ps : packagesForUser) { 10683 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10684 if (ps.primaryCpuAbiString != null) { 10685 continue; 10686 } 10687 10688 ps.primaryCpuAbiString = adjustedAbi; 10689 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10690 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10691 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10692 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10693 + " (requirer=" 10694 + (requirer == null ? "null" : requirer.pkg.packageName) 10695 + ", scannedPackage=" 10696 + (scannedPackage != null ? scannedPackage.packageName : "null") 10697 + ")"); 10698 try { 10699 mInstaller.rmdex(ps.codePathString, 10700 getDexCodeInstructionSet(getPreferredInstructionSet())); 10701 } catch (InstallerException ignored) { 10702 } 10703 } 10704 } 10705 } 10706 } 10707 } 10708 10709 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10710 synchronized (mPackages) { 10711 mResolverReplaced = true; 10712 // Set up information for custom user intent resolution activity. 10713 mResolveActivity.applicationInfo = pkg.applicationInfo; 10714 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10715 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10716 mResolveActivity.processName = pkg.applicationInfo.packageName; 10717 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10718 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10719 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10720 mResolveActivity.theme = 0; 10721 mResolveActivity.exported = true; 10722 mResolveActivity.enabled = true; 10723 mResolveInfo.activityInfo = mResolveActivity; 10724 mResolveInfo.priority = 0; 10725 mResolveInfo.preferredOrder = 0; 10726 mResolveInfo.match = 0; 10727 mResolveComponentName = mCustomResolverComponentName; 10728 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10729 mResolveComponentName); 10730 } 10731 } 10732 10733 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10734 if (installerComponent == null) { 10735 if (DEBUG_EPHEMERAL) { 10736 Slog.d(TAG, "Clear ephemeral installer activity"); 10737 } 10738 mInstantAppInstallerActivity.applicationInfo = null; 10739 return; 10740 } 10741 10742 if (DEBUG_EPHEMERAL) { 10743 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10744 } 10745 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10746 // Set up information for ephemeral installer activity 10747 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10748 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10749 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10750 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10751 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10752 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10753 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10754 mInstantAppInstallerActivity.theme = 0; 10755 mInstantAppInstallerActivity.exported = true; 10756 mInstantAppInstallerActivity.enabled = true; 10757 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10758 mInstantAppInstallerInfo.priority = 0; 10759 mInstantAppInstallerInfo.preferredOrder = 1; 10760 mInstantAppInstallerInfo.isDefault = true; 10761 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10762 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10763 } 10764 10765 private static String calculateBundledApkRoot(final String codePathString) { 10766 final File codePath = new File(codePathString); 10767 final File codeRoot; 10768 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10769 codeRoot = Environment.getRootDirectory(); 10770 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10771 codeRoot = Environment.getOemDirectory(); 10772 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10773 codeRoot = Environment.getVendorDirectory(); 10774 } else { 10775 // Unrecognized code path; take its top real segment as the apk root: 10776 // e.g. /something/app/blah.apk => /something 10777 try { 10778 File f = codePath.getCanonicalFile(); 10779 File parent = f.getParentFile(); // non-null because codePath is a file 10780 File tmp; 10781 while ((tmp = parent.getParentFile()) != null) { 10782 f = parent; 10783 parent = tmp; 10784 } 10785 codeRoot = f; 10786 Slog.w(TAG, "Unrecognized code path " 10787 + codePath + " - using " + codeRoot); 10788 } catch (IOException e) { 10789 // Can't canonicalize the code path -- shenanigans? 10790 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10791 return Environment.getRootDirectory().getPath(); 10792 } 10793 } 10794 return codeRoot.getPath(); 10795 } 10796 10797 /** 10798 * Derive and set the location of native libraries for the given package, 10799 * which varies depending on where and how the package was installed. 10800 */ 10801 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10802 final ApplicationInfo info = pkg.applicationInfo; 10803 final String codePath = pkg.codePath; 10804 final File codeFile = new File(codePath); 10805 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10806 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10807 10808 info.nativeLibraryRootDir = null; 10809 info.nativeLibraryRootRequiresIsa = false; 10810 info.nativeLibraryDir = null; 10811 info.secondaryNativeLibraryDir = null; 10812 10813 if (isApkFile(codeFile)) { 10814 // Monolithic install 10815 if (bundledApp) { 10816 // If "/system/lib64/apkname" exists, assume that is the per-package 10817 // native library directory to use; otherwise use "/system/lib/apkname". 10818 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10819 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10820 getPrimaryInstructionSet(info)); 10821 10822 // This is a bundled system app so choose the path based on the ABI. 10823 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10824 // is just the default path. 10825 final String apkName = deriveCodePathName(codePath); 10826 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10827 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10828 apkName).getAbsolutePath(); 10829 10830 if (info.secondaryCpuAbi != null) { 10831 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10832 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10833 secondaryLibDir, apkName).getAbsolutePath(); 10834 } 10835 } else if (asecApp) { 10836 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10837 .getAbsolutePath(); 10838 } else { 10839 final String apkName = deriveCodePathName(codePath); 10840 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10841 .getAbsolutePath(); 10842 } 10843 10844 info.nativeLibraryRootRequiresIsa = false; 10845 info.nativeLibraryDir = info.nativeLibraryRootDir; 10846 } else { 10847 // Cluster install 10848 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10849 info.nativeLibraryRootRequiresIsa = true; 10850 10851 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10852 getPrimaryInstructionSet(info)).getAbsolutePath(); 10853 10854 if (info.secondaryCpuAbi != null) { 10855 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10856 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10857 } 10858 } 10859 } 10860 10861 /** 10862 * Calculate the abis and roots for a bundled app. These can uniquely 10863 * be determined from the contents of the system partition, i.e whether 10864 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10865 * of this information, and instead assume that the system was built 10866 * sensibly. 10867 */ 10868 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10869 PackageSetting pkgSetting) { 10870 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10871 10872 // If "/system/lib64/apkname" exists, assume that is the per-package 10873 // native library directory to use; otherwise use "/system/lib/apkname". 10874 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10875 setBundledAppAbi(pkg, apkRoot, apkName); 10876 // pkgSetting might be null during rescan following uninstall of updates 10877 // to a bundled app, so accommodate that possibility. The settings in 10878 // that case will be established later from the parsed package. 10879 // 10880 // If the settings aren't null, sync them up with what we've just derived. 10881 // note that apkRoot isn't stored in the package settings. 10882 if (pkgSetting != null) { 10883 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10884 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10885 } 10886 } 10887 10888 /** 10889 * Deduces the ABI of a bundled app and sets the relevant fields on the 10890 * parsed pkg object. 10891 * 10892 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10893 * under which system libraries are installed. 10894 * @param apkName the name of the installed package. 10895 */ 10896 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10897 final File codeFile = new File(pkg.codePath); 10898 10899 final boolean has64BitLibs; 10900 final boolean has32BitLibs; 10901 if (isApkFile(codeFile)) { 10902 // Monolithic install 10903 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10904 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10905 } else { 10906 // Cluster install 10907 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10908 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10909 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10910 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10911 has64BitLibs = (new File(rootDir, isa)).exists(); 10912 } else { 10913 has64BitLibs = false; 10914 } 10915 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10916 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10917 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10918 has32BitLibs = (new File(rootDir, isa)).exists(); 10919 } else { 10920 has32BitLibs = false; 10921 } 10922 } 10923 10924 if (has64BitLibs && !has32BitLibs) { 10925 // The package has 64 bit libs, but not 32 bit libs. Its primary 10926 // ABI should be 64 bit. We can safely assume here that the bundled 10927 // native libraries correspond to the most preferred ABI in the list. 10928 10929 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10930 pkg.applicationInfo.secondaryCpuAbi = null; 10931 } else if (has32BitLibs && !has64BitLibs) { 10932 // The package has 32 bit libs but not 64 bit libs. Its primary 10933 // ABI should be 32 bit. 10934 10935 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10936 pkg.applicationInfo.secondaryCpuAbi = null; 10937 } else if (has32BitLibs && has64BitLibs) { 10938 // The application has both 64 and 32 bit bundled libraries. We check 10939 // here that the app declares multiArch support, and warn if it doesn't. 10940 // 10941 // We will be lenient here and record both ABIs. The primary will be the 10942 // ABI that's higher on the list, i.e, a device that's configured to prefer 10943 // 64 bit apps will see a 64 bit primary ABI, 10944 10945 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10946 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10947 } 10948 10949 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10950 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10951 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10952 } else { 10953 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10954 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10955 } 10956 } else { 10957 pkg.applicationInfo.primaryCpuAbi = null; 10958 pkg.applicationInfo.secondaryCpuAbi = null; 10959 } 10960 } 10961 10962 private void killApplication(String pkgName, int appId, String reason) { 10963 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10964 } 10965 10966 private void killApplication(String pkgName, int appId, int userId, String reason) { 10967 // Request the ActivityManager to kill the process(only for existing packages) 10968 // so that we do not end up in a confused state while the user is still using the older 10969 // version of the application while the new one gets installed. 10970 final long token = Binder.clearCallingIdentity(); 10971 try { 10972 IActivityManager am = ActivityManager.getService(); 10973 if (am != null) { 10974 try { 10975 am.killApplication(pkgName, appId, userId, reason); 10976 } catch (RemoteException e) { 10977 } 10978 } 10979 } finally { 10980 Binder.restoreCallingIdentity(token); 10981 } 10982 } 10983 10984 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10985 // Remove the parent package setting 10986 PackageSetting ps = (PackageSetting) pkg.mExtras; 10987 if (ps != null) { 10988 removePackageLI(ps, chatty); 10989 } 10990 // Remove the child package setting 10991 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10992 for (int i = 0; i < childCount; i++) { 10993 PackageParser.Package childPkg = pkg.childPackages.get(i); 10994 ps = (PackageSetting) childPkg.mExtras; 10995 if (ps != null) { 10996 removePackageLI(ps, chatty); 10997 } 10998 } 10999 } 11000 11001 void removePackageLI(PackageSetting ps, boolean chatty) { 11002 if (DEBUG_INSTALL) { 11003 if (chatty) 11004 Log.d(TAG, "Removing package " + ps.name); 11005 } 11006 11007 // writer 11008 synchronized (mPackages) { 11009 mPackages.remove(ps.name); 11010 final PackageParser.Package pkg = ps.pkg; 11011 if (pkg != null) { 11012 cleanPackageDataStructuresLILPw(pkg, chatty); 11013 } 11014 } 11015 } 11016 11017 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11018 if (DEBUG_INSTALL) { 11019 if (chatty) 11020 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11021 } 11022 11023 // writer 11024 synchronized (mPackages) { 11025 // Remove the parent package 11026 mPackages.remove(pkg.applicationInfo.packageName); 11027 cleanPackageDataStructuresLILPw(pkg, chatty); 11028 11029 // Remove the child packages 11030 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11031 for (int i = 0; i < childCount; i++) { 11032 PackageParser.Package childPkg = pkg.childPackages.get(i); 11033 mPackages.remove(childPkg.applicationInfo.packageName); 11034 cleanPackageDataStructuresLILPw(childPkg, chatty); 11035 } 11036 } 11037 } 11038 11039 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11040 int N = pkg.providers.size(); 11041 StringBuilder r = null; 11042 int i; 11043 for (i=0; i<N; i++) { 11044 PackageParser.Provider p = pkg.providers.get(i); 11045 mProviders.removeProvider(p); 11046 if (p.info.authority == null) { 11047 11048 /* There was another ContentProvider with this authority when 11049 * this app was installed so this authority is null, 11050 * Ignore it as we don't have to unregister the provider. 11051 */ 11052 continue; 11053 } 11054 String names[] = p.info.authority.split(";"); 11055 for (int j = 0; j < names.length; j++) { 11056 if (mProvidersByAuthority.get(names[j]) == p) { 11057 mProvidersByAuthority.remove(names[j]); 11058 if (DEBUG_REMOVE) { 11059 if (chatty) 11060 Log.d(TAG, "Unregistered content provider: " + names[j] 11061 + ", className = " + p.info.name + ", isSyncable = " 11062 + p.info.isSyncable); 11063 } 11064 } 11065 } 11066 if (DEBUG_REMOVE && chatty) { 11067 if (r == null) { 11068 r = new StringBuilder(256); 11069 } else { 11070 r.append(' '); 11071 } 11072 r.append(p.info.name); 11073 } 11074 } 11075 if (r != null) { 11076 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11077 } 11078 11079 N = pkg.services.size(); 11080 r = null; 11081 for (i=0; i<N; i++) { 11082 PackageParser.Service s = pkg.services.get(i); 11083 mServices.removeService(s); 11084 if (chatty) { 11085 if (r == null) { 11086 r = new StringBuilder(256); 11087 } else { 11088 r.append(' '); 11089 } 11090 r.append(s.info.name); 11091 } 11092 } 11093 if (r != null) { 11094 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11095 } 11096 11097 N = pkg.receivers.size(); 11098 r = null; 11099 for (i=0; i<N; i++) { 11100 PackageParser.Activity a = pkg.receivers.get(i); 11101 mReceivers.removeActivity(a, "receiver"); 11102 if (DEBUG_REMOVE && chatty) { 11103 if (r == null) { 11104 r = new StringBuilder(256); 11105 } else { 11106 r.append(' '); 11107 } 11108 r.append(a.info.name); 11109 } 11110 } 11111 if (r != null) { 11112 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11113 } 11114 11115 N = pkg.activities.size(); 11116 r = null; 11117 for (i=0; i<N; i++) { 11118 PackageParser.Activity a = pkg.activities.get(i); 11119 mActivities.removeActivity(a, "activity"); 11120 if (DEBUG_REMOVE && chatty) { 11121 if (r == null) { 11122 r = new StringBuilder(256); 11123 } else { 11124 r.append(' '); 11125 } 11126 r.append(a.info.name); 11127 } 11128 } 11129 if (r != null) { 11130 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11131 } 11132 11133 N = pkg.permissions.size(); 11134 r = null; 11135 for (i=0; i<N; i++) { 11136 PackageParser.Permission p = pkg.permissions.get(i); 11137 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11138 if (bp == null) { 11139 bp = mSettings.mPermissionTrees.get(p.info.name); 11140 } 11141 if (bp != null && bp.perm == p) { 11142 bp.perm = null; 11143 if (DEBUG_REMOVE && chatty) { 11144 if (r == null) { 11145 r = new StringBuilder(256); 11146 } else { 11147 r.append(' '); 11148 } 11149 r.append(p.info.name); 11150 } 11151 } 11152 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11153 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11154 if (appOpPkgs != null) { 11155 appOpPkgs.remove(pkg.packageName); 11156 } 11157 } 11158 } 11159 if (r != null) { 11160 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11161 } 11162 11163 N = pkg.requestedPermissions.size(); 11164 r = null; 11165 for (i=0; i<N; i++) { 11166 String perm = pkg.requestedPermissions.get(i); 11167 BasePermission bp = mSettings.mPermissions.get(perm); 11168 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11169 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11170 if (appOpPkgs != null) { 11171 appOpPkgs.remove(pkg.packageName); 11172 if (appOpPkgs.isEmpty()) { 11173 mAppOpPermissionPackages.remove(perm); 11174 } 11175 } 11176 } 11177 } 11178 if (r != null) { 11179 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11180 } 11181 11182 N = pkg.instrumentation.size(); 11183 r = null; 11184 for (i=0; i<N; i++) { 11185 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11186 mInstrumentation.remove(a.getComponentName()); 11187 if (DEBUG_REMOVE && chatty) { 11188 if (r == null) { 11189 r = new StringBuilder(256); 11190 } else { 11191 r.append(' '); 11192 } 11193 r.append(a.info.name); 11194 } 11195 } 11196 if (r != null) { 11197 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11198 } 11199 11200 r = null; 11201 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11202 // Only system apps can hold shared libraries. 11203 if (pkg.libraryNames != null) { 11204 for (i = 0; i < pkg.libraryNames.size(); i++) { 11205 String name = pkg.libraryNames.get(i); 11206 if (removeSharedLibraryLPw(name, 0)) { 11207 if (DEBUG_REMOVE && chatty) { 11208 if (r == null) { 11209 r = new StringBuilder(256); 11210 } else { 11211 r.append(' '); 11212 } 11213 r.append(name); 11214 } 11215 } 11216 } 11217 } 11218 } 11219 11220 r = null; 11221 11222 // Any package can hold static shared libraries. 11223 if (pkg.staticSharedLibName != null) { 11224 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11225 if (DEBUG_REMOVE && chatty) { 11226 if (r == null) { 11227 r = new StringBuilder(256); 11228 } else { 11229 r.append(' '); 11230 } 11231 r.append(pkg.staticSharedLibName); 11232 } 11233 } 11234 } 11235 11236 if (r != null) { 11237 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11238 } 11239 } 11240 11241 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11242 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11243 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11244 return true; 11245 } 11246 } 11247 return false; 11248 } 11249 11250 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11251 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11252 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11253 11254 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11255 // Update the parent permissions 11256 updatePermissionsLPw(pkg.packageName, pkg, flags); 11257 // Update the child permissions 11258 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11259 for (int i = 0; i < childCount; i++) { 11260 PackageParser.Package childPkg = pkg.childPackages.get(i); 11261 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11262 } 11263 } 11264 11265 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11266 int flags) { 11267 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11268 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11269 } 11270 11271 private void updatePermissionsLPw(String changingPkg, 11272 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11273 // Make sure there are no dangling permission trees. 11274 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11275 while (it.hasNext()) { 11276 final BasePermission bp = it.next(); 11277 if (bp.packageSetting == null) { 11278 // We may not yet have parsed the package, so just see if 11279 // we still know about its settings. 11280 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11281 } 11282 if (bp.packageSetting == null) { 11283 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11284 + " from package " + bp.sourcePackage); 11285 it.remove(); 11286 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11287 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11288 Slog.i(TAG, "Removing old permission tree: " + bp.name 11289 + " from package " + bp.sourcePackage); 11290 flags |= UPDATE_PERMISSIONS_ALL; 11291 it.remove(); 11292 } 11293 } 11294 } 11295 11296 // Make sure all dynamic permissions have been assigned to a package, 11297 // and make sure there are no dangling permissions. 11298 it = mSettings.mPermissions.values().iterator(); 11299 while (it.hasNext()) { 11300 final BasePermission bp = it.next(); 11301 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11302 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11303 + bp.name + " pkg=" + bp.sourcePackage 11304 + " info=" + bp.pendingInfo); 11305 if (bp.packageSetting == null && bp.pendingInfo != null) { 11306 final BasePermission tree = findPermissionTreeLP(bp.name); 11307 if (tree != null && tree.perm != null) { 11308 bp.packageSetting = tree.packageSetting; 11309 bp.perm = new PackageParser.Permission(tree.perm.owner, 11310 new PermissionInfo(bp.pendingInfo)); 11311 bp.perm.info.packageName = tree.perm.info.packageName; 11312 bp.perm.info.name = bp.name; 11313 bp.uid = tree.uid; 11314 } 11315 } 11316 } 11317 if (bp.packageSetting == null) { 11318 // We may not yet have parsed the package, so just see if 11319 // we still know about its settings. 11320 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11321 } 11322 if (bp.packageSetting == null) { 11323 Slog.w(TAG, "Removing dangling permission: " + bp.name 11324 + " from package " + bp.sourcePackage); 11325 it.remove(); 11326 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11327 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11328 Slog.i(TAG, "Removing old permission: " + bp.name 11329 + " from package " + bp.sourcePackage); 11330 flags |= UPDATE_PERMISSIONS_ALL; 11331 it.remove(); 11332 } 11333 } 11334 } 11335 11336 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11337 // Now update the permissions for all packages, in particular 11338 // replace the granted permissions of the system packages. 11339 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11340 for (PackageParser.Package pkg : mPackages.values()) { 11341 if (pkg != pkgInfo) { 11342 // Only replace for packages on requested volume 11343 final String volumeUuid = getVolumeUuidForPackage(pkg); 11344 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11345 && Objects.equals(replaceVolumeUuid, volumeUuid); 11346 grantPermissionsLPw(pkg, replace, changingPkg); 11347 } 11348 } 11349 } 11350 11351 if (pkgInfo != null) { 11352 // Only replace for packages on requested volume 11353 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11354 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11355 && Objects.equals(replaceVolumeUuid, volumeUuid); 11356 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11357 } 11358 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11359 } 11360 11361 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11362 String packageOfInterest) { 11363 // IMPORTANT: There are two types of permissions: install and runtime. 11364 // Install time permissions are granted when the app is installed to 11365 // all device users and users added in the future. Runtime permissions 11366 // are granted at runtime explicitly to specific users. Normal and signature 11367 // protected permissions are install time permissions. Dangerous permissions 11368 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11369 // otherwise they are runtime permissions. This function does not manage 11370 // runtime permissions except for the case an app targeting Lollipop MR1 11371 // being upgraded to target a newer SDK, in which case dangerous permissions 11372 // are transformed from install time to runtime ones. 11373 11374 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11375 if (ps == null) { 11376 return; 11377 } 11378 11379 PermissionsState permissionsState = ps.getPermissionsState(); 11380 PermissionsState origPermissions = permissionsState; 11381 11382 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11383 11384 boolean runtimePermissionsRevoked = false; 11385 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11386 11387 boolean changedInstallPermission = false; 11388 11389 if (replace) { 11390 ps.installPermissionsFixed = false; 11391 if (!ps.isSharedUser()) { 11392 origPermissions = new PermissionsState(permissionsState); 11393 permissionsState.reset(); 11394 } else { 11395 // We need to know only about runtime permission changes since the 11396 // calling code always writes the install permissions state but 11397 // the runtime ones are written only if changed. The only cases of 11398 // changed runtime permissions here are promotion of an install to 11399 // runtime and revocation of a runtime from a shared user. 11400 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11401 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11402 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11403 runtimePermissionsRevoked = true; 11404 } 11405 } 11406 } 11407 11408 permissionsState.setGlobalGids(mGlobalGids); 11409 11410 final int N = pkg.requestedPermissions.size(); 11411 for (int i=0; i<N; i++) { 11412 final String name = pkg.requestedPermissions.get(i); 11413 final BasePermission bp = mSettings.mPermissions.get(name); 11414 11415 if (DEBUG_INSTALL) { 11416 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11417 } 11418 11419 if (bp == null || bp.packageSetting == null) { 11420 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11421 Slog.w(TAG, "Unknown permission " + name 11422 + " in package " + pkg.packageName); 11423 } 11424 continue; 11425 } 11426 11427 11428 // Limit ephemeral apps to ephemeral allowed permissions. 11429 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11430 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11431 + pkg.packageName); 11432 continue; 11433 } 11434 11435 final String perm = bp.name; 11436 boolean allowedSig = false; 11437 int grant = GRANT_DENIED; 11438 11439 // Keep track of app op permissions. 11440 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11441 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11442 if (pkgs == null) { 11443 pkgs = new ArraySet<>(); 11444 mAppOpPermissionPackages.put(bp.name, pkgs); 11445 } 11446 pkgs.add(pkg.packageName); 11447 } 11448 11449 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11450 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11451 >= Build.VERSION_CODES.M; 11452 switch (level) { 11453 case PermissionInfo.PROTECTION_NORMAL: { 11454 // For all apps normal permissions are install time ones. 11455 grant = GRANT_INSTALL; 11456 } break; 11457 11458 case PermissionInfo.PROTECTION_DANGEROUS: { 11459 // If a permission review is required for legacy apps we represent 11460 // their permissions as always granted runtime ones since we need 11461 // to keep the review required permission flag per user while an 11462 // install permission's state is shared across all users. 11463 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11464 // For legacy apps dangerous permissions are install time ones. 11465 grant = GRANT_INSTALL; 11466 } else if (origPermissions.hasInstallPermission(bp.name)) { 11467 // For legacy apps that became modern, install becomes runtime. 11468 grant = GRANT_UPGRADE; 11469 } else if (mPromoteSystemApps 11470 && isSystemApp(ps) 11471 && mExistingSystemPackages.contains(ps.name)) { 11472 // For legacy system apps, install becomes runtime. 11473 // We cannot check hasInstallPermission() for system apps since those 11474 // permissions were granted implicitly and not persisted pre-M. 11475 grant = GRANT_UPGRADE; 11476 } else { 11477 // For modern apps keep runtime permissions unchanged. 11478 grant = GRANT_RUNTIME; 11479 } 11480 } break; 11481 11482 case PermissionInfo.PROTECTION_SIGNATURE: { 11483 // For all apps signature permissions are install time ones. 11484 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11485 if (allowedSig) { 11486 grant = GRANT_INSTALL; 11487 } 11488 } break; 11489 } 11490 11491 if (DEBUG_INSTALL) { 11492 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11493 } 11494 11495 if (grant != GRANT_DENIED) { 11496 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11497 // If this is an existing, non-system package, then 11498 // we can't add any new permissions to it. 11499 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11500 // Except... if this is a permission that was added 11501 // to the platform (note: need to only do this when 11502 // updating the platform). 11503 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11504 grant = GRANT_DENIED; 11505 } 11506 } 11507 } 11508 11509 switch (grant) { 11510 case GRANT_INSTALL: { 11511 // Revoke this as runtime permission to handle the case of 11512 // a runtime permission being downgraded to an install one. 11513 // Also in permission review mode we keep dangerous permissions 11514 // for legacy apps 11515 for (int userId : UserManagerService.getInstance().getUserIds()) { 11516 if (origPermissions.getRuntimePermissionState( 11517 bp.name, userId) != null) { 11518 // Revoke the runtime permission and clear the flags. 11519 origPermissions.revokeRuntimePermission(bp, userId); 11520 origPermissions.updatePermissionFlags(bp, userId, 11521 PackageManager.MASK_PERMISSION_FLAGS, 0); 11522 // If we revoked a permission permission, we have to write. 11523 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11524 changedRuntimePermissionUserIds, userId); 11525 } 11526 } 11527 // Grant an install permission. 11528 if (permissionsState.grantInstallPermission(bp) != 11529 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11530 changedInstallPermission = true; 11531 } 11532 } break; 11533 11534 case GRANT_RUNTIME: { 11535 // Grant previously granted runtime permissions. 11536 for (int userId : UserManagerService.getInstance().getUserIds()) { 11537 PermissionState permissionState = origPermissions 11538 .getRuntimePermissionState(bp.name, userId); 11539 int flags = permissionState != null 11540 ? permissionState.getFlags() : 0; 11541 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11542 // Don't propagate the permission in a permission review mode if 11543 // the former was revoked, i.e. marked to not propagate on upgrade. 11544 // Note that in a permission review mode install permissions are 11545 // represented as constantly granted runtime ones since we need to 11546 // keep a per user state associated with the permission. Also the 11547 // revoke on upgrade flag is no longer applicable and is reset. 11548 final boolean revokeOnUpgrade = (flags & PackageManager 11549 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11550 if (revokeOnUpgrade) { 11551 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11552 // Since we changed the flags, we have to write. 11553 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11554 changedRuntimePermissionUserIds, userId); 11555 } 11556 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11557 if (permissionsState.grantRuntimePermission(bp, userId) == 11558 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11559 // If we cannot put the permission as it was, 11560 // we have to write. 11561 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11562 changedRuntimePermissionUserIds, userId); 11563 } 11564 } 11565 11566 // If the app supports runtime permissions no need for a review. 11567 if (mPermissionReviewRequired 11568 && appSupportsRuntimePermissions 11569 && (flags & PackageManager 11570 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11571 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11572 // Since we changed the flags, we have to write. 11573 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11574 changedRuntimePermissionUserIds, userId); 11575 } 11576 } else if (mPermissionReviewRequired 11577 && !appSupportsRuntimePermissions) { 11578 // For legacy apps that need a permission review, every new 11579 // runtime permission is granted but it is pending a review. 11580 // We also need to review only platform defined runtime 11581 // permissions as these are the only ones the platform knows 11582 // how to disable the API to simulate revocation as legacy 11583 // apps don't expect to run with revoked permissions. 11584 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11585 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11586 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11587 // We changed the flags, hence have to write. 11588 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11589 changedRuntimePermissionUserIds, userId); 11590 } 11591 } 11592 if (permissionsState.grantRuntimePermission(bp, userId) 11593 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11594 // We changed the permission, hence have to write. 11595 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11596 changedRuntimePermissionUserIds, userId); 11597 } 11598 } 11599 // Propagate the permission flags. 11600 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11601 } 11602 } break; 11603 11604 case GRANT_UPGRADE: { 11605 // Grant runtime permissions for a previously held install permission. 11606 PermissionState permissionState = origPermissions 11607 .getInstallPermissionState(bp.name); 11608 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11609 11610 if (origPermissions.revokeInstallPermission(bp) 11611 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11612 // We will be transferring the permission flags, so clear them. 11613 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11614 PackageManager.MASK_PERMISSION_FLAGS, 0); 11615 changedInstallPermission = true; 11616 } 11617 11618 // If the permission is not to be promoted to runtime we ignore it and 11619 // also its other flags as they are not applicable to install permissions. 11620 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11621 for (int userId : currentUserIds) { 11622 if (permissionsState.grantRuntimePermission(bp, userId) != 11623 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11624 // Transfer the permission flags. 11625 permissionsState.updatePermissionFlags(bp, userId, 11626 flags, flags); 11627 // If we granted the permission, we have to write. 11628 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11629 changedRuntimePermissionUserIds, userId); 11630 } 11631 } 11632 } 11633 } break; 11634 11635 default: { 11636 if (packageOfInterest == null 11637 || packageOfInterest.equals(pkg.packageName)) { 11638 Slog.w(TAG, "Not granting permission " + perm 11639 + " to package " + pkg.packageName 11640 + " because it was previously installed without"); 11641 } 11642 } break; 11643 } 11644 } else { 11645 if (permissionsState.revokeInstallPermission(bp) != 11646 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11647 // Also drop the permission flags. 11648 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11649 PackageManager.MASK_PERMISSION_FLAGS, 0); 11650 changedInstallPermission = true; 11651 Slog.i(TAG, "Un-granting permission " + perm 11652 + " from package " + pkg.packageName 11653 + " (protectionLevel=" + bp.protectionLevel 11654 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11655 + ")"); 11656 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11657 // Don't print warning for app op permissions, since it is fine for them 11658 // not to be granted, there is a UI for the user to decide. 11659 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11660 Slog.w(TAG, "Not granting permission " + perm 11661 + " to package " + pkg.packageName 11662 + " (protectionLevel=" + bp.protectionLevel 11663 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11664 + ")"); 11665 } 11666 } 11667 } 11668 } 11669 11670 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11671 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11672 // This is the first that we have heard about this package, so the 11673 // permissions we have now selected are fixed until explicitly 11674 // changed. 11675 ps.installPermissionsFixed = true; 11676 } 11677 11678 // Persist the runtime permissions state for users with changes. If permissions 11679 // were revoked because no app in the shared user declares them we have to 11680 // write synchronously to avoid losing runtime permissions state. 11681 for (int userId : changedRuntimePermissionUserIds) { 11682 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11683 } 11684 } 11685 11686 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11687 boolean allowed = false; 11688 final int NP = PackageParser.NEW_PERMISSIONS.length; 11689 for (int ip=0; ip<NP; ip++) { 11690 final PackageParser.NewPermissionInfo npi 11691 = PackageParser.NEW_PERMISSIONS[ip]; 11692 if (npi.name.equals(perm) 11693 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11694 allowed = true; 11695 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11696 + pkg.packageName); 11697 break; 11698 } 11699 } 11700 return allowed; 11701 } 11702 11703 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11704 BasePermission bp, PermissionsState origPermissions) { 11705 boolean privilegedPermission = (bp.protectionLevel 11706 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11707 boolean privappPermissionsDisable = 11708 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11709 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11710 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11711 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11712 && !platformPackage && platformPermission) { 11713 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11714 .getPrivAppPermissions(pkg.packageName); 11715 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11716 if (!whitelisted) { 11717 Slog.w(TAG, "Privileged permission " + perm + " for package " 11718 + pkg.packageName + " - not in privapp-permissions whitelist"); 11719 if (!mSystemReady) { 11720 if (mPrivappPermissionsViolations == null) { 11721 mPrivappPermissionsViolations = new ArraySet<>(); 11722 } 11723 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11724 } 11725 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11726 return false; 11727 } 11728 } 11729 } 11730 boolean allowed = (compareSignatures( 11731 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11732 == PackageManager.SIGNATURE_MATCH) 11733 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11734 == PackageManager.SIGNATURE_MATCH); 11735 if (!allowed && privilegedPermission) { 11736 if (isSystemApp(pkg)) { 11737 // For updated system applications, a system permission 11738 // is granted only if it had been defined by the original application. 11739 if (pkg.isUpdatedSystemApp()) { 11740 final PackageSetting sysPs = mSettings 11741 .getDisabledSystemPkgLPr(pkg.packageName); 11742 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11743 // If the original was granted this permission, we take 11744 // that grant decision as read and propagate it to the 11745 // update. 11746 if (sysPs.isPrivileged()) { 11747 allowed = true; 11748 } 11749 } else { 11750 // The system apk may have been updated with an older 11751 // version of the one on the data partition, but which 11752 // granted a new system permission that it didn't have 11753 // before. In this case we do want to allow the app to 11754 // now get the new permission if the ancestral apk is 11755 // privileged to get it. 11756 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11757 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11758 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11759 allowed = true; 11760 break; 11761 } 11762 } 11763 } 11764 // Also if a privileged parent package on the system image or any of 11765 // its children requested a privileged permission, the updated child 11766 // packages can also get the permission. 11767 if (pkg.parentPackage != null) { 11768 final PackageSetting disabledSysParentPs = mSettings 11769 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11770 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11771 && disabledSysParentPs.isPrivileged()) { 11772 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11773 allowed = true; 11774 } else if (disabledSysParentPs.pkg.childPackages != null) { 11775 final int count = disabledSysParentPs.pkg.childPackages.size(); 11776 for (int i = 0; i < count; i++) { 11777 PackageParser.Package disabledSysChildPkg = 11778 disabledSysParentPs.pkg.childPackages.get(i); 11779 if (isPackageRequestingPermission(disabledSysChildPkg, 11780 perm)) { 11781 allowed = true; 11782 break; 11783 } 11784 } 11785 } 11786 } 11787 } 11788 } 11789 } else { 11790 allowed = isPrivilegedApp(pkg); 11791 } 11792 } 11793 } 11794 if (!allowed) { 11795 if (!allowed && (bp.protectionLevel 11796 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11797 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11798 // If this was a previously normal/dangerous permission that got moved 11799 // to a system permission as part of the runtime permission redesign, then 11800 // we still want to blindly grant it to old apps. 11801 allowed = true; 11802 } 11803 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11804 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11805 // If this permission is to be granted to the system installer and 11806 // this app is an installer, then it gets the permission. 11807 allowed = true; 11808 } 11809 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11810 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11811 // If this permission is to be granted to the system verifier and 11812 // this app is a verifier, then it gets the permission. 11813 allowed = true; 11814 } 11815 if (!allowed && (bp.protectionLevel 11816 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11817 && isSystemApp(pkg)) { 11818 // Any pre-installed system app is allowed to get this permission. 11819 allowed = true; 11820 } 11821 if (!allowed && (bp.protectionLevel 11822 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11823 // For development permissions, a development permission 11824 // is granted only if it was already granted. 11825 allowed = origPermissions.hasInstallPermission(perm); 11826 } 11827 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11828 && pkg.packageName.equals(mSetupWizardPackage)) { 11829 // If this permission is to be granted to the system setup wizard and 11830 // this app is a setup wizard, then it gets the permission. 11831 allowed = true; 11832 } 11833 } 11834 return allowed; 11835 } 11836 11837 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11838 final int permCount = pkg.requestedPermissions.size(); 11839 for (int j = 0; j < permCount; j++) { 11840 String requestedPermission = pkg.requestedPermissions.get(j); 11841 if (permission.equals(requestedPermission)) { 11842 return true; 11843 } 11844 } 11845 return false; 11846 } 11847 11848 final class ActivityIntentResolver 11849 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11850 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11851 boolean defaultOnly, int userId) { 11852 if (!sUserManager.exists(userId)) return null; 11853 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11854 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11855 } 11856 11857 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11858 int userId) { 11859 if (!sUserManager.exists(userId)) return null; 11860 mFlags = flags; 11861 return super.queryIntent(intent, resolvedType, 11862 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11863 userId); 11864 } 11865 11866 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11867 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11868 if (!sUserManager.exists(userId)) return null; 11869 if (packageActivities == null) { 11870 return null; 11871 } 11872 mFlags = flags; 11873 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11874 final int N = packageActivities.size(); 11875 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11876 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11877 11878 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11879 for (int i = 0; i < N; ++i) { 11880 intentFilters = packageActivities.get(i).intents; 11881 if (intentFilters != null && intentFilters.size() > 0) { 11882 PackageParser.ActivityIntentInfo[] array = 11883 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11884 intentFilters.toArray(array); 11885 listCut.add(array); 11886 } 11887 } 11888 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11889 } 11890 11891 /** 11892 * Finds a privileged activity that matches the specified activity names. 11893 */ 11894 private PackageParser.Activity findMatchingActivity( 11895 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11896 for (PackageParser.Activity sysActivity : activityList) { 11897 if (sysActivity.info.name.equals(activityInfo.name)) { 11898 return sysActivity; 11899 } 11900 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11901 return sysActivity; 11902 } 11903 if (sysActivity.info.targetActivity != null) { 11904 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11905 return sysActivity; 11906 } 11907 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11908 return sysActivity; 11909 } 11910 } 11911 } 11912 return null; 11913 } 11914 11915 public class IterGenerator<E> { 11916 public Iterator<E> generate(ActivityIntentInfo info) { 11917 return null; 11918 } 11919 } 11920 11921 public class ActionIterGenerator extends IterGenerator<String> { 11922 @Override 11923 public Iterator<String> generate(ActivityIntentInfo info) { 11924 return info.actionsIterator(); 11925 } 11926 } 11927 11928 public class CategoriesIterGenerator extends IterGenerator<String> { 11929 @Override 11930 public Iterator<String> generate(ActivityIntentInfo info) { 11931 return info.categoriesIterator(); 11932 } 11933 } 11934 11935 public class SchemesIterGenerator extends IterGenerator<String> { 11936 @Override 11937 public Iterator<String> generate(ActivityIntentInfo info) { 11938 return info.schemesIterator(); 11939 } 11940 } 11941 11942 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11943 @Override 11944 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11945 return info.authoritiesIterator(); 11946 } 11947 } 11948 11949 /** 11950 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11951 * MODIFIED. Do not pass in a list that should not be changed. 11952 */ 11953 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11954 IterGenerator<T> generator, Iterator<T> searchIterator) { 11955 // loop through the set of actions; every one must be found in the intent filter 11956 while (searchIterator.hasNext()) { 11957 // we must have at least one filter in the list to consider a match 11958 if (intentList.size() == 0) { 11959 break; 11960 } 11961 11962 final T searchAction = searchIterator.next(); 11963 11964 // loop through the set of intent filters 11965 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11966 while (intentIter.hasNext()) { 11967 final ActivityIntentInfo intentInfo = intentIter.next(); 11968 boolean selectionFound = false; 11969 11970 // loop through the intent filter's selection criteria; at least one 11971 // of them must match the searched criteria 11972 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11973 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11974 final T intentSelection = intentSelectionIter.next(); 11975 if (intentSelection != null && intentSelection.equals(searchAction)) { 11976 selectionFound = true; 11977 break; 11978 } 11979 } 11980 11981 // the selection criteria wasn't found in this filter's set; this filter 11982 // is not a potential match 11983 if (!selectionFound) { 11984 intentIter.remove(); 11985 } 11986 } 11987 } 11988 } 11989 11990 private boolean isProtectedAction(ActivityIntentInfo filter) { 11991 final Iterator<String> actionsIter = filter.actionsIterator(); 11992 while (actionsIter != null && actionsIter.hasNext()) { 11993 final String filterAction = actionsIter.next(); 11994 if (PROTECTED_ACTIONS.contains(filterAction)) { 11995 return true; 11996 } 11997 } 11998 return false; 11999 } 12000 12001 /** 12002 * Adjusts the priority of the given intent filter according to policy. 12003 * <p> 12004 * <ul> 12005 * <li>The priority for non privileged applications is capped to '0'</li> 12006 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12007 * <li>The priority for unbundled updates to privileged applications is capped to the 12008 * priority defined on the system partition</li> 12009 * </ul> 12010 * <p> 12011 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12012 * allowed to obtain any priority on any action. 12013 */ 12014 private void adjustPriority( 12015 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12016 // nothing to do; priority is fine as-is 12017 if (intent.getPriority() <= 0) { 12018 return; 12019 } 12020 12021 final ActivityInfo activityInfo = intent.activity.info; 12022 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12023 12024 final boolean privilegedApp = 12025 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12026 if (!privilegedApp) { 12027 // non-privileged applications can never define a priority >0 12028 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12029 + " package: " + applicationInfo.packageName 12030 + " activity: " + intent.activity.className 12031 + " origPrio: " + intent.getPriority()); 12032 intent.setPriority(0); 12033 return; 12034 } 12035 12036 if (systemActivities == null) { 12037 // the system package is not disabled; we're parsing the system partition 12038 if (isProtectedAction(intent)) { 12039 if (mDeferProtectedFilters) { 12040 // We can't deal with these just yet. No component should ever obtain a 12041 // >0 priority for a protected actions, with ONE exception -- the setup 12042 // wizard. The setup wizard, however, cannot be known until we're able to 12043 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12044 // until all intent filters have been processed. Chicken, meet egg. 12045 // Let the filter temporarily have a high priority and rectify the 12046 // priorities after all system packages have been scanned. 12047 mProtectedFilters.add(intent); 12048 if (DEBUG_FILTERS) { 12049 Slog.i(TAG, "Protected action; save for later;" 12050 + " package: " + applicationInfo.packageName 12051 + " activity: " + intent.activity.className 12052 + " origPrio: " + intent.getPriority()); 12053 } 12054 return; 12055 } else { 12056 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12057 Slog.i(TAG, "No setup wizard;" 12058 + " All protected intents capped to priority 0"); 12059 } 12060 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12061 if (DEBUG_FILTERS) { 12062 Slog.i(TAG, "Found setup wizard;" 12063 + " allow priority " + intent.getPriority() + ";" 12064 + " package: " + intent.activity.info.packageName 12065 + " activity: " + intent.activity.className 12066 + " priority: " + intent.getPriority()); 12067 } 12068 // setup wizard gets whatever it wants 12069 return; 12070 } 12071 Slog.w(TAG, "Protected action; cap priority to 0;" 12072 + " package: " + intent.activity.info.packageName 12073 + " activity: " + intent.activity.className 12074 + " origPrio: " + intent.getPriority()); 12075 intent.setPriority(0); 12076 return; 12077 } 12078 } 12079 // privileged apps on the system image get whatever priority they request 12080 return; 12081 } 12082 12083 // privileged app unbundled update ... try to find the same activity 12084 final PackageParser.Activity foundActivity = 12085 findMatchingActivity(systemActivities, activityInfo); 12086 if (foundActivity == null) { 12087 // this is a new activity; it cannot obtain >0 priority 12088 if (DEBUG_FILTERS) { 12089 Slog.i(TAG, "New activity; cap priority to 0;" 12090 + " package: " + applicationInfo.packageName 12091 + " activity: " + intent.activity.className 12092 + " origPrio: " + intent.getPriority()); 12093 } 12094 intent.setPriority(0); 12095 return; 12096 } 12097 12098 // found activity, now check for filter equivalence 12099 12100 // a shallow copy is enough; we modify the list, not its contents 12101 final List<ActivityIntentInfo> intentListCopy = 12102 new ArrayList<>(foundActivity.intents); 12103 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12104 12105 // find matching action subsets 12106 final Iterator<String> actionsIterator = intent.actionsIterator(); 12107 if (actionsIterator != null) { 12108 getIntentListSubset( 12109 intentListCopy, new ActionIterGenerator(), actionsIterator); 12110 if (intentListCopy.size() == 0) { 12111 // no more intents to match; we're not equivalent 12112 if (DEBUG_FILTERS) { 12113 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12114 + " package: " + applicationInfo.packageName 12115 + " activity: " + intent.activity.className 12116 + " origPrio: " + intent.getPriority()); 12117 } 12118 intent.setPriority(0); 12119 return; 12120 } 12121 } 12122 12123 // find matching category subsets 12124 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12125 if (categoriesIterator != null) { 12126 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12127 categoriesIterator); 12128 if (intentListCopy.size() == 0) { 12129 // no more intents to match; we're not equivalent 12130 if (DEBUG_FILTERS) { 12131 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12132 + " package: " + applicationInfo.packageName 12133 + " activity: " + intent.activity.className 12134 + " origPrio: " + intent.getPriority()); 12135 } 12136 intent.setPriority(0); 12137 return; 12138 } 12139 } 12140 12141 // find matching schemes subsets 12142 final Iterator<String> schemesIterator = intent.schemesIterator(); 12143 if (schemesIterator != null) { 12144 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12145 schemesIterator); 12146 if (intentListCopy.size() == 0) { 12147 // no more intents to match; we're not equivalent 12148 if (DEBUG_FILTERS) { 12149 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12150 + " package: " + applicationInfo.packageName 12151 + " activity: " + intent.activity.className 12152 + " origPrio: " + intent.getPriority()); 12153 } 12154 intent.setPriority(0); 12155 return; 12156 } 12157 } 12158 12159 // find matching authorities subsets 12160 final Iterator<IntentFilter.AuthorityEntry> 12161 authoritiesIterator = intent.authoritiesIterator(); 12162 if (authoritiesIterator != null) { 12163 getIntentListSubset(intentListCopy, 12164 new AuthoritiesIterGenerator(), 12165 authoritiesIterator); 12166 if (intentListCopy.size() == 0) { 12167 // no more intents to match; we're not equivalent 12168 if (DEBUG_FILTERS) { 12169 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12170 + " package: " + applicationInfo.packageName 12171 + " activity: " + intent.activity.className 12172 + " origPrio: " + intent.getPriority()); 12173 } 12174 intent.setPriority(0); 12175 return; 12176 } 12177 } 12178 12179 // we found matching filter(s); app gets the max priority of all intents 12180 int cappedPriority = 0; 12181 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12182 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12183 } 12184 if (intent.getPriority() > cappedPriority) { 12185 if (DEBUG_FILTERS) { 12186 Slog.i(TAG, "Found matching filter(s);" 12187 + " cap priority to " + cappedPriority + ";" 12188 + " package: " + applicationInfo.packageName 12189 + " activity: " + intent.activity.className 12190 + " origPrio: " + intent.getPriority()); 12191 } 12192 intent.setPriority(cappedPriority); 12193 return; 12194 } 12195 // all this for nothing; the requested priority was <= what was on the system 12196 } 12197 12198 public final void addActivity(PackageParser.Activity a, String type) { 12199 mActivities.put(a.getComponentName(), a); 12200 if (DEBUG_SHOW_INFO) 12201 Log.v( 12202 TAG, " " + type + " " + 12203 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12204 if (DEBUG_SHOW_INFO) 12205 Log.v(TAG, " Class=" + a.info.name); 12206 final int NI = a.intents.size(); 12207 for (int j=0; j<NI; j++) { 12208 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12209 if ("activity".equals(type)) { 12210 final PackageSetting ps = 12211 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12212 final List<PackageParser.Activity> systemActivities = 12213 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12214 adjustPriority(systemActivities, intent); 12215 } 12216 if (DEBUG_SHOW_INFO) { 12217 Log.v(TAG, " IntentFilter:"); 12218 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12219 } 12220 if (!intent.debugCheck()) { 12221 Log.w(TAG, "==> For Activity " + a.info.name); 12222 } 12223 addFilter(intent); 12224 } 12225 } 12226 12227 public final void removeActivity(PackageParser.Activity a, String type) { 12228 mActivities.remove(a.getComponentName()); 12229 if (DEBUG_SHOW_INFO) { 12230 Log.v(TAG, " " + type + " " 12231 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12232 : a.info.name) + ":"); 12233 Log.v(TAG, " Class=" + a.info.name); 12234 } 12235 final int NI = a.intents.size(); 12236 for (int j=0; j<NI; j++) { 12237 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12238 if (DEBUG_SHOW_INFO) { 12239 Log.v(TAG, " IntentFilter:"); 12240 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12241 } 12242 removeFilter(intent); 12243 } 12244 } 12245 12246 @Override 12247 protected boolean allowFilterResult( 12248 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12249 ActivityInfo filterAi = filter.activity.info; 12250 for (int i=dest.size()-1; i>=0; i--) { 12251 ActivityInfo destAi = dest.get(i).activityInfo; 12252 if (destAi.name == filterAi.name 12253 && destAi.packageName == filterAi.packageName) { 12254 return false; 12255 } 12256 } 12257 return true; 12258 } 12259 12260 @Override 12261 protected ActivityIntentInfo[] newArray(int size) { 12262 return new ActivityIntentInfo[size]; 12263 } 12264 12265 @Override 12266 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12267 if (!sUserManager.exists(userId)) return true; 12268 PackageParser.Package p = filter.activity.owner; 12269 if (p != null) { 12270 PackageSetting ps = (PackageSetting)p.mExtras; 12271 if (ps != null) { 12272 // System apps are never considered stopped for purposes of 12273 // filtering, because there may be no way for the user to 12274 // actually re-launch them. 12275 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12276 && ps.getStopped(userId); 12277 } 12278 } 12279 return false; 12280 } 12281 12282 @Override 12283 protected boolean isPackageForFilter(String packageName, 12284 PackageParser.ActivityIntentInfo info) { 12285 return packageName.equals(info.activity.owner.packageName); 12286 } 12287 12288 @Override 12289 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12290 int match, int userId) { 12291 if (!sUserManager.exists(userId)) return null; 12292 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12293 return null; 12294 } 12295 final PackageParser.Activity activity = info.activity; 12296 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12297 if (ps == null) { 12298 return null; 12299 } 12300 final PackageUserState userState = ps.readUserState(userId); 12301 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12302 userState, userId); 12303 if (ai == null) { 12304 return null; 12305 } 12306 final boolean matchVisibleToInstantApp = 12307 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12308 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12309 // throw out filters that aren't visible to ephemeral apps 12310 if (matchVisibleToInstantApp 12311 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12312 return null; 12313 } 12314 // throw out ephemeral filters if we're not explicitly requesting them 12315 if (!isInstantApp && userState.instantApp) { 12316 return null; 12317 } 12318 final ResolveInfo res = new ResolveInfo(); 12319 res.activityInfo = ai; 12320 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12321 res.filter = info; 12322 } 12323 if (info != null) { 12324 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12325 } 12326 res.priority = info.getPriority(); 12327 res.preferredOrder = activity.owner.mPreferredOrder; 12328 //System.out.println("Result: " + res.activityInfo.className + 12329 // " = " + res.priority); 12330 res.match = match; 12331 res.isDefault = info.hasDefault; 12332 res.labelRes = info.labelRes; 12333 res.nonLocalizedLabel = info.nonLocalizedLabel; 12334 if (userNeedsBadging(userId)) { 12335 res.noResourceId = true; 12336 } else { 12337 res.icon = info.icon; 12338 } 12339 res.iconResourceId = info.icon; 12340 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12341 return res; 12342 } 12343 12344 @Override 12345 protected void sortResults(List<ResolveInfo> results) { 12346 Collections.sort(results, mResolvePrioritySorter); 12347 } 12348 12349 @Override 12350 protected void dumpFilter(PrintWriter out, String prefix, 12351 PackageParser.ActivityIntentInfo filter) { 12352 out.print(prefix); out.print( 12353 Integer.toHexString(System.identityHashCode(filter.activity))); 12354 out.print(' '); 12355 filter.activity.printComponentShortName(out); 12356 out.print(" filter "); 12357 out.println(Integer.toHexString(System.identityHashCode(filter))); 12358 } 12359 12360 @Override 12361 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12362 return filter.activity; 12363 } 12364 12365 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12366 PackageParser.Activity activity = (PackageParser.Activity)label; 12367 out.print(prefix); out.print( 12368 Integer.toHexString(System.identityHashCode(activity))); 12369 out.print(' '); 12370 activity.printComponentShortName(out); 12371 if (count > 1) { 12372 out.print(" ("); out.print(count); out.print(" filters)"); 12373 } 12374 out.println(); 12375 } 12376 12377 // Keys are String (activity class name), values are Activity. 12378 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12379 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12380 private int mFlags; 12381 } 12382 12383 private final class ServiceIntentResolver 12384 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12385 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12386 boolean defaultOnly, int userId) { 12387 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12388 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12389 } 12390 12391 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12392 int userId) { 12393 if (!sUserManager.exists(userId)) return null; 12394 mFlags = flags; 12395 return super.queryIntent(intent, resolvedType, 12396 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12397 userId); 12398 } 12399 12400 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12401 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12402 if (!sUserManager.exists(userId)) return null; 12403 if (packageServices == null) { 12404 return null; 12405 } 12406 mFlags = flags; 12407 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12408 final int N = packageServices.size(); 12409 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12410 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12411 12412 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12413 for (int i = 0; i < N; ++i) { 12414 intentFilters = packageServices.get(i).intents; 12415 if (intentFilters != null && intentFilters.size() > 0) { 12416 PackageParser.ServiceIntentInfo[] array = 12417 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12418 intentFilters.toArray(array); 12419 listCut.add(array); 12420 } 12421 } 12422 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12423 } 12424 12425 public final void addService(PackageParser.Service s) { 12426 mServices.put(s.getComponentName(), s); 12427 if (DEBUG_SHOW_INFO) { 12428 Log.v(TAG, " " 12429 + (s.info.nonLocalizedLabel != null 12430 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12431 Log.v(TAG, " Class=" + s.info.name); 12432 } 12433 final int NI = s.intents.size(); 12434 int j; 12435 for (j=0; j<NI; j++) { 12436 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12437 if (DEBUG_SHOW_INFO) { 12438 Log.v(TAG, " IntentFilter:"); 12439 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12440 } 12441 if (!intent.debugCheck()) { 12442 Log.w(TAG, "==> For Service " + s.info.name); 12443 } 12444 addFilter(intent); 12445 } 12446 } 12447 12448 public final void removeService(PackageParser.Service s) { 12449 mServices.remove(s.getComponentName()); 12450 if (DEBUG_SHOW_INFO) { 12451 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12452 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12453 Log.v(TAG, " Class=" + s.info.name); 12454 } 12455 final int NI = s.intents.size(); 12456 int j; 12457 for (j=0; j<NI; j++) { 12458 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12459 if (DEBUG_SHOW_INFO) { 12460 Log.v(TAG, " IntentFilter:"); 12461 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12462 } 12463 removeFilter(intent); 12464 } 12465 } 12466 12467 @Override 12468 protected boolean allowFilterResult( 12469 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12470 ServiceInfo filterSi = filter.service.info; 12471 for (int i=dest.size()-1; i>=0; i--) { 12472 ServiceInfo destAi = dest.get(i).serviceInfo; 12473 if (destAi.name == filterSi.name 12474 && destAi.packageName == filterSi.packageName) { 12475 return false; 12476 } 12477 } 12478 return true; 12479 } 12480 12481 @Override 12482 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12483 return new PackageParser.ServiceIntentInfo[size]; 12484 } 12485 12486 @Override 12487 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12488 if (!sUserManager.exists(userId)) return true; 12489 PackageParser.Package p = filter.service.owner; 12490 if (p != null) { 12491 PackageSetting ps = (PackageSetting)p.mExtras; 12492 if (ps != null) { 12493 // System apps are never considered stopped for purposes of 12494 // filtering, because there may be no way for the user to 12495 // actually re-launch them. 12496 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12497 && ps.getStopped(userId); 12498 } 12499 } 12500 return false; 12501 } 12502 12503 @Override 12504 protected boolean isPackageForFilter(String packageName, 12505 PackageParser.ServiceIntentInfo info) { 12506 return packageName.equals(info.service.owner.packageName); 12507 } 12508 12509 @Override 12510 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12511 int match, int userId) { 12512 if (!sUserManager.exists(userId)) return null; 12513 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12514 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12515 return null; 12516 } 12517 final PackageParser.Service service = info.service; 12518 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12519 if (ps == null) { 12520 return null; 12521 } 12522 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12523 ps.readUserState(userId), userId); 12524 if (si == null) { 12525 return null; 12526 } 12527 final ResolveInfo res = new ResolveInfo(); 12528 res.serviceInfo = si; 12529 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12530 res.filter = filter; 12531 } 12532 res.priority = info.getPriority(); 12533 res.preferredOrder = service.owner.mPreferredOrder; 12534 res.match = match; 12535 res.isDefault = info.hasDefault; 12536 res.labelRes = info.labelRes; 12537 res.nonLocalizedLabel = info.nonLocalizedLabel; 12538 res.icon = info.icon; 12539 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12540 return res; 12541 } 12542 12543 @Override 12544 protected void sortResults(List<ResolveInfo> results) { 12545 Collections.sort(results, mResolvePrioritySorter); 12546 } 12547 12548 @Override 12549 protected void dumpFilter(PrintWriter out, String prefix, 12550 PackageParser.ServiceIntentInfo filter) { 12551 out.print(prefix); out.print( 12552 Integer.toHexString(System.identityHashCode(filter.service))); 12553 out.print(' '); 12554 filter.service.printComponentShortName(out); 12555 out.print(" filter "); 12556 out.println(Integer.toHexString(System.identityHashCode(filter))); 12557 } 12558 12559 @Override 12560 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12561 return filter.service; 12562 } 12563 12564 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12565 PackageParser.Service service = (PackageParser.Service)label; 12566 out.print(prefix); out.print( 12567 Integer.toHexString(System.identityHashCode(service))); 12568 out.print(' '); 12569 service.printComponentShortName(out); 12570 if (count > 1) { 12571 out.print(" ("); out.print(count); out.print(" filters)"); 12572 } 12573 out.println(); 12574 } 12575 12576// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12577// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12578// final List<ResolveInfo> retList = Lists.newArrayList(); 12579// while (i.hasNext()) { 12580// final ResolveInfo resolveInfo = (ResolveInfo) i; 12581// if (isEnabledLP(resolveInfo.serviceInfo)) { 12582// retList.add(resolveInfo); 12583// } 12584// } 12585// return retList; 12586// } 12587 12588 // Keys are String (activity class name), values are Activity. 12589 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12590 = new ArrayMap<ComponentName, PackageParser.Service>(); 12591 private int mFlags; 12592 } 12593 12594 private final class ProviderIntentResolver 12595 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12596 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12597 boolean defaultOnly, int userId) { 12598 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12599 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12600 } 12601 12602 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12603 int userId) { 12604 if (!sUserManager.exists(userId)) 12605 return null; 12606 mFlags = flags; 12607 return super.queryIntent(intent, resolvedType, 12608 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12609 userId); 12610 } 12611 12612 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12613 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12614 if (!sUserManager.exists(userId)) 12615 return null; 12616 if (packageProviders == null) { 12617 return null; 12618 } 12619 mFlags = flags; 12620 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12621 final int N = packageProviders.size(); 12622 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12623 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12624 12625 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12626 for (int i = 0; i < N; ++i) { 12627 intentFilters = packageProviders.get(i).intents; 12628 if (intentFilters != null && intentFilters.size() > 0) { 12629 PackageParser.ProviderIntentInfo[] array = 12630 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12631 intentFilters.toArray(array); 12632 listCut.add(array); 12633 } 12634 } 12635 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12636 } 12637 12638 public final void addProvider(PackageParser.Provider p) { 12639 if (mProviders.containsKey(p.getComponentName())) { 12640 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12641 return; 12642 } 12643 12644 mProviders.put(p.getComponentName(), p); 12645 if (DEBUG_SHOW_INFO) { 12646 Log.v(TAG, " " 12647 + (p.info.nonLocalizedLabel != null 12648 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12649 Log.v(TAG, " Class=" + p.info.name); 12650 } 12651 final int NI = p.intents.size(); 12652 int j; 12653 for (j = 0; j < NI; j++) { 12654 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12655 if (DEBUG_SHOW_INFO) { 12656 Log.v(TAG, " IntentFilter:"); 12657 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12658 } 12659 if (!intent.debugCheck()) { 12660 Log.w(TAG, "==> For Provider " + p.info.name); 12661 } 12662 addFilter(intent); 12663 } 12664 } 12665 12666 public final void removeProvider(PackageParser.Provider p) { 12667 mProviders.remove(p.getComponentName()); 12668 if (DEBUG_SHOW_INFO) { 12669 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12670 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12671 Log.v(TAG, " Class=" + p.info.name); 12672 } 12673 final int NI = p.intents.size(); 12674 int j; 12675 for (j = 0; j < NI; j++) { 12676 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12677 if (DEBUG_SHOW_INFO) { 12678 Log.v(TAG, " IntentFilter:"); 12679 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12680 } 12681 removeFilter(intent); 12682 } 12683 } 12684 12685 @Override 12686 protected boolean allowFilterResult( 12687 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12688 ProviderInfo filterPi = filter.provider.info; 12689 for (int i = dest.size() - 1; i >= 0; i--) { 12690 ProviderInfo destPi = dest.get(i).providerInfo; 12691 if (destPi.name == filterPi.name 12692 && destPi.packageName == filterPi.packageName) { 12693 return false; 12694 } 12695 } 12696 return true; 12697 } 12698 12699 @Override 12700 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12701 return new PackageParser.ProviderIntentInfo[size]; 12702 } 12703 12704 @Override 12705 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12706 if (!sUserManager.exists(userId)) 12707 return true; 12708 PackageParser.Package p = filter.provider.owner; 12709 if (p != null) { 12710 PackageSetting ps = (PackageSetting) p.mExtras; 12711 if (ps != null) { 12712 // System apps are never considered stopped for purposes of 12713 // filtering, because there may be no way for the user to 12714 // actually re-launch them. 12715 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12716 && ps.getStopped(userId); 12717 } 12718 } 12719 return false; 12720 } 12721 12722 @Override 12723 protected boolean isPackageForFilter(String packageName, 12724 PackageParser.ProviderIntentInfo info) { 12725 return packageName.equals(info.provider.owner.packageName); 12726 } 12727 12728 @Override 12729 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12730 int match, int userId) { 12731 if (!sUserManager.exists(userId)) 12732 return null; 12733 final PackageParser.ProviderIntentInfo info = filter; 12734 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12735 return null; 12736 } 12737 final PackageParser.Provider provider = info.provider; 12738 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12739 if (ps == null) { 12740 return null; 12741 } 12742 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12743 ps.readUserState(userId), userId); 12744 if (pi == null) { 12745 return null; 12746 } 12747 final ResolveInfo res = new ResolveInfo(); 12748 res.providerInfo = pi; 12749 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12750 res.filter = filter; 12751 } 12752 res.priority = info.getPriority(); 12753 res.preferredOrder = provider.owner.mPreferredOrder; 12754 res.match = match; 12755 res.isDefault = info.hasDefault; 12756 res.labelRes = info.labelRes; 12757 res.nonLocalizedLabel = info.nonLocalizedLabel; 12758 res.icon = info.icon; 12759 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12760 return res; 12761 } 12762 12763 @Override 12764 protected void sortResults(List<ResolveInfo> results) { 12765 Collections.sort(results, mResolvePrioritySorter); 12766 } 12767 12768 @Override 12769 protected void dumpFilter(PrintWriter out, String prefix, 12770 PackageParser.ProviderIntentInfo filter) { 12771 out.print(prefix); 12772 out.print( 12773 Integer.toHexString(System.identityHashCode(filter.provider))); 12774 out.print(' '); 12775 filter.provider.printComponentShortName(out); 12776 out.print(" filter "); 12777 out.println(Integer.toHexString(System.identityHashCode(filter))); 12778 } 12779 12780 @Override 12781 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12782 return filter.provider; 12783 } 12784 12785 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12786 PackageParser.Provider provider = (PackageParser.Provider)label; 12787 out.print(prefix); out.print( 12788 Integer.toHexString(System.identityHashCode(provider))); 12789 out.print(' '); 12790 provider.printComponentShortName(out); 12791 if (count > 1) { 12792 out.print(" ("); out.print(count); out.print(" filters)"); 12793 } 12794 out.println(); 12795 } 12796 12797 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12798 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12799 private int mFlags; 12800 } 12801 12802 static final class EphemeralIntentResolver 12803 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12804 /** 12805 * The result that has the highest defined order. Ordering applies on a 12806 * per-package basis. Mapping is from package name to Pair of order and 12807 * EphemeralResolveInfo. 12808 * <p> 12809 * NOTE: This is implemented as a field variable for convenience and efficiency. 12810 * By having a field variable, we're able to track filter ordering as soon as 12811 * a non-zero order is defined. Otherwise, multiple loops across the result set 12812 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12813 * this needs to be contained entirely within {@link #filterResults()}. 12814 */ 12815 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12816 12817 @Override 12818 protected AuxiliaryResolveInfo[] newArray(int size) { 12819 return new AuxiliaryResolveInfo[size]; 12820 } 12821 12822 @Override 12823 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12824 return true; 12825 } 12826 12827 @Override 12828 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12829 int userId) { 12830 if (!sUserManager.exists(userId)) { 12831 return null; 12832 } 12833 final String packageName = responseObj.resolveInfo.getPackageName(); 12834 final Integer order = responseObj.getOrder(); 12835 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12836 mOrderResult.get(packageName); 12837 // ordering is enabled and this item's order isn't high enough 12838 if (lastOrderResult != null && lastOrderResult.first >= order) { 12839 return null; 12840 } 12841 final EphemeralResolveInfo res = responseObj.resolveInfo; 12842 if (order > 0) { 12843 // non-zero order, enable ordering 12844 mOrderResult.put(packageName, new Pair<>(order, res)); 12845 } 12846 return responseObj; 12847 } 12848 12849 @Override 12850 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12851 // only do work if ordering is enabled [most of the time it won't be] 12852 if (mOrderResult.size() == 0) { 12853 return; 12854 } 12855 int resultSize = results.size(); 12856 for (int i = 0; i < resultSize; i++) { 12857 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12858 final String packageName = info.getPackageName(); 12859 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12860 if (savedInfo == null) { 12861 // package doesn't having ordering 12862 continue; 12863 } 12864 if (savedInfo.second == info) { 12865 // circled back to the highest ordered item; remove from order list 12866 mOrderResult.remove(savedInfo); 12867 if (mOrderResult.size() == 0) { 12868 // no more ordered items 12869 break; 12870 } 12871 continue; 12872 } 12873 // item has a worse order, remove it from the result list 12874 results.remove(i); 12875 resultSize--; 12876 i--; 12877 } 12878 } 12879 } 12880 12881 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12882 new Comparator<ResolveInfo>() { 12883 public int compare(ResolveInfo r1, ResolveInfo r2) { 12884 int v1 = r1.priority; 12885 int v2 = r2.priority; 12886 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12887 if (v1 != v2) { 12888 return (v1 > v2) ? -1 : 1; 12889 } 12890 v1 = r1.preferredOrder; 12891 v2 = r2.preferredOrder; 12892 if (v1 != v2) { 12893 return (v1 > v2) ? -1 : 1; 12894 } 12895 if (r1.isDefault != r2.isDefault) { 12896 return r1.isDefault ? -1 : 1; 12897 } 12898 v1 = r1.match; 12899 v2 = r2.match; 12900 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12901 if (v1 != v2) { 12902 return (v1 > v2) ? -1 : 1; 12903 } 12904 if (r1.system != r2.system) { 12905 return r1.system ? -1 : 1; 12906 } 12907 if (r1.activityInfo != null) { 12908 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12909 } 12910 if (r1.serviceInfo != null) { 12911 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12912 } 12913 if (r1.providerInfo != null) { 12914 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12915 } 12916 return 0; 12917 } 12918 }; 12919 12920 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12921 new Comparator<ProviderInfo>() { 12922 public int compare(ProviderInfo p1, ProviderInfo p2) { 12923 final int v1 = p1.initOrder; 12924 final int v2 = p2.initOrder; 12925 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12926 } 12927 }; 12928 12929 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12930 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12931 final int[] userIds) { 12932 mHandler.post(new Runnable() { 12933 @Override 12934 public void run() { 12935 try { 12936 final IActivityManager am = ActivityManager.getService(); 12937 if (am == null) return; 12938 final int[] resolvedUserIds; 12939 if (userIds == null) { 12940 resolvedUserIds = am.getRunningUserIds(); 12941 } else { 12942 resolvedUserIds = userIds; 12943 } 12944 for (int id : resolvedUserIds) { 12945 final Intent intent = new Intent(action, 12946 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12947 if (extras != null) { 12948 intent.putExtras(extras); 12949 } 12950 if (targetPkg != null) { 12951 intent.setPackage(targetPkg); 12952 } 12953 // Modify the UID when posting to other users 12954 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12955 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12956 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12957 intent.putExtra(Intent.EXTRA_UID, uid); 12958 } 12959 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12960 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12961 if (DEBUG_BROADCASTS) { 12962 RuntimeException here = new RuntimeException("here"); 12963 here.fillInStackTrace(); 12964 Slog.d(TAG, "Sending to user " + id + ": " 12965 + intent.toShortString(false, true, false, false) 12966 + " " + intent.getExtras(), here); 12967 } 12968 am.broadcastIntent(null, intent, null, finishedReceiver, 12969 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12970 null, finishedReceiver != null, false, id); 12971 } 12972 } catch (RemoteException ex) { 12973 } 12974 } 12975 }); 12976 } 12977 12978 /** 12979 * Check if the external storage media is available. This is true if there 12980 * is a mounted external storage medium or if the external storage is 12981 * emulated. 12982 */ 12983 private boolean isExternalMediaAvailable() { 12984 return mMediaMounted || Environment.isExternalStorageEmulated(); 12985 } 12986 12987 @Override 12988 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12989 // writer 12990 synchronized (mPackages) { 12991 if (!isExternalMediaAvailable()) { 12992 // If the external storage is no longer mounted at this point, 12993 // the caller may not have been able to delete all of this 12994 // packages files and can not delete any more. Bail. 12995 return null; 12996 } 12997 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12998 if (lastPackage != null) { 12999 pkgs.remove(lastPackage); 13000 } 13001 if (pkgs.size() > 0) { 13002 return pkgs.get(0); 13003 } 13004 } 13005 return null; 13006 } 13007 13008 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13009 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13010 userId, andCode ? 1 : 0, packageName); 13011 if (mSystemReady) { 13012 msg.sendToTarget(); 13013 } else { 13014 if (mPostSystemReadyMessages == null) { 13015 mPostSystemReadyMessages = new ArrayList<>(); 13016 } 13017 mPostSystemReadyMessages.add(msg); 13018 } 13019 } 13020 13021 void startCleaningPackages() { 13022 // reader 13023 if (!isExternalMediaAvailable()) { 13024 return; 13025 } 13026 synchronized (mPackages) { 13027 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13028 return; 13029 } 13030 } 13031 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13032 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13033 IActivityManager am = ActivityManager.getService(); 13034 if (am != null) { 13035 try { 13036 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 13037 UserHandle.USER_SYSTEM); 13038 } catch (RemoteException e) { 13039 } 13040 } 13041 } 13042 13043 @Override 13044 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13045 int installFlags, String installerPackageName, int userId) { 13046 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13047 13048 final int callingUid = Binder.getCallingUid(); 13049 enforceCrossUserPermission(callingUid, userId, 13050 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13051 13052 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13053 try { 13054 if (observer != null) { 13055 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13056 } 13057 } catch (RemoteException re) { 13058 } 13059 return; 13060 } 13061 13062 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13063 installFlags |= PackageManager.INSTALL_FROM_ADB; 13064 13065 } else { 13066 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13067 // about installerPackageName. 13068 13069 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13070 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13071 } 13072 13073 UserHandle user; 13074 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13075 user = UserHandle.ALL; 13076 } else { 13077 user = new UserHandle(userId); 13078 } 13079 13080 // Only system components can circumvent runtime permissions when installing. 13081 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13082 && mContext.checkCallingOrSelfPermission(Manifest.permission 13083 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13084 throw new SecurityException("You need the " 13085 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13086 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13087 } 13088 13089 final File originFile = new File(originPath); 13090 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13091 13092 final Message msg = mHandler.obtainMessage(INIT_COPY); 13093 final VerificationInfo verificationInfo = new VerificationInfo( 13094 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13095 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13096 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13097 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13098 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13099 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13100 msg.obj = params; 13101 13102 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13103 System.identityHashCode(msg.obj)); 13104 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13105 System.identityHashCode(msg.obj)); 13106 13107 mHandler.sendMessage(msg); 13108 } 13109 13110 13111 /** 13112 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13113 * it is acting on behalf on an enterprise or the user). 13114 * 13115 * Note that the ordering of the conditionals in this method is important. The checks we perform 13116 * are as follows, in this order: 13117 * 13118 * 1) If the install is being performed by a system app, we can trust the app to have set the 13119 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13120 * what it is. 13121 * 2) If the install is being performed by a device or profile owner app, the install reason 13122 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13123 * set the install reason correctly. If the app targets an older SDK version where install 13124 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13125 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13126 * 3) In all other cases, the install is being performed by a regular app that is neither part 13127 * of the system nor a device or profile owner. We have no reason to believe that this app is 13128 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13129 * set to enterprise policy and if so, change it to unknown instead. 13130 */ 13131 private int fixUpInstallReason(String installerPackageName, int installerUid, 13132 int installReason) { 13133 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13134 == PERMISSION_GRANTED) { 13135 // If the install is being performed by a system app, we trust that app to have set the 13136 // install reason correctly. 13137 return installReason; 13138 } 13139 13140 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13141 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13142 if (dpm != null) { 13143 ComponentName owner = null; 13144 try { 13145 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13146 if (owner == null) { 13147 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13148 } 13149 } catch (RemoteException e) { 13150 } 13151 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13152 // If the install is being performed by a device or profile owner, the install 13153 // reason should be enterprise policy. 13154 return PackageManager.INSTALL_REASON_POLICY; 13155 } 13156 } 13157 13158 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13159 // If the install is being performed by a regular app (i.e. neither system app nor 13160 // device or profile owner), we have no reason to believe that the app is acting on 13161 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13162 // change it to unknown instead. 13163 return PackageManager.INSTALL_REASON_UNKNOWN; 13164 } 13165 13166 // If the install is being performed by a regular app and the install reason was set to any 13167 // value but enterprise policy, leave the install reason unchanged. 13168 return installReason; 13169 } 13170 13171 void installStage(String packageName, File stagedDir, String stagedCid, 13172 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13173 String installerPackageName, int installerUid, UserHandle user, 13174 Certificate[][] certificates) { 13175 if (DEBUG_EPHEMERAL) { 13176 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13177 Slog.d(TAG, "Ephemeral install of " + packageName); 13178 } 13179 } 13180 final VerificationInfo verificationInfo = new VerificationInfo( 13181 sessionParams.originatingUri, sessionParams.referrerUri, 13182 sessionParams.originatingUid, installerUid); 13183 13184 final OriginInfo origin; 13185 if (stagedDir != null) { 13186 origin = OriginInfo.fromStagedFile(stagedDir); 13187 } else { 13188 origin = OriginInfo.fromStagedContainer(stagedCid); 13189 } 13190 13191 final Message msg = mHandler.obtainMessage(INIT_COPY); 13192 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13193 sessionParams.installReason); 13194 final InstallParams params = new InstallParams(origin, null, observer, 13195 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13196 verificationInfo, user, sessionParams.abiOverride, 13197 sessionParams.grantedRuntimePermissions, certificates, installReason); 13198 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13199 msg.obj = params; 13200 13201 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13202 System.identityHashCode(msg.obj)); 13203 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13204 System.identityHashCode(msg.obj)); 13205 13206 mHandler.sendMessage(msg); 13207 } 13208 13209 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13210 int userId) { 13211 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13212 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13213 } 13214 13215 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13216 int appId, int... userIds) { 13217 if (ArrayUtils.isEmpty(userIds)) { 13218 return; 13219 } 13220 Bundle extras = new Bundle(1); 13221 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13222 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13223 13224 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13225 packageName, extras, 0, null, null, userIds); 13226 if (isSystem) { 13227 mHandler.post(() -> { 13228 for (int userId : userIds) { 13229 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13230 } 13231 } 13232 ); 13233 } 13234 } 13235 13236 /** 13237 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13238 * automatically without needing an explicit launch. 13239 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13240 */ 13241 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13242 // If user is not running, the app didn't miss any broadcast 13243 if (!mUserManagerInternal.isUserRunning(userId)) { 13244 return; 13245 } 13246 final IActivityManager am = ActivityManager.getService(); 13247 try { 13248 // Deliver LOCKED_BOOT_COMPLETED first 13249 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13250 .setPackage(packageName); 13251 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13252 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13253 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13254 13255 // Deliver BOOT_COMPLETED only if user is unlocked 13256 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13257 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13258 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13259 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13260 } 13261 } catch (RemoteException e) { 13262 throw e.rethrowFromSystemServer(); 13263 } 13264 } 13265 13266 @Override 13267 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13268 int userId) { 13269 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13270 PackageSetting pkgSetting; 13271 final int uid = Binder.getCallingUid(); 13272 enforceCrossUserPermission(uid, userId, 13273 true /* requireFullPermission */, true /* checkShell */, 13274 "setApplicationHiddenSetting for user " + userId); 13275 13276 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13277 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13278 return false; 13279 } 13280 13281 long callingId = Binder.clearCallingIdentity(); 13282 try { 13283 boolean sendAdded = false; 13284 boolean sendRemoved = false; 13285 // writer 13286 synchronized (mPackages) { 13287 pkgSetting = mSettings.mPackages.get(packageName); 13288 if (pkgSetting == null) { 13289 return false; 13290 } 13291 // Do not allow "android" is being disabled 13292 if ("android".equals(packageName)) { 13293 Slog.w(TAG, "Cannot hide package: android"); 13294 return false; 13295 } 13296 // Cannot hide static shared libs as they are considered 13297 // a part of the using app (emulating static linking). Also 13298 // static libs are installed always on internal storage. 13299 PackageParser.Package pkg = mPackages.get(packageName); 13300 if (pkg != null && pkg.staticSharedLibName != null) { 13301 Slog.w(TAG, "Cannot hide package: " + packageName 13302 + " providing static shared library: " 13303 + pkg.staticSharedLibName); 13304 return false; 13305 } 13306 // Only allow protected packages to hide themselves. 13307 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13308 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13309 Slog.w(TAG, "Not hiding protected package: " + packageName); 13310 return false; 13311 } 13312 13313 if (pkgSetting.getHidden(userId) != hidden) { 13314 pkgSetting.setHidden(hidden, userId); 13315 mSettings.writePackageRestrictionsLPr(userId); 13316 if (hidden) { 13317 sendRemoved = true; 13318 } else { 13319 sendAdded = true; 13320 } 13321 } 13322 } 13323 if (sendAdded) { 13324 sendPackageAddedForUser(packageName, pkgSetting, userId); 13325 return true; 13326 } 13327 if (sendRemoved) { 13328 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13329 "hiding pkg"); 13330 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13331 return true; 13332 } 13333 } finally { 13334 Binder.restoreCallingIdentity(callingId); 13335 } 13336 return false; 13337 } 13338 13339 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13340 int userId) { 13341 final PackageRemovedInfo info = new PackageRemovedInfo(); 13342 info.removedPackage = packageName; 13343 info.removedUsers = new int[] {userId}; 13344 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13345 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13346 } 13347 13348 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13349 if (pkgList.length > 0) { 13350 Bundle extras = new Bundle(1); 13351 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13352 13353 sendPackageBroadcast( 13354 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13355 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13356 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13357 new int[] {userId}); 13358 } 13359 } 13360 13361 /** 13362 * Returns true if application is not found or there was an error. Otherwise it returns 13363 * the hidden state of the package for the given user. 13364 */ 13365 @Override 13366 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13368 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13369 true /* requireFullPermission */, false /* checkShell */, 13370 "getApplicationHidden for user " + userId); 13371 PackageSetting pkgSetting; 13372 long callingId = Binder.clearCallingIdentity(); 13373 try { 13374 // writer 13375 synchronized (mPackages) { 13376 pkgSetting = mSettings.mPackages.get(packageName); 13377 if (pkgSetting == null) { 13378 return true; 13379 } 13380 return pkgSetting.getHidden(userId); 13381 } 13382 } finally { 13383 Binder.restoreCallingIdentity(callingId); 13384 } 13385 } 13386 13387 /** 13388 * @hide 13389 */ 13390 @Override 13391 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13392 int installReason) { 13393 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13394 null); 13395 PackageSetting pkgSetting; 13396 final int uid = Binder.getCallingUid(); 13397 enforceCrossUserPermission(uid, userId, 13398 true /* requireFullPermission */, true /* checkShell */, 13399 "installExistingPackage for user " + userId); 13400 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13401 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13402 } 13403 13404 long callingId = Binder.clearCallingIdentity(); 13405 try { 13406 boolean installed = false; 13407 final boolean instantApp = 13408 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13409 final boolean fullApp = 13410 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13411 13412 // writer 13413 synchronized (mPackages) { 13414 pkgSetting = mSettings.mPackages.get(packageName); 13415 if (pkgSetting == null) { 13416 return PackageManager.INSTALL_FAILED_INVALID_URI; 13417 } 13418 if (!pkgSetting.getInstalled(userId)) { 13419 pkgSetting.setInstalled(true, userId); 13420 pkgSetting.setHidden(false, userId); 13421 pkgSetting.setInstallReason(installReason, userId); 13422 mSettings.writePackageRestrictionsLPr(userId); 13423 mSettings.writeKernelMappingLPr(pkgSetting); 13424 installed = true; 13425 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13426 // upgrade app from instant to full; we don't allow app downgrade 13427 installed = true; 13428 } 13429 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13430 } 13431 13432 if (installed) { 13433 if (pkgSetting.pkg != null) { 13434 synchronized (mInstallLock) { 13435 // We don't need to freeze for a brand new install 13436 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13437 } 13438 } 13439 sendPackageAddedForUser(packageName, pkgSetting, userId); 13440 synchronized (mPackages) { 13441 updateSequenceNumberLP(packageName, new int[]{ userId }); 13442 } 13443 } 13444 } finally { 13445 Binder.restoreCallingIdentity(callingId); 13446 } 13447 13448 return PackageManager.INSTALL_SUCCEEDED; 13449 } 13450 13451 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13452 boolean instantApp, boolean fullApp) { 13453 // no state specified; do nothing 13454 if (!instantApp && !fullApp) { 13455 return; 13456 } 13457 if (userId != UserHandle.USER_ALL) { 13458 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13459 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13460 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13461 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13462 } 13463 } else { 13464 for (int currentUserId : sUserManager.getUserIds()) { 13465 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13466 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13467 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13468 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13469 } 13470 } 13471 } 13472 } 13473 13474 boolean isUserRestricted(int userId, String restrictionKey) { 13475 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13476 if (restrictions.getBoolean(restrictionKey, false)) { 13477 Log.w(TAG, "User is restricted: " + restrictionKey); 13478 return true; 13479 } 13480 return false; 13481 } 13482 13483 @Override 13484 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13485 int userId) { 13486 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13487 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13488 true /* requireFullPermission */, true /* checkShell */, 13489 "setPackagesSuspended for user " + userId); 13490 13491 if (ArrayUtils.isEmpty(packageNames)) { 13492 return packageNames; 13493 } 13494 13495 // List of package names for whom the suspended state has changed. 13496 List<String> changedPackages = new ArrayList<>(packageNames.length); 13497 // List of package names for whom the suspended state is not set as requested in this 13498 // method. 13499 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13500 long callingId = Binder.clearCallingIdentity(); 13501 try { 13502 for (int i = 0; i < packageNames.length; i++) { 13503 String packageName = packageNames[i]; 13504 boolean changed = false; 13505 final int appId; 13506 synchronized (mPackages) { 13507 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13508 if (pkgSetting == null) { 13509 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13510 + "\". Skipping suspending/un-suspending."); 13511 unactionedPackages.add(packageName); 13512 continue; 13513 } 13514 appId = pkgSetting.appId; 13515 if (pkgSetting.getSuspended(userId) != suspended) { 13516 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13517 unactionedPackages.add(packageName); 13518 continue; 13519 } 13520 pkgSetting.setSuspended(suspended, userId); 13521 mSettings.writePackageRestrictionsLPr(userId); 13522 changed = true; 13523 changedPackages.add(packageName); 13524 } 13525 } 13526 13527 if (changed && suspended) { 13528 killApplication(packageName, UserHandle.getUid(userId, appId), 13529 "suspending package"); 13530 } 13531 } 13532 } finally { 13533 Binder.restoreCallingIdentity(callingId); 13534 } 13535 13536 if (!changedPackages.isEmpty()) { 13537 sendPackagesSuspendedForUser(changedPackages.toArray( 13538 new String[changedPackages.size()]), userId, suspended); 13539 } 13540 13541 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13542 } 13543 13544 @Override 13545 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13546 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13547 true /* requireFullPermission */, false /* checkShell */, 13548 "isPackageSuspendedForUser for user " + userId); 13549 synchronized (mPackages) { 13550 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13551 if (pkgSetting == null) { 13552 throw new IllegalArgumentException("Unknown target package: " + packageName); 13553 } 13554 return pkgSetting.getSuspended(userId); 13555 } 13556 } 13557 13558 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13559 if (isPackageDeviceAdmin(packageName, userId)) { 13560 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13561 + "\": has an active device admin"); 13562 return false; 13563 } 13564 13565 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13566 if (packageName.equals(activeLauncherPackageName)) { 13567 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13568 + "\": contains the active launcher"); 13569 return false; 13570 } 13571 13572 if (packageName.equals(mRequiredInstallerPackage)) { 13573 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13574 + "\": required for package installation"); 13575 return false; 13576 } 13577 13578 if (packageName.equals(mRequiredUninstallerPackage)) { 13579 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13580 + "\": required for package uninstallation"); 13581 return false; 13582 } 13583 13584 if (packageName.equals(mRequiredVerifierPackage)) { 13585 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13586 + "\": required for package verification"); 13587 return false; 13588 } 13589 13590 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13591 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13592 + "\": is the default dialer"); 13593 return false; 13594 } 13595 13596 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13597 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13598 + "\": protected package"); 13599 return false; 13600 } 13601 13602 // Cannot suspend static shared libs as they are considered 13603 // a part of the using app (emulating static linking). Also 13604 // static libs are installed always on internal storage. 13605 PackageParser.Package pkg = mPackages.get(packageName); 13606 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13607 Slog.w(TAG, "Cannot suspend package: " + packageName 13608 + " providing static shared library: " 13609 + pkg.staticSharedLibName); 13610 return false; 13611 } 13612 13613 return true; 13614 } 13615 13616 private String getActiveLauncherPackageName(int userId) { 13617 Intent intent = new Intent(Intent.ACTION_MAIN); 13618 intent.addCategory(Intent.CATEGORY_HOME); 13619 ResolveInfo resolveInfo = resolveIntent( 13620 intent, 13621 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13622 PackageManager.MATCH_DEFAULT_ONLY, 13623 userId); 13624 13625 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13626 } 13627 13628 private String getDefaultDialerPackageName(int userId) { 13629 synchronized (mPackages) { 13630 return mSettings.getDefaultDialerPackageNameLPw(userId); 13631 } 13632 } 13633 13634 @Override 13635 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13636 mContext.enforceCallingOrSelfPermission( 13637 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13638 "Only package verification agents can verify applications"); 13639 13640 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13641 final PackageVerificationResponse response = new PackageVerificationResponse( 13642 verificationCode, Binder.getCallingUid()); 13643 msg.arg1 = id; 13644 msg.obj = response; 13645 mHandler.sendMessage(msg); 13646 } 13647 13648 @Override 13649 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13650 long millisecondsToDelay) { 13651 mContext.enforceCallingOrSelfPermission( 13652 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13653 "Only package verification agents can extend verification timeouts"); 13654 13655 final PackageVerificationState state = mPendingVerification.get(id); 13656 final PackageVerificationResponse response = new PackageVerificationResponse( 13657 verificationCodeAtTimeout, Binder.getCallingUid()); 13658 13659 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13660 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13661 } 13662 if (millisecondsToDelay < 0) { 13663 millisecondsToDelay = 0; 13664 } 13665 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13666 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13667 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13668 } 13669 13670 if ((state != null) && !state.timeoutExtended()) { 13671 state.extendTimeout(); 13672 13673 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13674 msg.arg1 = id; 13675 msg.obj = response; 13676 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13677 } 13678 } 13679 13680 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13681 int verificationCode, UserHandle user) { 13682 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13683 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13684 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13685 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13686 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13687 13688 mContext.sendBroadcastAsUser(intent, user, 13689 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13690 } 13691 13692 private ComponentName matchComponentForVerifier(String packageName, 13693 List<ResolveInfo> receivers) { 13694 ActivityInfo targetReceiver = null; 13695 13696 final int NR = receivers.size(); 13697 for (int i = 0; i < NR; i++) { 13698 final ResolveInfo info = receivers.get(i); 13699 if (info.activityInfo == null) { 13700 continue; 13701 } 13702 13703 if (packageName.equals(info.activityInfo.packageName)) { 13704 targetReceiver = info.activityInfo; 13705 break; 13706 } 13707 } 13708 13709 if (targetReceiver == null) { 13710 return null; 13711 } 13712 13713 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13714 } 13715 13716 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13717 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13718 if (pkgInfo.verifiers.length == 0) { 13719 return null; 13720 } 13721 13722 final int N = pkgInfo.verifiers.length; 13723 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13724 for (int i = 0; i < N; i++) { 13725 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13726 13727 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13728 receivers); 13729 if (comp == null) { 13730 continue; 13731 } 13732 13733 final int verifierUid = getUidForVerifier(verifierInfo); 13734 if (verifierUid == -1) { 13735 continue; 13736 } 13737 13738 if (DEBUG_VERIFY) { 13739 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13740 + " with the correct signature"); 13741 } 13742 sufficientVerifiers.add(comp); 13743 verificationState.addSufficientVerifier(verifierUid); 13744 } 13745 13746 return sufficientVerifiers; 13747 } 13748 13749 private int getUidForVerifier(VerifierInfo verifierInfo) { 13750 synchronized (mPackages) { 13751 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13752 if (pkg == null) { 13753 return -1; 13754 } else if (pkg.mSignatures.length != 1) { 13755 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13756 + " has more than one signature; ignoring"); 13757 return -1; 13758 } 13759 13760 /* 13761 * If the public key of the package's signature does not match 13762 * our expected public key, then this is a different package and 13763 * we should skip. 13764 */ 13765 13766 final byte[] expectedPublicKey; 13767 try { 13768 final Signature verifierSig = pkg.mSignatures[0]; 13769 final PublicKey publicKey = verifierSig.getPublicKey(); 13770 expectedPublicKey = publicKey.getEncoded(); 13771 } catch (CertificateException e) { 13772 return -1; 13773 } 13774 13775 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13776 13777 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13778 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13779 + " does not have the expected public key; ignoring"); 13780 return -1; 13781 } 13782 13783 return pkg.applicationInfo.uid; 13784 } 13785 } 13786 13787 @Override 13788 public void finishPackageInstall(int token, boolean didLaunch) { 13789 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13790 13791 if (DEBUG_INSTALL) { 13792 Slog.v(TAG, "BM finishing package install for " + token); 13793 } 13794 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13795 13796 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13797 mHandler.sendMessage(msg); 13798 } 13799 13800 /** 13801 * Get the verification agent timeout. 13802 * 13803 * @return verification timeout in milliseconds 13804 */ 13805 private long getVerificationTimeout() { 13806 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13807 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13808 DEFAULT_VERIFICATION_TIMEOUT); 13809 } 13810 13811 /** 13812 * Get the default verification agent response code. 13813 * 13814 * @return default verification response code 13815 */ 13816 private int getDefaultVerificationResponse() { 13817 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13818 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13819 DEFAULT_VERIFICATION_RESPONSE); 13820 } 13821 13822 /** 13823 * Check whether or not package verification has been enabled. 13824 * 13825 * @return true if verification should be performed 13826 */ 13827 private boolean isVerificationEnabled(int userId, int installFlags) { 13828 if (!DEFAULT_VERIFY_ENABLE) { 13829 return false; 13830 } 13831 // Ephemeral apps don't get the full verification treatment 13832 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13833 if (DEBUG_EPHEMERAL) { 13834 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 13835 } 13836 return false; 13837 } 13838 13839 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13840 13841 // Check if installing from ADB 13842 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13843 // Do not run verification in a test harness environment 13844 if (ActivityManager.isRunningInTestHarness()) { 13845 return false; 13846 } 13847 if (ensureVerifyAppsEnabled) { 13848 return true; 13849 } 13850 // Check if the developer does not want package verification for ADB installs 13851 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13852 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13853 return false; 13854 } 13855 } 13856 13857 if (ensureVerifyAppsEnabled) { 13858 return true; 13859 } 13860 13861 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13862 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13863 } 13864 13865 @Override 13866 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13867 throws RemoteException { 13868 mContext.enforceCallingOrSelfPermission( 13869 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13870 "Only intentfilter verification agents can verify applications"); 13871 13872 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13873 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13874 Binder.getCallingUid(), verificationCode, failedDomains); 13875 msg.arg1 = id; 13876 msg.obj = response; 13877 mHandler.sendMessage(msg); 13878 } 13879 13880 @Override 13881 public int getIntentVerificationStatus(String packageName, int userId) { 13882 synchronized (mPackages) { 13883 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13884 } 13885 } 13886 13887 @Override 13888 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13889 mContext.enforceCallingOrSelfPermission( 13890 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13891 13892 boolean result = false; 13893 synchronized (mPackages) { 13894 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13895 } 13896 if (result) { 13897 scheduleWritePackageRestrictionsLocked(userId); 13898 } 13899 return result; 13900 } 13901 13902 @Override 13903 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13904 String packageName) { 13905 synchronized (mPackages) { 13906 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13907 } 13908 } 13909 13910 @Override 13911 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13912 if (TextUtils.isEmpty(packageName)) { 13913 return ParceledListSlice.emptyList(); 13914 } 13915 synchronized (mPackages) { 13916 PackageParser.Package pkg = mPackages.get(packageName); 13917 if (pkg == null || pkg.activities == null) { 13918 return ParceledListSlice.emptyList(); 13919 } 13920 final int count = pkg.activities.size(); 13921 ArrayList<IntentFilter> result = new ArrayList<>(); 13922 for (int n=0; n<count; n++) { 13923 PackageParser.Activity activity = pkg.activities.get(n); 13924 if (activity.intents != null && activity.intents.size() > 0) { 13925 result.addAll(activity.intents); 13926 } 13927 } 13928 return new ParceledListSlice<>(result); 13929 } 13930 } 13931 13932 @Override 13933 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13934 mContext.enforceCallingOrSelfPermission( 13935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13936 13937 synchronized (mPackages) { 13938 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13939 if (packageName != null) { 13940 result |= updateIntentVerificationStatus(packageName, 13941 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13942 userId); 13943 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13944 packageName, userId); 13945 } 13946 return result; 13947 } 13948 } 13949 13950 @Override 13951 public String getDefaultBrowserPackageName(int userId) { 13952 synchronized (mPackages) { 13953 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13954 } 13955 } 13956 13957 /** 13958 * Get the "allow unknown sources" setting. 13959 * 13960 * @return the current "allow unknown sources" setting 13961 */ 13962 private int getUnknownSourcesSettings() { 13963 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13964 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13965 -1); 13966 } 13967 13968 @Override 13969 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13970 final int uid = Binder.getCallingUid(); 13971 // writer 13972 synchronized (mPackages) { 13973 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13974 if (targetPackageSetting == null) { 13975 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13976 } 13977 13978 PackageSetting installerPackageSetting; 13979 if (installerPackageName != null) { 13980 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13981 if (installerPackageSetting == null) { 13982 throw new IllegalArgumentException("Unknown installer package: " 13983 + installerPackageName); 13984 } 13985 } else { 13986 installerPackageSetting = null; 13987 } 13988 13989 Signature[] callerSignature; 13990 Object obj = mSettings.getUserIdLPr(uid); 13991 if (obj != null) { 13992 if (obj instanceof SharedUserSetting) { 13993 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13994 } else if (obj instanceof PackageSetting) { 13995 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13996 } else { 13997 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13998 } 13999 } else { 14000 throw new SecurityException("Unknown calling UID: " + uid); 14001 } 14002 14003 // Verify: can't set installerPackageName to a package that is 14004 // not signed with the same cert as the caller. 14005 if (installerPackageSetting != null) { 14006 if (compareSignatures(callerSignature, 14007 installerPackageSetting.signatures.mSignatures) 14008 != PackageManager.SIGNATURE_MATCH) { 14009 throw new SecurityException( 14010 "Caller does not have same cert as new installer package " 14011 + installerPackageName); 14012 } 14013 } 14014 14015 // Verify: if target already has an installer package, it must 14016 // be signed with the same cert as the caller. 14017 if (targetPackageSetting.installerPackageName != null) { 14018 PackageSetting setting = mSettings.mPackages.get( 14019 targetPackageSetting.installerPackageName); 14020 // If the currently set package isn't valid, then it's always 14021 // okay to change it. 14022 if (setting != null) { 14023 if (compareSignatures(callerSignature, 14024 setting.signatures.mSignatures) 14025 != PackageManager.SIGNATURE_MATCH) { 14026 throw new SecurityException( 14027 "Caller does not have same cert as old installer package " 14028 + targetPackageSetting.installerPackageName); 14029 } 14030 } 14031 } 14032 14033 // Okay! 14034 targetPackageSetting.installerPackageName = installerPackageName; 14035 if (installerPackageName != null) { 14036 mSettings.mInstallerPackages.add(installerPackageName); 14037 } 14038 scheduleWriteSettingsLocked(); 14039 } 14040 } 14041 14042 @Override 14043 public void setApplicationCategoryHint(String packageName, int categoryHint, 14044 String callerPackageName) { 14045 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14046 callerPackageName); 14047 synchronized (mPackages) { 14048 PackageSetting ps = mSettings.mPackages.get(packageName); 14049 if (ps == null) { 14050 throw new IllegalArgumentException("Unknown target package " + packageName); 14051 } 14052 14053 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14054 throw new IllegalArgumentException("Calling package " + callerPackageName 14055 + " is not installer for " + packageName); 14056 } 14057 14058 if (ps.categoryHint != categoryHint) { 14059 ps.categoryHint = categoryHint; 14060 scheduleWriteSettingsLocked(); 14061 } 14062 } 14063 } 14064 14065 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14066 // Queue up an async operation since the package installation may take a little while. 14067 mHandler.post(new Runnable() { 14068 public void run() { 14069 mHandler.removeCallbacks(this); 14070 // Result object to be returned 14071 PackageInstalledInfo res = new PackageInstalledInfo(); 14072 res.setReturnCode(currentStatus); 14073 res.uid = -1; 14074 res.pkg = null; 14075 res.removedInfo = null; 14076 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14077 args.doPreInstall(res.returnCode); 14078 synchronized (mInstallLock) { 14079 installPackageTracedLI(args, res); 14080 } 14081 args.doPostInstall(res.returnCode, res.uid); 14082 } 14083 14084 // A restore should be performed at this point if (a) the install 14085 // succeeded, (b) the operation is not an update, and (c) the new 14086 // package has not opted out of backup participation. 14087 final boolean update = res.removedInfo != null 14088 && res.removedInfo.removedPackage != null; 14089 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14090 boolean doRestore = !update 14091 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14092 14093 // Set up the post-install work request bookkeeping. This will be used 14094 // and cleaned up by the post-install event handling regardless of whether 14095 // there's a restore pass performed. Token values are >= 1. 14096 int token; 14097 if (mNextInstallToken < 0) mNextInstallToken = 1; 14098 token = mNextInstallToken++; 14099 14100 PostInstallData data = new PostInstallData(args, res); 14101 mRunningInstalls.put(token, data); 14102 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14103 14104 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14105 // Pass responsibility to the Backup Manager. It will perform a 14106 // restore if appropriate, then pass responsibility back to the 14107 // Package Manager to run the post-install observer callbacks 14108 // and broadcasts. 14109 IBackupManager bm = IBackupManager.Stub.asInterface( 14110 ServiceManager.getService(Context.BACKUP_SERVICE)); 14111 if (bm != null) { 14112 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14113 + " to BM for possible restore"); 14114 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14115 try { 14116 // TODO: http://b/22388012 14117 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14118 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14119 } else { 14120 doRestore = false; 14121 } 14122 } catch (RemoteException e) { 14123 // can't happen; the backup manager is local 14124 } catch (Exception e) { 14125 Slog.e(TAG, "Exception trying to enqueue restore", e); 14126 doRestore = false; 14127 } 14128 } else { 14129 Slog.e(TAG, "Backup Manager not found!"); 14130 doRestore = false; 14131 } 14132 } 14133 14134 if (!doRestore) { 14135 // No restore possible, or the Backup Manager was mysteriously not 14136 // available -- just fire the post-install work request directly. 14137 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14138 14139 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14140 14141 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14142 mHandler.sendMessage(msg); 14143 } 14144 } 14145 }); 14146 } 14147 14148 /** 14149 * Callback from PackageSettings whenever an app is first transitioned out of the 14150 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14151 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14152 * here whether the app is the target of an ongoing install, and only send the 14153 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14154 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14155 * handling. 14156 */ 14157 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14158 // Serialize this with the rest of the install-process message chain. In the 14159 // restore-at-install case, this Runnable will necessarily run before the 14160 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14161 // are coherent. In the non-restore case, the app has already completed install 14162 // and been launched through some other means, so it is not in a problematic 14163 // state for observers to see the FIRST_LAUNCH signal. 14164 mHandler.post(new Runnable() { 14165 @Override 14166 public void run() { 14167 for (int i = 0; i < mRunningInstalls.size(); i++) { 14168 final PostInstallData data = mRunningInstalls.valueAt(i); 14169 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14170 continue; 14171 } 14172 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14173 // right package; but is it for the right user? 14174 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14175 if (userId == data.res.newUsers[uIndex]) { 14176 if (DEBUG_BACKUP) { 14177 Slog.i(TAG, "Package " + pkgName 14178 + " being restored so deferring FIRST_LAUNCH"); 14179 } 14180 return; 14181 } 14182 } 14183 } 14184 } 14185 // didn't find it, so not being restored 14186 if (DEBUG_BACKUP) { 14187 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14188 } 14189 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14190 } 14191 }); 14192 } 14193 14194 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14195 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14196 installerPkg, null, userIds); 14197 } 14198 14199 private abstract class HandlerParams { 14200 private static final int MAX_RETRIES = 4; 14201 14202 /** 14203 * Number of times startCopy() has been attempted and had a non-fatal 14204 * error. 14205 */ 14206 private int mRetries = 0; 14207 14208 /** User handle for the user requesting the information or installation. */ 14209 private final UserHandle mUser; 14210 String traceMethod; 14211 int traceCookie; 14212 14213 HandlerParams(UserHandle user) { 14214 mUser = user; 14215 } 14216 14217 UserHandle getUser() { 14218 return mUser; 14219 } 14220 14221 HandlerParams setTraceMethod(String traceMethod) { 14222 this.traceMethod = traceMethod; 14223 return this; 14224 } 14225 14226 HandlerParams setTraceCookie(int traceCookie) { 14227 this.traceCookie = traceCookie; 14228 return this; 14229 } 14230 14231 final boolean startCopy() { 14232 boolean res; 14233 try { 14234 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14235 14236 if (++mRetries > MAX_RETRIES) { 14237 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14238 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14239 handleServiceError(); 14240 return false; 14241 } else { 14242 handleStartCopy(); 14243 res = true; 14244 } 14245 } catch (RemoteException e) { 14246 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14247 mHandler.sendEmptyMessage(MCS_RECONNECT); 14248 res = false; 14249 } 14250 handleReturnCode(); 14251 return res; 14252 } 14253 14254 final void serviceError() { 14255 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14256 handleServiceError(); 14257 handleReturnCode(); 14258 } 14259 14260 abstract void handleStartCopy() throws RemoteException; 14261 abstract void handleServiceError(); 14262 abstract void handleReturnCode(); 14263 } 14264 14265 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14266 for (File path : paths) { 14267 try { 14268 mcs.clearDirectory(path.getAbsolutePath()); 14269 } catch (RemoteException e) { 14270 } 14271 } 14272 } 14273 14274 static class OriginInfo { 14275 /** 14276 * Location where install is coming from, before it has been 14277 * copied/renamed into place. This could be a single monolithic APK 14278 * file, or a cluster directory. This location may be untrusted. 14279 */ 14280 final File file; 14281 final String cid; 14282 14283 /** 14284 * Flag indicating that {@link #file} or {@link #cid} has already been 14285 * staged, meaning downstream users don't need to defensively copy the 14286 * contents. 14287 */ 14288 final boolean staged; 14289 14290 /** 14291 * Flag indicating that {@link #file} or {@link #cid} is an already 14292 * installed app that is being moved. 14293 */ 14294 final boolean existing; 14295 14296 final String resolvedPath; 14297 final File resolvedFile; 14298 14299 static OriginInfo fromNothing() { 14300 return new OriginInfo(null, null, false, false); 14301 } 14302 14303 static OriginInfo fromUntrustedFile(File file) { 14304 return new OriginInfo(file, null, false, false); 14305 } 14306 14307 static OriginInfo fromExistingFile(File file) { 14308 return new OriginInfo(file, null, false, true); 14309 } 14310 14311 static OriginInfo fromStagedFile(File file) { 14312 return new OriginInfo(file, null, true, false); 14313 } 14314 14315 static OriginInfo fromStagedContainer(String cid) { 14316 return new OriginInfo(null, cid, true, false); 14317 } 14318 14319 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14320 this.file = file; 14321 this.cid = cid; 14322 this.staged = staged; 14323 this.existing = existing; 14324 14325 if (cid != null) { 14326 resolvedPath = PackageHelper.getSdDir(cid); 14327 resolvedFile = new File(resolvedPath); 14328 } else if (file != null) { 14329 resolvedPath = file.getAbsolutePath(); 14330 resolvedFile = file; 14331 } else { 14332 resolvedPath = null; 14333 resolvedFile = null; 14334 } 14335 } 14336 } 14337 14338 static class MoveInfo { 14339 final int moveId; 14340 final String fromUuid; 14341 final String toUuid; 14342 final String packageName; 14343 final String dataAppName; 14344 final int appId; 14345 final String seinfo; 14346 final int targetSdkVersion; 14347 14348 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14349 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14350 this.moveId = moveId; 14351 this.fromUuid = fromUuid; 14352 this.toUuid = toUuid; 14353 this.packageName = packageName; 14354 this.dataAppName = dataAppName; 14355 this.appId = appId; 14356 this.seinfo = seinfo; 14357 this.targetSdkVersion = targetSdkVersion; 14358 } 14359 } 14360 14361 static class VerificationInfo { 14362 /** A constant used to indicate that a uid value is not present. */ 14363 public static final int NO_UID = -1; 14364 14365 /** URI referencing where the package was downloaded from. */ 14366 final Uri originatingUri; 14367 14368 /** HTTP referrer URI associated with the originatingURI. */ 14369 final Uri referrer; 14370 14371 /** UID of the application that the install request originated from. */ 14372 final int originatingUid; 14373 14374 /** UID of application requesting the install */ 14375 final int installerUid; 14376 14377 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14378 this.originatingUri = originatingUri; 14379 this.referrer = referrer; 14380 this.originatingUid = originatingUid; 14381 this.installerUid = installerUid; 14382 } 14383 } 14384 14385 class InstallParams extends HandlerParams { 14386 final OriginInfo origin; 14387 final MoveInfo move; 14388 final IPackageInstallObserver2 observer; 14389 int installFlags; 14390 final String installerPackageName; 14391 final String volumeUuid; 14392 private InstallArgs mArgs; 14393 private int mRet; 14394 final String packageAbiOverride; 14395 final String[] grantedRuntimePermissions; 14396 final VerificationInfo verificationInfo; 14397 final Certificate[][] certificates; 14398 final int installReason; 14399 14400 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14401 int installFlags, String installerPackageName, String volumeUuid, 14402 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14403 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14404 super(user); 14405 this.origin = origin; 14406 this.move = move; 14407 this.observer = observer; 14408 this.installFlags = installFlags; 14409 this.installerPackageName = installerPackageName; 14410 this.volumeUuid = volumeUuid; 14411 this.verificationInfo = verificationInfo; 14412 this.packageAbiOverride = packageAbiOverride; 14413 this.grantedRuntimePermissions = grantedPermissions; 14414 this.certificates = certificates; 14415 this.installReason = installReason; 14416 } 14417 14418 @Override 14419 public String toString() { 14420 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14421 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14422 } 14423 14424 private int installLocationPolicy(PackageInfoLite pkgLite) { 14425 String packageName = pkgLite.packageName; 14426 int installLocation = pkgLite.installLocation; 14427 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14428 // reader 14429 synchronized (mPackages) { 14430 // Currently installed package which the new package is attempting to replace or 14431 // null if no such package is installed. 14432 PackageParser.Package installedPkg = mPackages.get(packageName); 14433 // Package which currently owns the data which the new package will own if installed. 14434 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14435 // will be null whereas dataOwnerPkg will contain information about the package 14436 // which was uninstalled while keeping its data. 14437 PackageParser.Package dataOwnerPkg = installedPkg; 14438 if (dataOwnerPkg == null) { 14439 PackageSetting ps = mSettings.mPackages.get(packageName); 14440 if (ps != null) { 14441 dataOwnerPkg = ps.pkg; 14442 } 14443 } 14444 14445 if (dataOwnerPkg != null) { 14446 // If installed, the package will get access to data left on the device by its 14447 // predecessor. As a security measure, this is permited only if this is not a 14448 // version downgrade or if the predecessor package is marked as debuggable and 14449 // a downgrade is explicitly requested. 14450 // 14451 // On debuggable platform builds, downgrades are permitted even for 14452 // non-debuggable packages to make testing easier. Debuggable platform builds do 14453 // not offer security guarantees and thus it's OK to disable some security 14454 // mechanisms to make debugging/testing easier on those builds. However, even on 14455 // debuggable builds downgrades of packages are permitted only if requested via 14456 // installFlags. This is because we aim to keep the behavior of debuggable 14457 // platform builds as close as possible to the behavior of non-debuggable 14458 // platform builds. 14459 final boolean downgradeRequested = 14460 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14461 final boolean packageDebuggable = 14462 (dataOwnerPkg.applicationInfo.flags 14463 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14464 final boolean downgradePermitted = 14465 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14466 if (!downgradePermitted) { 14467 try { 14468 checkDowngrade(dataOwnerPkg, pkgLite); 14469 } catch (PackageManagerException e) { 14470 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14471 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14472 } 14473 } 14474 } 14475 14476 if (installedPkg != null) { 14477 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14478 // Check for updated system application. 14479 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14480 if (onSd) { 14481 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14482 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14483 } 14484 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14485 } else { 14486 if (onSd) { 14487 // Install flag overrides everything. 14488 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14489 } 14490 // If current upgrade specifies particular preference 14491 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14492 // Application explicitly specified internal. 14493 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14494 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14495 // App explictly prefers external. Let policy decide 14496 } else { 14497 // Prefer previous location 14498 if (isExternal(installedPkg)) { 14499 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14500 } 14501 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14502 } 14503 } 14504 } else { 14505 // Invalid install. Return error code 14506 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14507 } 14508 } 14509 } 14510 // All the special cases have been taken care of. 14511 // Return result based on recommended install location. 14512 if (onSd) { 14513 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14514 } 14515 return pkgLite.recommendedInstallLocation; 14516 } 14517 14518 /* 14519 * Invoke remote method to get package information and install 14520 * location values. Override install location based on default 14521 * policy if needed and then create install arguments based 14522 * on the install location. 14523 */ 14524 public void handleStartCopy() throws RemoteException { 14525 int ret = PackageManager.INSTALL_SUCCEEDED; 14526 14527 // If we're already staged, we've firmly committed to an install location 14528 if (origin.staged) { 14529 if (origin.file != null) { 14530 installFlags |= PackageManager.INSTALL_INTERNAL; 14531 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14532 } else if (origin.cid != null) { 14533 installFlags |= PackageManager.INSTALL_EXTERNAL; 14534 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14535 } else { 14536 throw new IllegalStateException("Invalid stage location"); 14537 } 14538 } 14539 14540 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14541 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14542 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14543 PackageInfoLite pkgLite = null; 14544 14545 if (onInt && onSd) { 14546 // Check if both bits are set. 14547 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14548 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14549 } else if (onSd && ephemeral) { 14550 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14551 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14552 } else { 14553 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14554 packageAbiOverride); 14555 14556 if (DEBUG_EPHEMERAL && ephemeral) { 14557 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14558 } 14559 14560 /* 14561 * If we have too little free space, try to free cache 14562 * before giving up. 14563 */ 14564 if (!origin.staged && pkgLite.recommendedInstallLocation 14565 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14566 // TODO: focus freeing disk space on the target device 14567 final StorageManager storage = StorageManager.from(mContext); 14568 final long lowThreshold = storage.getStorageLowBytes( 14569 Environment.getDataDirectory()); 14570 14571 final long sizeBytes = mContainerService.calculateInstalledSize( 14572 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14573 14574 try { 14575 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14576 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14577 installFlags, packageAbiOverride); 14578 } catch (InstallerException e) { 14579 Slog.w(TAG, "Failed to free cache", e); 14580 } 14581 14582 /* 14583 * The cache free must have deleted the file we 14584 * downloaded to install. 14585 * 14586 * TODO: fix the "freeCache" call to not delete 14587 * the file we care about. 14588 */ 14589 if (pkgLite.recommendedInstallLocation 14590 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14591 pkgLite.recommendedInstallLocation 14592 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14593 } 14594 } 14595 } 14596 14597 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14598 int loc = pkgLite.recommendedInstallLocation; 14599 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14600 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14601 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14602 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14603 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14604 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14605 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14606 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14607 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14608 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14609 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14610 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14611 } else { 14612 // Override with defaults if needed. 14613 loc = installLocationPolicy(pkgLite); 14614 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14615 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14616 } else if (!onSd && !onInt) { 14617 // Override install location with flags 14618 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14619 // Set the flag to install on external media. 14620 installFlags |= PackageManager.INSTALL_EXTERNAL; 14621 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14622 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14623 if (DEBUG_EPHEMERAL) { 14624 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14625 } 14626 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14627 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14628 |PackageManager.INSTALL_INTERNAL); 14629 } else { 14630 // Make sure the flag for installing on external 14631 // media is unset 14632 installFlags |= PackageManager.INSTALL_INTERNAL; 14633 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14634 } 14635 } 14636 } 14637 } 14638 14639 final InstallArgs args = createInstallArgs(this); 14640 mArgs = args; 14641 14642 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14643 // TODO: http://b/22976637 14644 // Apps installed for "all" users use the device owner to verify the app 14645 UserHandle verifierUser = getUser(); 14646 if (verifierUser == UserHandle.ALL) { 14647 verifierUser = UserHandle.SYSTEM; 14648 } 14649 14650 /* 14651 * Determine if we have any installed package verifiers. If we 14652 * do, then we'll defer to them to verify the packages. 14653 */ 14654 final int requiredUid = mRequiredVerifierPackage == null ? -1 14655 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14656 verifierUser.getIdentifier()); 14657 if (!origin.existing && requiredUid != -1 14658 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14659 final Intent verification = new Intent( 14660 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14661 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14662 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14663 PACKAGE_MIME_TYPE); 14664 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14665 14666 // Query all live verifiers based on current user state 14667 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14668 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14669 14670 if (DEBUG_VERIFY) { 14671 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14672 + verification.toString() + " with " + pkgLite.verifiers.length 14673 + " optional verifiers"); 14674 } 14675 14676 final int verificationId = mPendingVerificationToken++; 14677 14678 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14679 14680 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14681 installerPackageName); 14682 14683 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14684 installFlags); 14685 14686 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14687 pkgLite.packageName); 14688 14689 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14690 pkgLite.versionCode); 14691 14692 if (verificationInfo != null) { 14693 if (verificationInfo.originatingUri != null) { 14694 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14695 verificationInfo.originatingUri); 14696 } 14697 if (verificationInfo.referrer != null) { 14698 verification.putExtra(Intent.EXTRA_REFERRER, 14699 verificationInfo.referrer); 14700 } 14701 if (verificationInfo.originatingUid >= 0) { 14702 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14703 verificationInfo.originatingUid); 14704 } 14705 if (verificationInfo.installerUid >= 0) { 14706 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14707 verificationInfo.installerUid); 14708 } 14709 } 14710 14711 final PackageVerificationState verificationState = new PackageVerificationState( 14712 requiredUid, args); 14713 14714 mPendingVerification.append(verificationId, verificationState); 14715 14716 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14717 receivers, verificationState); 14718 14719 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14720 final long idleDuration = getVerificationTimeout(); 14721 14722 /* 14723 * If any sufficient verifiers were listed in the package 14724 * manifest, attempt to ask them. 14725 */ 14726 if (sufficientVerifiers != null) { 14727 final int N = sufficientVerifiers.size(); 14728 if (N == 0) { 14729 Slog.i(TAG, "Additional verifiers required, but none installed."); 14730 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14731 } else { 14732 for (int i = 0; i < N; i++) { 14733 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14734 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14735 verifierComponent.getPackageName(), idleDuration, 14736 verifierUser.getIdentifier(), false, "package verifier"); 14737 14738 final Intent sufficientIntent = new Intent(verification); 14739 sufficientIntent.setComponent(verifierComponent); 14740 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14741 } 14742 } 14743 } 14744 14745 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14746 mRequiredVerifierPackage, receivers); 14747 if (ret == PackageManager.INSTALL_SUCCEEDED 14748 && mRequiredVerifierPackage != null) { 14749 Trace.asyncTraceBegin( 14750 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14751 /* 14752 * Send the intent to the required verification agent, 14753 * but only start the verification timeout after the 14754 * target BroadcastReceivers have run. 14755 */ 14756 verification.setComponent(requiredVerifierComponent); 14757 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14758 requiredVerifierComponent.getPackageName(), idleDuration, 14759 verifierUser.getIdentifier(), false, "package verifier"); 14760 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14761 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14762 new BroadcastReceiver() { 14763 @Override 14764 public void onReceive(Context context, Intent intent) { 14765 final Message msg = mHandler 14766 .obtainMessage(CHECK_PENDING_VERIFICATION); 14767 msg.arg1 = verificationId; 14768 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14769 } 14770 }, null, 0, null, null); 14771 14772 /* 14773 * We don't want the copy to proceed until verification 14774 * succeeds, so null out this field. 14775 */ 14776 mArgs = null; 14777 } 14778 } else { 14779 /* 14780 * No package verification is enabled, so immediately start 14781 * the remote call to initiate copy using temporary file. 14782 */ 14783 ret = args.copyApk(mContainerService, true); 14784 } 14785 } 14786 14787 mRet = ret; 14788 } 14789 14790 @Override 14791 void handleReturnCode() { 14792 // If mArgs is null, then MCS couldn't be reached. When it 14793 // reconnects, it will try again to install. At that point, this 14794 // will succeed. 14795 if (mArgs != null) { 14796 processPendingInstall(mArgs, mRet); 14797 } 14798 } 14799 14800 @Override 14801 void handleServiceError() { 14802 mArgs = createInstallArgs(this); 14803 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14804 } 14805 14806 public boolean isForwardLocked() { 14807 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14808 } 14809 } 14810 14811 /** 14812 * Used during creation of InstallArgs 14813 * 14814 * @param installFlags package installation flags 14815 * @return true if should be installed on external storage 14816 */ 14817 private static boolean installOnExternalAsec(int installFlags) { 14818 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14819 return false; 14820 } 14821 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14822 return true; 14823 } 14824 return false; 14825 } 14826 14827 /** 14828 * Used during creation of InstallArgs 14829 * 14830 * @param installFlags package installation flags 14831 * @return true if should be installed as forward locked 14832 */ 14833 private static boolean installForwardLocked(int installFlags) { 14834 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14835 } 14836 14837 private InstallArgs createInstallArgs(InstallParams params) { 14838 if (params.move != null) { 14839 return new MoveInstallArgs(params); 14840 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14841 return new AsecInstallArgs(params); 14842 } else { 14843 return new FileInstallArgs(params); 14844 } 14845 } 14846 14847 /** 14848 * Create args that describe an existing installed package. Typically used 14849 * when cleaning up old installs, or used as a move source. 14850 */ 14851 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14852 String resourcePath, String[] instructionSets) { 14853 final boolean isInAsec; 14854 if (installOnExternalAsec(installFlags)) { 14855 /* Apps on SD card are always in ASEC containers. */ 14856 isInAsec = true; 14857 } else if (installForwardLocked(installFlags) 14858 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14859 /* 14860 * Forward-locked apps are only in ASEC containers if they're the 14861 * new style 14862 */ 14863 isInAsec = true; 14864 } else { 14865 isInAsec = false; 14866 } 14867 14868 if (isInAsec) { 14869 return new AsecInstallArgs(codePath, instructionSets, 14870 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14871 } else { 14872 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14873 } 14874 } 14875 14876 static abstract class InstallArgs { 14877 /** @see InstallParams#origin */ 14878 final OriginInfo origin; 14879 /** @see InstallParams#move */ 14880 final MoveInfo move; 14881 14882 final IPackageInstallObserver2 observer; 14883 // Always refers to PackageManager flags only 14884 final int installFlags; 14885 final String installerPackageName; 14886 final String volumeUuid; 14887 final UserHandle user; 14888 final String abiOverride; 14889 final String[] installGrantPermissions; 14890 /** If non-null, drop an async trace when the install completes */ 14891 final String traceMethod; 14892 final int traceCookie; 14893 final Certificate[][] certificates; 14894 final int installReason; 14895 14896 // The list of instruction sets supported by this app. This is currently 14897 // only used during the rmdex() phase to clean up resources. We can get rid of this 14898 // if we move dex files under the common app path. 14899 /* nullable */ String[] instructionSets; 14900 14901 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14902 int installFlags, String installerPackageName, String volumeUuid, 14903 UserHandle user, String[] instructionSets, 14904 String abiOverride, String[] installGrantPermissions, 14905 String traceMethod, int traceCookie, Certificate[][] certificates, 14906 int installReason) { 14907 this.origin = origin; 14908 this.move = move; 14909 this.installFlags = installFlags; 14910 this.observer = observer; 14911 this.installerPackageName = installerPackageName; 14912 this.volumeUuid = volumeUuid; 14913 this.user = user; 14914 this.instructionSets = instructionSets; 14915 this.abiOverride = abiOverride; 14916 this.installGrantPermissions = installGrantPermissions; 14917 this.traceMethod = traceMethod; 14918 this.traceCookie = traceCookie; 14919 this.certificates = certificates; 14920 this.installReason = installReason; 14921 } 14922 14923 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14924 abstract int doPreInstall(int status); 14925 14926 /** 14927 * Rename package into final resting place. All paths on the given 14928 * scanned package should be updated to reflect the rename. 14929 */ 14930 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14931 abstract int doPostInstall(int status, int uid); 14932 14933 /** @see PackageSettingBase#codePathString */ 14934 abstract String getCodePath(); 14935 /** @see PackageSettingBase#resourcePathString */ 14936 abstract String getResourcePath(); 14937 14938 // Need installer lock especially for dex file removal. 14939 abstract void cleanUpResourcesLI(); 14940 abstract boolean doPostDeleteLI(boolean delete); 14941 14942 /** 14943 * Called before the source arguments are copied. This is used mostly 14944 * for MoveParams when it needs to read the source file to put it in the 14945 * destination. 14946 */ 14947 int doPreCopy() { 14948 return PackageManager.INSTALL_SUCCEEDED; 14949 } 14950 14951 /** 14952 * Called after the source arguments are copied. This is used mostly for 14953 * MoveParams when it needs to read the source file to put it in the 14954 * destination. 14955 */ 14956 int doPostCopy(int uid) { 14957 return PackageManager.INSTALL_SUCCEEDED; 14958 } 14959 14960 protected boolean isFwdLocked() { 14961 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14962 } 14963 14964 protected boolean isExternalAsec() { 14965 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14966 } 14967 14968 protected boolean isEphemeral() { 14969 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14970 } 14971 14972 UserHandle getUser() { 14973 return user; 14974 } 14975 } 14976 14977 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14978 if (!allCodePaths.isEmpty()) { 14979 if (instructionSets == null) { 14980 throw new IllegalStateException("instructionSet == null"); 14981 } 14982 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14983 for (String codePath : allCodePaths) { 14984 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14985 try { 14986 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14987 } catch (InstallerException ignored) { 14988 } 14989 } 14990 } 14991 } 14992 } 14993 14994 /** 14995 * Logic to handle installation of non-ASEC applications, including copying 14996 * and renaming logic. 14997 */ 14998 class FileInstallArgs extends InstallArgs { 14999 private File codeFile; 15000 private File resourceFile; 15001 15002 // Example topology: 15003 // /data/app/com.example/base.apk 15004 // /data/app/com.example/split_foo.apk 15005 // /data/app/com.example/lib/arm/libfoo.so 15006 // /data/app/com.example/lib/arm64/libfoo.so 15007 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15008 15009 /** New install */ 15010 FileInstallArgs(InstallParams params) { 15011 super(params.origin, params.move, params.observer, params.installFlags, 15012 params.installerPackageName, params.volumeUuid, 15013 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15014 params.grantedRuntimePermissions, 15015 params.traceMethod, params.traceCookie, params.certificates, 15016 params.installReason); 15017 if (isFwdLocked()) { 15018 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15019 } 15020 } 15021 15022 /** Existing install */ 15023 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15024 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15025 null, null, null, 0, null /*certificates*/, 15026 PackageManager.INSTALL_REASON_UNKNOWN); 15027 this.codeFile = (codePath != null) ? new File(codePath) : null; 15028 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15029 } 15030 15031 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15032 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15033 try { 15034 return doCopyApk(imcs, temp); 15035 } finally { 15036 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15037 } 15038 } 15039 15040 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15041 if (origin.staged) { 15042 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15043 codeFile = origin.file; 15044 resourceFile = origin.file; 15045 return PackageManager.INSTALL_SUCCEEDED; 15046 } 15047 15048 try { 15049 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15050 final File tempDir = 15051 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15052 codeFile = tempDir; 15053 resourceFile = tempDir; 15054 } catch (IOException e) { 15055 Slog.w(TAG, "Failed to create copy file: " + e); 15056 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15057 } 15058 15059 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15060 @Override 15061 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15062 if (!FileUtils.isValidExtFilename(name)) { 15063 throw new IllegalArgumentException("Invalid filename: " + name); 15064 } 15065 try { 15066 final File file = new File(codeFile, name); 15067 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15068 O_RDWR | O_CREAT, 0644); 15069 Os.chmod(file.getAbsolutePath(), 0644); 15070 return new ParcelFileDescriptor(fd); 15071 } catch (ErrnoException e) { 15072 throw new RemoteException("Failed to open: " + e.getMessage()); 15073 } 15074 } 15075 }; 15076 15077 int ret = PackageManager.INSTALL_SUCCEEDED; 15078 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15079 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15080 Slog.e(TAG, "Failed to copy package"); 15081 return ret; 15082 } 15083 15084 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15085 NativeLibraryHelper.Handle handle = null; 15086 try { 15087 handle = NativeLibraryHelper.Handle.create(codeFile); 15088 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15089 abiOverride); 15090 } catch (IOException e) { 15091 Slog.e(TAG, "Copying native libraries failed", e); 15092 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15093 } finally { 15094 IoUtils.closeQuietly(handle); 15095 } 15096 15097 return ret; 15098 } 15099 15100 int doPreInstall(int status) { 15101 if (status != PackageManager.INSTALL_SUCCEEDED) { 15102 cleanUp(); 15103 } 15104 return status; 15105 } 15106 15107 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15108 if (status != PackageManager.INSTALL_SUCCEEDED) { 15109 cleanUp(); 15110 return false; 15111 } 15112 15113 final File targetDir = codeFile.getParentFile(); 15114 final File beforeCodeFile = codeFile; 15115 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15116 15117 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15118 try { 15119 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15120 } catch (ErrnoException e) { 15121 Slog.w(TAG, "Failed to rename", e); 15122 return false; 15123 } 15124 15125 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15126 Slog.w(TAG, "Failed to restorecon"); 15127 return false; 15128 } 15129 15130 // Reflect the rename internally 15131 codeFile = afterCodeFile; 15132 resourceFile = afterCodeFile; 15133 15134 // Reflect the rename in scanned details 15135 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15136 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15137 afterCodeFile, pkg.baseCodePath)); 15138 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15139 afterCodeFile, pkg.splitCodePaths)); 15140 15141 // Reflect the rename in app info 15142 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15143 pkg.setApplicationInfoCodePath(pkg.codePath); 15144 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15145 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15146 pkg.setApplicationInfoResourcePath(pkg.codePath); 15147 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15148 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15149 15150 return true; 15151 } 15152 15153 int doPostInstall(int status, int uid) { 15154 if (status != PackageManager.INSTALL_SUCCEEDED) { 15155 cleanUp(); 15156 } 15157 return status; 15158 } 15159 15160 @Override 15161 String getCodePath() { 15162 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15163 } 15164 15165 @Override 15166 String getResourcePath() { 15167 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15168 } 15169 15170 private boolean cleanUp() { 15171 if (codeFile == null || !codeFile.exists()) { 15172 return false; 15173 } 15174 15175 removeCodePathLI(codeFile); 15176 15177 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15178 resourceFile.delete(); 15179 } 15180 15181 return true; 15182 } 15183 15184 void cleanUpResourcesLI() { 15185 // Try enumerating all code paths before deleting 15186 List<String> allCodePaths = Collections.EMPTY_LIST; 15187 if (codeFile != null && codeFile.exists()) { 15188 try { 15189 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15190 allCodePaths = pkg.getAllCodePaths(); 15191 } catch (PackageParserException e) { 15192 // Ignored; we tried our best 15193 } 15194 } 15195 15196 cleanUp(); 15197 removeDexFiles(allCodePaths, instructionSets); 15198 } 15199 15200 boolean doPostDeleteLI(boolean delete) { 15201 // XXX err, shouldn't we respect the delete flag? 15202 cleanUpResourcesLI(); 15203 return true; 15204 } 15205 } 15206 15207 private boolean isAsecExternal(String cid) { 15208 final String asecPath = PackageHelper.getSdFilesystem(cid); 15209 return !asecPath.startsWith(mAsecInternalPath); 15210 } 15211 15212 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15213 PackageManagerException { 15214 if (copyRet < 0) { 15215 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15216 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15217 throw new PackageManagerException(copyRet, message); 15218 } 15219 } 15220 } 15221 15222 /** 15223 * Extract the StorageManagerService "container ID" from the full code path of an 15224 * .apk. 15225 */ 15226 static String cidFromCodePath(String fullCodePath) { 15227 int eidx = fullCodePath.lastIndexOf("/"); 15228 String subStr1 = fullCodePath.substring(0, eidx); 15229 int sidx = subStr1.lastIndexOf("/"); 15230 return subStr1.substring(sidx+1, eidx); 15231 } 15232 15233 /** 15234 * Logic to handle installation of ASEC applications, including copying and 15235 * renaming logic. 15236 */ 15237 class AsecInstallArgs extends InstallArgs { 15238 static final String RES_FILE_NAME = "pkg.apk"; 15239 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15240 15241 String cid; 15242 String packagePath; 15243 String resourcePath; 15244 15245 /** New install */ 15246 AsecInstallArgs(InstallParams params) { 15247 super(params.origin, params.move, params.observer, params.installFlags, 15248 params.installerPackageName, params.volumeUuid, 15249 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15250 params.grantedRuntimePermissions, 15251 params.traceMethod, params.traceCookie, params.certificates, 15252 params.installReason); 15253 } 15254 15255 /** Existing install */ 15256 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15257 boolean isExternal, boolean isForwardLocked) { 15258 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15259 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15260 instructionSets, null, null, null, 0, null /*certificates*/, 15261 PackageManager.INSTALL_REASON_UNKNOWN); 15262 // Hackily pretend we're still looking at a full code path 15263 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15264 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15265 } 15266 15267 // Extract cid from fullCodePath 15268 int eidx = fullCodePath.lastIndexOf("/"); 15269 String subStr1 = fullCodePath.substring(0, eidx); 15270 int sidx = subStr1.lastIndexOf("/"); 15271 cid = subStr1.substring(sidx+1, eidx); 15272 setMountPath(subStr1); 15273 } 15274 15275 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15276 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15277 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15278 instructionSets, null, null, null, 0, null /*certificates*/, 15279 PackageManager.INSTALL_REASON_UNKNOWN); 15280 this.cid = cid; 15281 setMountPath(PackageHelper.getSdDir(cid)); 15282 } 15283 15284 void createCopyFile() { 15285 cid = mInstallerService.allocateExternalStageCidLegacy(); 15286 } 15287 15288 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15289 if (origin.staged && origin.cid != null) { 15290 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15291 cid = origin.cid; 15292 setMountPath(PackageHelper.getSdDir(cid)); 15293 return PackageManager.INSTALL_SUCCEEDED; 15294 } 15295 15296 if (temp) { 15297 createCopyFile(); 15298 } else { 15299 /* 15300 * Pre-emptively destroy the container since it's destroyed if 15301 * copying fails due to it existing anyway. 15302 */ 15303 PackageHelper.destroySdDir(cid); 15304 } 15305 15306 final String newMountPath = imcs.copyPackageToContainer( 15307 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15308 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15309 15310 if (newMountPath != null) { 15311 setMountPath(newMountPath); 15312 return PackageManager.INSTALL_SUCCEEDED; 15313 } else { 15314 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15315 } 15316 } 15317 15318 @Override 15319 String getCodePath() { 15320 return packagePath; 15321 } 15322 15323 @Override 15324 String getResourcePath() { 15325 return resourcePath; 15326 } 15327 15328 int doPreInstall(int status) { 15329 if (status != PackageManager.INSTALL_SUCCEEDED) { 15330 // Destroy container 15331 PackageHelper.destroySdDir(cid); 15332 } else { 15333 boolean mounted = PackageHelper.isContainerMounted(cid); 15334 if (!mounted) { 15335 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15336 Process.SYSTEM_UID); 15337 if (newMountPath != null) { 15338 setMountPath(newMountPath); 15339 } else { 15340 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15341 } 15342 } 15343 } 15344 return status; 15345 } 15346 15347 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15348 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15349 String newMountPath = null; 15350 if (PackageHelper.isContainerMounted(cid)) { 15351 // Unmount the container 15352 if (!PackageHelper.unMountSdDir(cid)) { 15353 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15354 return false; 15355 } 15356 } 15357 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15358 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15359 " which might be stale. Will try to clean up."); 15360 // Clean up the stale container and proceed to recreate. 15361 if (!PackageHelper.destroySdDir(newCacheId)) { 15362 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15363 return false; 15364 } 15365 // Successfully cleaned up stale container. Try to rename again. 15366 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15367 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15368 + " inspite of cleaning it up."); 15369 return false; 15370 } 15371 } 15372 if (!PackageHelper.isContainerMounted(newCacheId)) { 15373 Slog.w(TAG, "Mounting container " + newCacheId); 15374 newMountPath = PackageHelper.mountSdDir(newCacheId, 15375 getEncryptKey(), Process.SYSTEM_UID); 15376 } else { 15377 newMountPath = PackageHelper.getSdDir(newCacheId); 15378 } 15379 if (newMountPath == null) { 15380 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15381 return false; 15382 } 15383 Log.i(TAG, "Succesfully renamed " + cid + 15384 " to " + newCacheId + 15385 " at new path: " + newMountPath); 15386 cid = newCacheId; 15387 15388 final File beforeCodeFile = new File(packagePath); 15389 setMountPath(newMountPath); 15390 final File afterCodeFile = new File(packagePath); 15391 15392 // Reflect the rename in scanned details 15393 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15394 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15395 afterCodeFile, pkg.baseCodePath)); 15396 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15397 afterCodeFile, pkg.splitCodePaths)); 15398 15399 // Reflect the rename in app info 15400 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15401 pkg.setApplicationInfoCodePath(pkg.codePath); 15402 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15403 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15404 pkg.setApplicationInfoResourcePath(pkg.codePath); 15405 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15406 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15407 15408 return true; 15409 } 15410 15411 private void setMountPath(String mountPath) { 15412 final File mountFile = new File(mountPath); 15413 15414 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15415 if (monolithicFile.exists()) { 15416 packagePath = monolithicFile.getAbsolutePath(); 15417 if (isFwdLocked()) { 15418 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15419 } else { 15420 resourcePath = packagePath; 15421 } 15422 } else { 15423 packagePath = mountFile.getAbsolutePath(); 15424 resourcePath = packagePath; 15425 } 15426 } 15427 15428 int doPostInstall(int status, int uid) { 15429 if (status != PackageManager.INSTALL_SUCCEEDED) { 15430 cleanUp(); 15431 } else { 15432 final int groupOwner; 15433 final String protectedFile; 15434 if (isFwdLocked()) { 15435 groupOwner = UserHandle.getSharedAppGid(uid); 15436 protectedFile = RES_FILE_NAME; 15437 } else { 15438 groupOwner = -1; 15439 protectedFile = null; 15440 } 15441 15442 if (uid < Process.FIRST_APPLICATION_UID 15443 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15444 Slog.e(TAG, "Failed to finalize " + cid); 15445 PackageHelper.destroySdDir(cid); 15446 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15447 } 15448 15449 boolean mounted = PackageHelper.isContainerMounted(cid); 15450 if (!mounted) { 15451 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15452 } 15453 } 15454 return status; 15455 } 15456 15457 private void cleanUp() { 15458 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15459 15460 // Destroy secure container 15461 PackageHelper.destroySdDir(cid); 15462 } 15463 15464 private List<String> getAllCodePaths() { 15465 final File codeFile = new File(getCodePath()); 15466 if (codeFile != null && codeFile.exists()) { 15467 try { 15468 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15469 return pkg.getAllCodePaths(); 15470 } catch (PackageParserException e) { 15471 // Ignored; we tried our best 15472 } 15473 } 15474 return Collections.EMPTY_LIST; 15475 } 15476 15477 void cleanUpResourcesLI() { 15478 // Enumerate all code paths before deleting 15479 cleanUpResourcesLI(getAllCodePaths()); 15480 } 15481 15482 private void cleanUpResourcesLI(List<String> allCodePaths) { 15483 cleanUp(); 15484 removeDexFiles(allCodePaths, instructionSets); 15485 } 15486 15487 String getPackageName() { 15488 return getAsecPackageName(cid); 15489 } 15490 15491 boolean doPostDeleteLI(boolean delete) { 15492 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15493 final List<String> allCodePaths = getAllCodePaths(); 15494 boolean mounted = PackageHelper.isContainerMounted(cid); 15495 if (mounted) { 15496 // Unmount first 15497 if (PackageHelper.unMountSdDir(cid)) { 15498 mounted = false; 15499 } 15500 } 15501 if (!mounted && delete) { 15502 cleanUpResourcesLI(allCodePaths); 15503 } 15504 return !mounted; 15505 } 15506 15507 @Override 15508 int doPreCopy() { 15509 if (isFwdLocked()) { 15510 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15511 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15512 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15513 } 15514 } 15515 15516 return PackageManager.INSTALL_SUCCEEDED; 15517 } 15518 15519 @Override 15520 int doPostCopy(int uid) { 15521 if (isFwdLocked()) { 15522 if (uid < Process.FIRST_APPLICATION_UID 15523 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15524 RES_FILE_NAME)) { 15525 Slog.e(TAG, "Failed to finalize " + cid); 15526 PackageHelper.destroySdDir(cid); 15527 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15528 } 15529 } 15530 15531 return PackageManager.INSTALL_SUCCEEDED; 15532 } 15533 } 15534 15535 /** 15536 * Logic to handle movement of existing installed applications. 15537 */ 15538 class MoveInstallArgs extends InstallArgs { 15539 private File codeFile; 15540 private File resourceFile; 15541 15542 /** New install */ 15543 MoveInstallArgs(InstallParams params) { 15544 super(params.origin, params.move, params.observer, params.installFlags, 15545 params.installerPackageName, params.volumeUuid, 15546 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15547 params.grantedRuntimePermissions, 15548 params.traceMethod, params.traceCookie, params.certificates, 15549 params.installReason); 15550 } 15551 15552 int copyApk(IMediaContainerService imcs, boolean temp) { 15553 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15554 + move.fromUuid + " to " + move.toUuid); 15555 synchronized (mInstaller) { 15556 try { 15557 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15558 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15559 } catch (InstallerException e) { 15560 Slog.w(TAG, "Failed to move app", e); 15561 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15562 } 15563 } 15564 15565 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15566 resourceFile = codeFile; 15567 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15568 15569 return PackageManager.INSTALL_SUCCEEDED; 15570 } 15571 15572 int doPreInstall(int status) { 15573 if (status != PackageManager.INSTALL_SUCCEEDED) { 15574 cleanUp(move.toUuid); 15575 } 15576 return status; 15577 } 15578 15579 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15580 if (status != PackageManager.INSTALL_SUCCEEDED) { 15581 cleanUp(move.toUuid); 15582 return false; 15583 } 15584 15585 // Reflect the move in app info 15586 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15587 pkg.setApplicationInfoCodePath(pkg.codePath); 15588 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15589 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15590 pkg.setApplicationInfoResourcePath(pkg.codePath); 15591 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15592 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15593 15594 return true; 15595 } 15596 15597 int doPostInstall(int status, int uid) { 15598 if (status == PackageManager.INSTALL_SUCCEEDED) { 15599 cleanUp(move.fromUuid); 15600 } else { 15601 cleanUp(move.toUuid); 15602 } 15603 return status; 15604 } 15605 15606 @Override 15607 String getCodePath() { 15608 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15609 } 15610 15611 @Override 15612 String getResourcePath() { 15613 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15614 } 15615 15616 private boolean cleanUp(String volumeUuid) { 15617 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15618 move.dataAppName); 15619 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15620 final int[] userIds = sUserManager.getUserIds(); 15621 synchronized (mInstallLock) { 15622 // Clean up both app data and code 15623 // All package moves are frozen until finished 15624 for (int userId : userIds) { 15625 try { 15626 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15627 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15628 } catch (InstallerException e) { 15629 Slog.w(TAG, String.valueOf(e)); 15630 } 15631 } 15632 removeCodePathLI(codeFile); 15633 } 15634 return true; 15635 } 15636 15637 void cleanUpResourcesLI() { 15638 throw new UnsupportedOperationException(); 15639 } 15640 15641 boolean doPostDeleteLI(boolean delete) { 15642 throw new UnsupportedOperationException(); 15643 } 15644 } 15645 15646 static String getAsecPackageName(String packageCid) { 15647 int idx = packageCid.lastIndexOf("-"); 15648 if (idx == -1) { 15649 return packageCid; 15650 } 15651 return packageCid.substring(0, idx); 15652 } 15653 15654 // Utility method used to create code paths based on package name and available index. 15655 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15656 String idxStr = ""; 15657 int idx = 1; 15658 // Fall back to default value of idx=1 if prefix is not 15659 // part of oldCodePath 15660 if (oldCodePath != null) { 15661 String subStr = oldCodePath; 15662 // Drop the suffix right away 15663 if (suffix != null && subStr.endsWith(suffix)) { 15664 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15665 } 15666 // If oldCodePath already contains prefix find out the 15667 // ending index to either increment or decrement. 15668 int sidx = subStr.lastIndexOf(prefix); 15669 if (sidx != -1) { 15670 subStr = subStr.substring(sidx + prefix.length()); 15671 if (subStr != null) { 15672 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15673 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15674 } 15675 try { 15676 idx = Integer.parseInt(subStr); 15677 if (idx <= 1) { 15678 idx++; 15679 } else { 15680 idx--; 15681 } 15682 } catch(NumberFormatException e) { 15683 } 15684 } 15685 } 15686 } 15687 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15688 return prefix + idxStr; 15689 } 15690 15691 private File getNextCodePath(File targetDir, String packageName) { 15692 File result; 15693 SecureRandom random = new SecureRandom(); 15694 byte[] bytes = new byte[16]; 15695 do { 15696 random.nextBytes(bytes); 15697 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15698 result = new File(targetDir, packageName + "-" + suffix); 15699 } while (result.exists()); 15700 return result; 15701 } 15702 15703 // Utility method that returns the relative package path with respect 15704 // to the installation directory. Like say for /data/data/com.test-1.apk 15705 // string com.test-1 is returned. 15706 static String deriveCodePathName(String codePath) { 15707 if (codePath == null) { 15708 return null; 15709 } 15710 final File codeFile = new File(codePath); 15711 final String name = codeFile.getName(); 15712 if (codeFile.isDirectory()) { 15713 return name; 15714 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15715 final int lastDot = name.lastIndexOf('.'); 15716 return name.substring(0, lastDot); 15717 } else { 15718 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15719 return null; 15720 } 15721 } 15722 15723 static class PackageInstalledInfo { 15724 String name; 15725 int uid; 15726 // The set of users that originally had this package installed. 15727 int[] origUsers; 15728 // The set of users that now have this package installed. 15729 int[] newUsers; 15730 PackageParser.Package pkg; 15731 int returnCode; 15732 String returnMsg; 15733 PackageRemovedInfo removedInfo; 15734 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15735 15736 public void setError(int code, String msg) { 15737 setReturnCode(code); 15738 setReturnMessage(msg); 15739 Slog.w(TAG, msg); 15740 } 15741 15742 public void setError(String msg, PackageParserException e) { 15743 setReturnCode(e.error); 15744 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15745 Slog.w(TAG, msg, e); 15746 } 15747 15748 public void setError(String msg, PackageManagerException e) { 15749 returnCode = e.error; 15750 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15751 Slog.w(TAG, msg, e); 15752 } 15753 15754 public void setReturnCode(int returnCode) { 15755 this.returnCode = returnCode; 15756 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15757 for (int i = 0; i < childCount; i++) { 15758 addedChildPackages.valueAt(i).returnCode = returnCode; 15759 } 15760 } 15761 15762 private void setReturnMessage(String returnMsg) { 15763 this.returnMsg = returnMsg; 15764 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15765 for (int i = 0; i < childCount; i++) { 15766 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15767 } 15768 } 15769 15770 // In some error cases we want to convey more info back to the observer 15771 String origPackage; 15772 String origPermission; 15773 } 15774 15775 /* 15776 * Install a non-existing package. 15777 */ 15778 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15779 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15780 PackageInstalledInfo res, int installReason) { 15781 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15782 15783 // Remember this for later, in case we need to rollback this install 15784 String pkgName = pkg.packageName; 15785 15786 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15787 15788 synchronized(mPackages) { 15789 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15790 if (renamedPackage != null) { 15791 // A package with the same name is already installed, though 15792 // it has been renamed to an older name. The package we 15793 // are trying to install should be installed as an update to 15794 // the existing one, but that has not been requested, so bail. 15795 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15796 + " without first uninstalling package running as " 15797 + renamedPackage); 15798 return; 15799 } 15800 if (mPackages.containsKey(pkgName)) { 15801 // Don't allow installation over an existing package with the same name. 15802 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15803 + " without first uninstalling."); 15804 return; 15805 } 15806 } 15807 15808 try { 15809 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15810 System.currentTimeMillis(), user); 15811 15812 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15813 15814 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15815 prepareAppDataAfterInstallLIF(newPackage); 15816 15817 } else { 15818 // Remove package from internal structures, but keep around any 15819 // data that might have already existed 15820 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15821 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15822 } 15823 } catch (PackageManagerException e) { 15824 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15825 } 15826 15827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15828 } 15829 15830 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15831 // Can't rotate keys during boot or if sharedUser. 15832 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15833 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15834 return false; 15835 } 15836 // app is using upgradeKeySets; make sure all are valid 15837 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15838 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15839 for (int i = 0; i < upgradeKeySets.length; i++) { 15840 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15841 Slog.wtf(TAG, "Package " 15842 + (oldPs.name != null ? oldPs.name : "<null>") 15843 + " contains upgrade-key-set reference to unknown key-set: " 15844 + upgradeKeySets[i] 15845 + " reverting to signatures check."); 15846 return false; 15847 } 15848 } 15849 return true; 15850 } 15851 15852 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15853 // Upgrade keysets are being used. Determine if new package has a superset of the 15854 // required keys. 15855 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15856 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15857 for (int i = 0; i < upgradeKeySets.length; i++) { 15858 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15859 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15860 return true; 15861 } 15862 } 15863 return false; 15864 } 15865 15866 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15867 try (DigestInputStream digestStream = 15868 new DigestInputStream(new FileInputStream(file), digest)) { 15869 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15870 } 15871 } 15872 15873 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15874 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15875 int installReason) { 15876 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15877 15878 final PackageParser.Package oldPackage; 15879 final String pkgName = pkg.packageName; 15880 final int[] allUsers; 15881 final int[] installedUsers; 15882 15883 synchronized(mPackages) { 15884 oldPackage = mPackages.get(pkgName); 15885 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15886 15887 // don't allow upgrade to target a release SDK from a pre-release SDK 15888 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15889 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15890 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15891 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15892 if (oldTargetsPreRelease 15893 && !newTargetsPreRelease 15894 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15895 Slog.w(TAG, "Can't install package targeting released sdk"); 15896 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15897 return; 15898 } 15899 15900 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15901 15902 // don't allow an upgrade from full to ephemeral 15903 if (isInstantApp && !ps.getInstantApp(user.getIdentifier())) { 15904 // can't downgrade from full to instant 15905 Slog.w(TAG, "Can't replace app with instant app: " + pkgName); 15906 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15907 return; 15908 } 15909 15910 // verify signatures are valid 15911 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15912 if (!checkUpgradeKeySetLP(ps, pkg)) { 15913 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15914 "New package not signed by keys specified by upgrade-keysets: " 15915 + pkgName); 15916 return; 15917 } 15918 } else { 15919 // default to original signature matching 15920 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15921 != PackageManager.SIGNATURE_MATCH) { 15922 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15923 "New package has a different signature: " + pkgName); 15924 return; 15925 } 15926 } 15927 15928 // don't allow a system upgrade unless the upgrade hash matches 15929 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15930 byte[] digestBytes = null; 15931 try { 15932 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15933 updateDigest(digest, new File(pkg.baseCodePath)); 15934 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15935 for (String path : pkg.splitCodePaths) { 15936 updateDigest(digest, new File(path)); 15937 } 15938 } 15939 digestBytes = digest.digest(); 15940 } catch (NoSuchAlgorithmException | IOException e) { 15941 res.setError(INSTALL_FAILED_INVALID_APK, 15942 "Could not compute hash: " + pkgName); 15943 return; 15944 } 15945 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15946 res.setError(INSTALL_FAILED_INVALID_APK, 15947 "New package fails restrict-update check: " + pkgName); 15948 return; 15949 } 15950 // retain upgrade restriction 15951 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15952 } 15953 15954 // Check for shared user id changes 15955 String invalidPackageName = 15956 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15957 if (invalidPackageName != null) { 15958 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15959 "Package " + invalidPackageName + " tried to change user " 15960 + oldPackage.mSharedUserId); 15961 return; 15962 } 15963 15964 // In case of rollback, remember per-user/profile install state 15965 allUsers = sUserManager.getUserIds(); 15966 installedUsers = ps.queryInstalledUsers(allUsers, true); 15967 } 15968 15969 // Update what is removed 15970 res.removedInfo = new PackageRemovedInfo(); 15971 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15972 res.removedInfo.removedPackage = oldPackage.packageName; 15973 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15974 res.removedInfo.isUpdate = true; 15975 res.removedInfo.origUsers = installedUsers; 15976 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15977 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15978 for (int i = 0; i < installedUsers.length; i++) { 15979 final int userId = installedUsers[i]; 15980 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15981 } 15982 15983 final int childCount = (oldPackage.childPackages != null) 15984 ? oldPackage.childPackages.size() : 0; 15985 for (int i = 0; i < childCount; i++) { 15986 boolean childPackageUpdated = false; 15987 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15988 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15989 if (res.addedChildPackages != null) { 15990 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15991 if (childRes != null) { 15992 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15993 childRes.removedInfo.removedPackage = childPkg.packageName; 15994 childRes.removedInfo.isUpdate = true; 15995 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15996 childPackageUpdated = true; 15997 } 15998 } 15999 if (!childPackageUpdated) { 16000 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16001 childRemovedRes.removedPackage = childPkg.packageName; 16002 childRemovedRes.isUpdate = false; 16003 childRemovedRes.dataRemoved = true; 16004 synchronized (mPackages) { 16005 if (childPs != null) { 16006 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16007 } 16008 } 16009 if (res.removedInfo.removedChildPackages == null) { 16010 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16011 } 16012 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16013 } 16014 } 16015 16016 boolean sysPkg = (isSystemApp(oldPackage)); 16017 if (sysPkg) { 16018 // Set the system/privileged flags as needed 16019 final boolean privileged = 16020 (oldPackage.applicationInfo.privateFlags 16021 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16022 final int systemPolicyFlags = policyFlags 16023 | PackageParser.PARSE_IS_SYSTEM 16024 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16025 16026 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16027 user, allUsers, installerPackageName, res, installReason); 16028 } else { 16029 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16030 user, allUsers, installerPackageName, res, installReason); 16031 } 16032 } 16033 16034 public List<String> getPreviousCodePaths(String packageName) { 16035 final PackageSetting ps = mSettings.mPackages.get(packageName); 16036 final List<String> result = new ArrayList<String>(); 16037 if (ps != null && ps.oldCodePaths != null) { 16038 result.addAll(ps.oldCodePaths); 16039 } 16040 return result; 16041 } 16042 16043 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16044 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16045 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16046 int installReason) { 16047 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16048 + deletedPackage); 16049 16050 String pkgName = deletedPackage.packageName; 16051 boolean deletedPkg = true; 16052 boolean addedPkg = false; 16053 boolean updatedSettings = false; 16054 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16055 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16056 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16057 16058 final long origUpdateTime = (pkg.mExtras != null) 16059 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16060 16061 // First delete the existing package while retaining the data directory 16062 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16063 res.removedInfo, true, pkg)) { 16064 // If the existing package wasn't successfully deleted 16065 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16066 deletedPkg = false; 16067 } else { 16068 // Successfully deleted the old package; proceed with replace. 16069 16070 // If deleted package lived in a container, give users a chance to 16071 // relinquish resources before killing. 16072 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16073 if (DEBUG_INSTALL) { 16074 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16075 } 16076 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16077 final ArrayList<String> pkgList = new ArrayList<String>(1); 16078 pkgList.add(deletedPackage.applicationInfo.packageName); 16079 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16080 } 16081 16082 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16083 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16084 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16085 16086 try { 16087 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16088 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16089 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16090 installReason); 16091 16092 // Update the in-memory copy of the previous code paths. 16093 PackageSetting ps = mSettings.mPackages.get(pkgName); 16094 if (!killApp) { 16095 if (ps.oldCodePaths == null) { 16096 ps.oldCodePaths = new ArraySet<>(); 16097 } 16098 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16099 if (deletedPackage.splitCodePaths != null) { 16100 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16101 } 16102 } else { 16103 ps.oldCodePaths = null; 16104 } 16105 if (ps.childPackageNames != null) { 16106 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16107 final String childPkgName = ps.childPackageNames.get(i); 16108 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16109 childPs.oldCodePaths = ps.oldCodePaths; 16110 } 16111 } 16112 // set instant app status, but, only if it's explicitly specified 16113 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16114 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16115 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16116 prepareAppDataAfterInstallLIF(newPackage); 16117 addedPkg = true; 16118 } catch (PackageManagerException e) { 16119 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16120 } 16121 } 16122 16123 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16124 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16125 16126 // Revert all internal state mutations and added folders for the failed install 16127 if (addedPkg) { 16128 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16129 res.removedInfo, true, null); 16130 } 16131 16132 // Restore the old package 16133 if (deletedPkg) { 16134 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16135 File restoreFile = new File(deletedPackage.codePath); 16136 // Parse old package 16137 boolean oldExternal = isExternal(deletedPackage); 16138 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16139 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16140 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16141 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16142 try { 16143 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16144 null); 16145 } catch (PackageManagerException e) { 16146 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16147 + e.getMessage()); 16148 return; 16149 } 16150 16151 synchronized (mPackages) { 16152 // Ensure the installer package name up to date 16153 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16154 16155 // Update permissions for restored package 16156 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16157 16158 mSettings.writeLPr(); 16159 } 16160 16161 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16162 } 16163 } else { 16164 synchronized (mPackages) { 16165 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16166 if (ps != null) { 16167 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16168 if (res.removedInfo.removedChildPackages != null) { 16169 final int childCount = res.removedInfo.removedChildPackages.size(); 16170 // Iterate in reverse as we may modify the collection 16171 for (int i = childCount - 1; i >= 0; i--) { 16172 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16173 if (res.addedChildPackages.containsKey(childPackageName)) { 16174 res.removedInfo.removedChildPackages.removeAt(i); 16175 } else { 16176 PackageRemovedInfo childInfo = res.removedInfo 16177 .removedChildPackages.valueAt(i); 16178 childInfo.removedForAllUsers = mPackages.get( 16179 childInfo.removedPackage) == null; 16180 } 16181 } 16182 } 16183 } 16184 } 16185 } 16186 } 16187 16188 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16189 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16190 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16191 int installReason) { 16192 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16193 + ", old=" + deletedPackage); 16194 16195 final boolean disabledSystem; 16196 16197 // Remove existing system package 16198 removePackageLI(deletedPackage, true); 16199 16200 synchronized (mPackages) { 16201 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16202 } 16203 if (!disabledSystem) { 16204 // We didn't need to disable the .apk as a current system package, 16205 // which means we are replacing another update that is already 16206 // installed. We need to make sure to delete the older one's .apk. 16207 res.removedInfo.args = createInstallArgsForExisting(0, 16208 deletedPackage.applicationInfo.getCodePath(), 16209 deletedPackage.applicationInfo.getResourcePath(), 16210 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16211 } else { 16212 res.removedInfo.args = null; 16213 } 16214 16215 // Successfully disabled the old package. Now proceed with re-installation 16216 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16217 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16218 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16219 16220 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16221 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16222 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16223 16224 PackageParser.Package newPackage = null; 16225 try { 16226 // Add the package to the internal data structures 16227 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16228 16229 // Set the update and install times 16230 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16231 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16232 System.currentTimeMillis()); 16233 16234 // Update the package dynamic state if succeeded 16235 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16236 // Now that the install succeeded make sure we remove data 16237 // directories for any child package the update removed. 16238 final int deletedChildCount = (deletedPackage.childPackages != null) 16239 ? deletedPackage.childPackages.size() : 0; 16240 final int newChildCount = (newPackage.childPackages != null) 16241 ? newPackage.childPackages.size() : 0; 16242 for (int i = 0; i < deletedChildCount; i++) { 16243 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16244 boolean childPackageDeleted = true; 16245 for (int j = 0; j < newChildCount; j++) { 16246 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16247 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16248 childPackageDeleted = false; 16249 break; 16250 } 16251 } 16252 if (childPackageDeleted) { 16253 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16254 deletedChildPkg.packageName); 16255 if (ps != null && res.removedInfo.removedChildPackages != null) { 16256 PackageRemovedInfo removedChildRes = res.removedInfo 16257 .removedChildPackages.get(deletedChildPkg.packageName); 16258 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16259 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16260 } 16261 } 16262 } 16263 16264 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16265 installReason); 16266 prepareAppDataAfterInstallLIF(newPackage); 16267 } 16268 } catch (PackageManagerException e) { 16269 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16270 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16271 } 16272 16273 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16274 // Re installation failed. Restore old information 16275 // Remove new pkg information 16276 if (newPackage != null) { 16277 removeInstalledPackageLI(newPackage, true); 16278 } 16279 // Add back the old system package 16280 try { 16281 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16282 } catch (PackageManagerException e) { 16283 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16284 } 16285 16286 synchronized (mPackages) { 16287 if (disabledSystem) { 16288 enableSystemPackageLPw(deletedPackage); 16289 } 16290 16291 // Ensure the installer package name up to date 16292 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16293 16294 // Update permissions for restored package 16295 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16296 16297 mSettings.writeLPr(); 16298 } 16299 16300 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16301 + " after failed upgrade"); 16302 } 16303 } 16304 16305 /** 16306 * Checks whether the parent or any of the child packages have a change shared 16307 * user. For a package to be a valid update the shred users of the parent and 16308 * the children should match. We may later support changing child shared users. 16309 * @param oldPkg The updated package. 16310 * @param newPkg The update package. 16311 * @return The shared user that change between the versions. 16312 */ 16313 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16314 PackageParser.Package newPkg) { 16315 // Check parent shared user 16316 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16317 return newPkg.packageName; 16318 } 16319 // Check child shared users 16320 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16321 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16322 for (int i = 0; i < newChildCount; i++) { 16323 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16324 // If this child was present, did it have the same shared user? 16325 for (int j = 0; j < oldChildCount; j++) { 16326 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16327 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16328 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16329 return newChildPkg.packageName; 16330 } 16331 } 16332 } 16333 return null; 16334 } 16335 16336 private void removeNativeBinariesLI(PackageSetting ps) { 16337 // Remove the lib path for the parent package 16338 if (ps != null) { 16339 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16340 // Remove the lib path for the child packages 16341 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16342 for (int i = 0; i < childCount; i++) { 16343 PackageSetting childPs = null; 16344 synchronized (mPackages) { 16345 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16346 } 16347 if (childPs != null) { 16348 NativeLibraryHelper.removeNativeBinariesLI(childPs 16349 .legacyNativeLibraryPathString); 16350 } 16351 } 16352 } 16353 } 16354 16355 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16356 // Enable the parent package 16357 mSettings.enableSystemPackageLPw(pkg.packageName); 16358 // Enable the child packages 16359 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16360 for (int i = 0; i < childCount; i++) { 16361 PackageParser.Package childPkg = pkg.childPackages.get(i); 16362 mSettings.enableSystemPackageLPw(childPkg.packageName); 16363 } 16364 } 16365 16366 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16367 PackageParser.Package newPkg) { 16368 // Disable the parent package (parent always replaced) 16369 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16370 // Disable the child packages 16371 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16372 for (int i = 0; i < childCount; i++) { 16373 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16374 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16375 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16376 } 16377 return disabled; 16378 } 16379 16380 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16381 String installerPackageName) { 16382 // Enable the parent package 16383 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16384 // Enable the child packages 16385 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16386 for (int i = 0; i < childCount; i++) { 16387 PackageParser.Package childPkg = pkg.childPackages.get(i); 16388 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16389 } 16390 } 16391 16392 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16393 // Collect all used permissions in the UID 16394 ArraySet<String> usedPermissions = new ArraySet<>(); 16395 final int packageCount = su.packages.size(); 16396 for (int i = 0; i < packageCount; i++) { 16397 PackageSetting ps = su.packages.valueAt(i); 16398 if (ps.pkg == null) { 16399 continue; 16400 } 16401 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16402 for (int j = 0; j < requestedPermCount; j++) { 16403 String permission = ps.pkg.requestedPermissions.get(j); 16404 BasePermission bp = mSettings.mPermissions.get(permission); 16405 if (bp != null) { 16406 usedPermissions.add(permission); 16407 } 16408 } 16409 } 16410 16411 PermissionsState permissionsState = su.getPermissionsState(); 16412 // Prune install permissions 16413 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16414 final int installPermCount = installPermStates.size(); 16415 for (int i = installPermCount - 1; i >= 0; i--) { 16416 PermissionState permissionState = installPermStates.get(i); 16417 if (!usedPermissions.contains(permissionState.getName())) { 16418 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16419 if (bp != null) { 16420 permissionsState.revokeInstallPermission(bp); 16421 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16422 PackageManager.MASK_PERMISSION_FLAGS, 0); 16423 } 16424 } 16425 } 16426 16427 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16428 16429 // Prune runtime permissions 16430 for (int userId : allUserIds) { 16431 List<PermissionState> runtimePermStates = permissionsState 16432 .getRuntimePermissionStates(userId); 16433 final int runtimePermCount = runtimePermStates.size(); 16434 for (int i = runtimePermCount - 1; i >= 0; i--) { 16435 PermissionState permissionState = runtimePermStates.get(i); 16436 if (!usedPermissions.contains(permissionState.getName())) { 16437 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16438 if (bp != null) { 16439 permissionsState.revokeRuntimePermission(bp, userId); 16440 permissionsState.updatePermissionFlags(bp, userId, 16441 PackageManager.MASK_PERMISSION_FLAGS, 0); 16442 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16443 runtimePermissionChangedUserIds, userId); 16444 } 16445 } 16446 } 16447 } 16448 16449 return runtimePermissionChangedUserIds; 16450 } 16451 16452 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16453 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16454 // Update the parent package setting 16455 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16456 res, user, installReason); 16457 // Update the child packages setting 16458 final int childCount = (newPackage.childPackages != null) 16459 ? newPackage.childPackages.size() : 0; 16460 for (int i = 0; i < childCount; i++) { 16461 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16462 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16463 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16464 childRes.origUsers, childRes, user, installReason); 16465 } 16466 } 16467 16468 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16469 String installerPackageName, int[] allUsers, int[] installedForUsers, 16470 PackageInstalledInfo res, UserHandle user, int installReason) { 16471 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16472 16473 String pkgName = newPackage.packageName; 16474 synchronized (mPackages) { 16475 //write settings. the installStatus will be incomplete at this stage. 16476 //note that the new package setting would have already been 16477 //added to mPackages. It hasn't been persisted yet. 16478 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16479 // TODO: Remove this write? It's also written at the end of this method 16480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16481 mSettings.writeLPr(); 16482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16483 } 16484 16485 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16486 synchronized (mPackages) { 16487 updatePermissionsLPw(newPackage.packageName, newPackage, 16488 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16489 ? UPDATE_PERMISSIONS_ALL : 0)); 16490 // For system-bundled packages, we assume that installing an upgraded version 16491 // of the package implies that the user actually wants to run that new code, 16492 // so we enable the package. 16493 PackageSetting ps = mSettings.mPackages.get(pkgName); 16494 final int userId = user.getIdentifier(); 16495 if (ps != null) { 16496 if (isSystemApp(newPackage)) { 16497 if (DEBUG_INSTALL) { 16498 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16499 } 16500 // Enable system package for requested users 16501 if (res.origUsers != null) { 16502 for (int origUserId : res.origUsers) { 16503 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16504 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16505 origUserId, installerPackageName); 16506 } 16507 } 16508 } 16509 // Also convey the prior install/uninstall state 16510 if (allUsers != null && installedForUsers != null) { 16511 for (int currentUserId : allUsers) { 16512 final boolean installed = ArrayUtils.contains( 16513 installedForUsers, currentUserId); 16514 if (DEBUG_INSTALL) { 16515 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16516 } 16517 ps.setInstalled(installed, currentUserId); 16518 } 16519 // these install state changes will be persisted in the 16520 // upcoming call to mSettings.writeLPr(). 16521 } 16522 } 16523 // It's implied that when a user requests installation, they want the app to be 16524 // installed and enabled. 16525 if (userId != UserHandle.USER_ALL) { 16526 ps.setInstalled(true, userId); 16527 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16528 } 16529 16530 // When replacing an existing package, preserve the original install reason for all 16531 // users that had the package installed before. 16532 final Set<Integer> previousUserIds = new ArraySet<>(); 16533 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16534 final int installReasonCount = res.removedInfo.installReasons.size(); 16535 for (int i = 0; i < installReasonCount; i++) { 16536 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16537 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16538 ps.setInstallReason(previousInstallReason, previousUserId); 16539 previousUserIds.add(previousUserId); 16540 } 16541 } 16542 16543 // Set install reason for users that are having the package newly installed. 16544 if (userId == UserHandle.USER_ALL) { 16545 for (int currentUserId : sUserManager.getUserIds()) { 16546 if (!previousUserIds.contains(currentUserId)) { 16547 ps.setInstallReason(installReason, currentUserId); 16548 } 16549 } 16550 } else if (!previousUserIds.contains(userId)) { 16551 ps.setInstallReason(installReason, userId); 16552 } 16553 mSettings.writeKernelMappingLPr(ps); 16554 } 16555 res.name = pkgName; 16556 res.uid = newPackage.applicationInfo.uid; 16557 res.pkg = newPackage; 16558 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16559 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16560 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16561 //to update install status 16562 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16563 mSettings.writeLPr(); 16564 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16565 } 16566 16567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16568 } 16569 16570 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16571 try { 16572 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16573 installPackageLI(args, res); 16574 } finally { 16575 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16576 } 16577 } 16578 16579 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16580 final int installFlags = args.installFlags; 16581 final String installerPackageName = args.installerPackageName; 16582 final String volumeUuid = args.volumeUuid; 16583 final File tmpPackageFile = new File(args.getCodePath()); 16584 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16585 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16586 || (args.volumeUuid != null)); 16587 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16588 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16589 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16590 boolean replace = false; 16591 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16592 if (args.move != null) { 16593 // moving a complete application; perform an initial scan on the new install location 16594 scanFlags |= SCAN_INITIAL; 16595 } 16596 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16597 scanFlags |= SCAN_DONT_KILL_APP; 16598 } 16599 if (instantApp) { 16600 scanFlags |= SCAN_AS_INSTANT_APP; 16601 } 16602 if (fullApp) { 16603 scanFlags |= SCAN_AS_FULL_APP; 16604 } 16605 16606 // Result object to be returned 16607 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16608 16609 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16610 16611 // Sanity check 16612 if (instantApp && (forwardLocked || onExternal)) { 16613 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16614 + " external=" + onExternal); 16615 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16616 return; 16617 } 16618 16619 // Retrieve PackageSettings and parse package 16620 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16621 | PackageParser.PARSE_ENFORCE_CODE 16622 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16623 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16624 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16625 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16626 PackageParser pp = new PackageParser(); 16627 pp.setSeparateProcesses(mSeparateProcesses); 16628 pp.setDisplayMetrics(mMetrics); 16629 16630 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16631 final PackageParser.Package pkg; 16632 try { 16633 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16634 } catch (PackageParserException e) { 16635 res.setError("Failed parse during installPackageLI", e); 16636 return; 16637 } finally { 16638 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16639 } 16640 16641 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16642 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16643 Slog.w(TAG, "Instant app package " + pkg.packageName 16644 + " does not target O, this will be a fatal error."); 16645 // STOPSHIP: Make this a fatal error 16646 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16647 } 16648 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16649 Slog.w(TAG, "Instant app package " + pkg.packageName 16650 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16651 // STOPSHIP: Make this a fatal error 16652 pkg.applicationInfo.targetSandboxVersion = 2; 16653 } 16654 16655 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16656 // Static shared libraries have synthetic package names 16657 renameStaticSharedLibraryPackage(pkg); 16658 16659 // No static shared libs on external storage 16660 if (onExternal) { 16661 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16662 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16663 "Packages declaring static-shared libs cannot be updated"); 16664 return; 16665 } 16666 } 16667 16668 // If we are installing a clustered package add results for the children 16669 if (pkg.childPackages != null) { 16670 synchronized (mPackages) { 16671 final int childCount = pkg.childPackages.size(); 16672 for (int i = 0; i < childCount; i++) { 16673 PackageParser.Package childPkg = pkg.childPackages.get(i); 16674 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16675 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16676 childRes.pkg = childPkg; 16677 childRes.name = childPkg.packageName; 16678 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16679 if (childPs != null) { 16680 childRes.origUsers = childPs.queryInstalledUsers( 16681 sUserManager.getUserIds(), true); 16682 } 16683 if ((mPackages.containsKey(childPkg.packageName))) { 16684 childRes.removedInfo = new PackageRemovedInfo(); 16685 childRes.removedInfo.removedPackage = childPkg.packageName; 16686 } 16687 if (res.addedChildPackages == null) { 16688 res.addedChildPackages = new ArrayMap<>(); 16689 } 16690 res.addedChildPackages.put(childPkg.packageName, childRes); 16691 } 16692 } 16693 } 16694 16695 // If package doesn't declare API override, mark that we have an install 16696 // time CPU ABI override. 16697 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16698 pkg.cpuAbiOverride = args.abiOverride; 16699 } 16700 16701 String pkgName = res.name = pkg.packageName; 16702 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16703 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16704 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16705 return; 16706 } 16707 } 16708 16709 try { 16710 // either use what we've been given or parse directly from the APK 16711 if (args.certificates != null) { 16712 try { 16713 PackageParser.populateCertificates(pkg, args.certificates); 16714 } catch (PackageParserException e) { 16715 // there was something wrong with the certificates we were given; 16716 // try to pull them from the APK 16717 PackageParser.collectCertificates(pkg, parseFlags); 16718 } 16719 } else { 16720 PackageParser.collectCertificates(pkg, parseFlags); 16721 } 16722 } catch (PackageParserException e) { 16723 res.setError("Failed collect during installPackageLI", e); 16724 return; 16725 } 16726 16727 // Get rid of all references to package scan path via parser. 16728 pp = null; 16729 String oldCodePath = null; 16730 boolean systemApp = false; 16731 synchronized (mPackages) { 16732 // Check if installing already existing package 16733 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16734 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16735 if (pkg.mOriginalPackages != null 16736 && pkg.mOriginalPackages.contains(oldName) 16737 && mPackages.containsKey(oldName)) { 16738 // This package is derived from an original package, 16739 // and this device has been updating from that original 16740 // name. We must continue using the original name, so 16741 // rename the new package here. 16742 pkg.setPackageName(oldName); 16743 pkgName = pkg.packageName; 16744 replace = true; 16745 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16746 + oldName + " pkgName=" + pkgName); 16747 } else if (mPackages.containsKey(pkgName)) { 16748 // This package, under its official name, already exists 16749 // on the device; we should replace it. 16750 replace = true; 16751 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16752 } 16753 16754 // Child packages are installed through the parent package 16755 if (pkg.parentPackage != null) { 16756 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16757 "Package " + pkg.packageName + " is child of package " 16758 + pkg.parentPackage.parentPackage + ". Child packages " 16759 + "can be updated only through the parent package."); 16760 return; 16761 } 16762 16763 if (replace) { 16764 // Prevent apps opting out from runtime permissions 16765 PackageParser.Package oldPackage = mPackages.get(pkgName); 16766 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16767 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16768 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16769 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16770 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16771 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16772 + " doesn't support runtime permissions but the old" 16773 + " target SDK " + oldTargetSdk + " does."); 16774 return; 16775 } 16776 16777 // Prevent installing of child packages 16778 if (oldPackage.parentPackage != null) { 16779 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16780 "Package " + pkg.packageName + " is child of package " 16781 + oldPackage.parentPackage + ". Child packages " 16782 + "can be updated only through the parent package."); 16783 return; 16784 } 16785 } 16786 } 16787 16788 PackageSetting ps = mSettings.mPackages.get(pkgName); 16789 if (ps != null) { 16790 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16791 16792 // Static shared libs have same package with different versions where 16793 // we internally use a synthetic package name to allow multiple versions 16794 // of the same package, therefore we need to compare signatures against 16795 // the package setting for the latest library version. 16796 PackageSetting signatureCheckPs = ps; 16797 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16798 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16799 if (libraryEntry != null) { 16800 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16801 } 16802 } 16803 16804 // Quick sanity check that we're signed correctly if updating; 16805 // we'll check this again later when scanning, but we want to 16806 // bail early here before tripping over redefined permissions. 16807 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16808 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16809 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16810 + pkg.packageName + " upgrade keys do not match the " 16811 + "previously installed version"); 16812 return; 16813 } 16814 } else { 16815 try { 16816 verifySignaturesLP(signatureCheckPs, pkg); 16817 } catch (PackageManagerException e) { 16818 res.setError(e.error, e.getMessage()); 16819 return; 16820 } 16821 } 16822 16823 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16824 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16825 systemApp = (ps.pkg.applicationInfo.flags & 16826 ApplicationInfo.FLAG_SYSTEM) != 0; 16827 } 16828 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16829 } 16830 16831 // Check whether the newly-scanned package wants to define an already-defined perm 16832 int N = pkg.permissions.size(); 16833 for (int i = N-1; i >= 0; i--) { 16834 PackageParser.Permission perm = pkg.permissions.get(i); 16835 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16836 if (bp != null) { 16837 // If the defining package is signed with our cert, it's okay. This 16838 // also includes the "updating the same package" case, of course. 16839 // "updating same package" could also involve key-rotation. 16840 final boolean sigsOk; 16841 if (bp.sourcePackage.equals(pkg.packageName) 16842 && (bp.packageSetting instanceof PackageSetting) 16843 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16844 scanFlags))) { 16845 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16846 } else { 16847 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16848 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16849 } 16850 if (!sigsOk) { 16851 // If the owning package is the system itself, we log but allow 16852 // install to proceed; we fail the install on all other permission 16853 // redefinitions. 16854 if (!bp.sourcePackage.equals("android")) { 16855 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16856 + pkg.packageName + " attempting to redeclare permission " 16857 + perm.info.name + " already owned by " + bp.sourcePackage); 16858 res.origPermission = perm.info.name; 16859 res.origPackage = bp.sourcePackage; 16860 return; 16861 } else { 16862 Slog.w(TAG, "Package " + pkg.packageName 16863 + " attempting to redeclare system permission " 16864 + perm.info.name + "; ignoring new declaration"); 16865 pkg.permissions.remove(i); 16866 } 16867 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16868 // Prevent apps to change protection level to dangerous from any other 16869 // type as this would allow a privilege escalation where an app adds a 16870 // normal/signature permission in other app's group and later redefines 16871 // it as dangerous leading to the group auto-grant. 16872 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16873 == PermissionInfo.PROTECTION_DANGEROUS) { 16874 if (bp != null && !bp.isRuntime()) { 16875 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16876 + "non-runtime permission " + perm.info.name 16877 + " to runtime; keeping old protection level"); 16878 perm.info.protectionLevel = bp.protectionLevel; 16879 } 16880 } 16881 } 16882 } 16883 } 16884 } 16885 16886 if (systemApp) { 16887 if (onExternal) { 16888 // Abort update; system app can't be replaced with app on sdcard 16889 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16890 "Cannot install updates to system apps on sdcard"); 16891 return; 16892 } else if (instantApp) { 16893 // Abort update; system app can't be replaced with an instant app 16894 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16895 "Cannot update a system app with an instant app"); 16896 return; 16897 } 16898 } 16899 16900 if (args.move != null) { 16901 // We did an in-place move, so dex is ready to roll 16902 scanFlags |= SCAN_NO_DEX; 16903 scanFlags |= SCAN_MOVE; 16904 16905 synchronized (mPackages) { 16906 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16907 if (ps == null) { 16908 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16909 "Missing settings for moved package " + pkgName); 16910 } 16911 16912 // We moved the entire application as-is, so bring over the 16913 // previously derived ABI information. 16914 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16915 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16916 } 16917 16918 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16919 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16920 scanFlags |= SCAN_NO_DEX; 16921 16922 try { 16923 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16924 args.abiOverride : pkg.cpuAbiOverride); 16925 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16926 true /*extractLibs*/, mAppLib32InstallDir); 16927 } catch (PackageManagerException pme) { 16928 Slog.e(TAG, "Error deriving application ABI", pme); 16929 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16930 return; 16931 } 16932 16933 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16934 // Do not run PackageDexOptimizer through the local performDexOpt 16935 // method because `pkg` may not be in `mPackages` yet. 16936 // 16937 // Also, don't fail application installs if the dexopt step fails. 16938 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16939 null /* instructionSets */, false /* checkProfiles */, 16940 getCompilerFilterForReason(REASON_INSTALL), 16941 getOrCreateCompilerPackageStats(pkg)); 16942 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16943 16944 // Notify BackgroundDexOptJobService that the package has been changed. 16945 // If this is an update of a package which used to fail to compile, 16946 // BDOS will remove it from its blacklist. 16947 // TODO: Layering violation 16948 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16949 } 16950 16951 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16952 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16953 return; 16954 } 16955 16956 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16957 16958 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16959 "installPackageLI")) { 16960 if (replace) { 16961 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16962 // Static libs have a synthetic package name containing the version 16963 // and cannot be updated as an update would get a new package name, 16964 // unless this is the exact same version code which is useful for 16965 // development. 16966 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16967 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16968 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16969 + "static-shared libs cannot be updated"); 16970 return; 16971 } 16972 } 16973 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16974 installerPackageName, res, args.installReason); 16975 } else { 16976 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16977 args.user, installerPackageName, volumeUuid, res, args.installReason); 16978 } 16979 } 16980 synchronized (mPackages) { 16981 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16982 if (ps != null) { 16983 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16984 } 16985 16986 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16987 for (int i = 0; i < childCount; i++) { 16988 PackageParser.Package childPkg = pkg.childPackages.get(i); 16989 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16990 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16991 if (childPs != null) { 16992 childRes.newUsers = childPs.queryInstalledUsers( 16993 sUserManager.getUserIds(), true); 16994 } 16995 } 16996 16997 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16998 updateSequenceNumberLP(pkgName, res.newUsers); 16999 } 17000 } 17001 } 17002 17003 private void startIntentFilterVerifications(int userId, boolean replacing, 17004 PackageParser.Package pkg) { 17005 if (mIntentFilterVerifierComponent == null) { 17006 Slog.w(TAG, "No IntentFilter verification will not be done as " 17007 + "there is no IntentFilterVerifier available!"); 17008 return; 17009 } 17010 17011 final int verifierUid = getPackageUid( 17012 mIntentFilterVerifierComponent.getPackageName(), 17013 MATCH_DEBUG_TRIAGED_MISSING, 17014 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17015 17016 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17017 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17018 mHandler.sendMessage(msg); 17019 17020 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17021 for (int i = 0; i < childCount; i++) { 17022 PackageParser.Package childPkg = pkg.childPackages.get(i); 17023 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17024 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17025 mHandler.sendMessage(msg); 17026 } 17027 } 17028 17029 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17030 PackageParser.Package pkg) { 17031 int size = pkg.activities.size(); 17032 if (size == 0) { 17033 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17034 "No activity, so no need to verify any IntentFilter!"); 17035 return; 17036 } 17037 17038 final boolean hasDomainURLs = hasDomainURLs(pkg); 17039 if (!hasDomainURLs) { 17040 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17041 "No domain URLs, so no need to verify any IntentFilter!"); 17042 return; 17043 } 17044 17045 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17046 + " if any IntentFilter from the " + size 17047 + " Activities needs verification ..."); 17048 17049 int count = 0; 17050 final String packageName = pkg.packageName; 17051 17052 synchronized (mPackages) { 17053 // If this is a new install and we see that we've already run verification for this 17054 // package, we have nothing to do: it means the state was restored from backup. 17055 if (!replacing) { 17056 IntentFilterVerificationInfo ivi = 17057 mSettings.getIntentFilterVerificationLPr(packageName); 17058 if (ivi != null) { 17059 if (DEBUG_DOMAIN_VERIFICATION) { 17060 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17061 + ivi.getStatusString()); 17062 } 17063 return; 17064 } 17065 } 17066 17067 // If any filters need to be verified, then all need to be. 17068 boolean needToVerify = false; 17069 for (PackageParser.Activity a : pkg.activities) { 17070 for (ActivityIntentInfo filter : a.intents) { 17071 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17072 if (DEBUG_DOMAIN_VERIFICATION) { 17073 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17074 } 17075 needToVerify = true; 17076 break; 17077 } 17078 } 17079 } 17080 17081 if (needToVerify) { 17082 final int verificationId = mIntentFilterVerificationToken++; 17083 for (PackageParser.Activity a : pkg.activities) { 17084 for (ActivityIntentInfo filter : a.intents) { 17085 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17086 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17087 "Verification needed for IntentFilter:" + filter.toString()); 17088 mIntentFilterVerifier.addOneIntentFilterVerification( 17089 verifierUid, userId, verificationId, filter, packageName); 17090 count++; 17091 } 17092 } 17093 } 17094 } 17095 } 17096 17097 if (count > 0) { 17098 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17099 + " IntentFilter verification" + (count > 1 ? "s" : "") 17100 + " for userId:" + userId); 17101 mIntentFilterVerifier.startVerifications(userId); 17102 } else { 17103 if (DEBUG_DOMAIN_VERIFICATION) { 17104 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17105 } 17106 } 17107 } 17108 17109 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17110 final ComponentName cn = filter.activity.getComponentName(); 17111 final String packageName = cn.getPackageName(); 17112 17113 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17114 packageName); 17115 if (ivi == null) { 17116 return true; 17117 } 17118 int status = ivi.getStatus(); 17119 switch (status) { 17120 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17121 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17122 return true; 17123 17124 default: 17125 // Nothing to do 17126 return false; 17127 } 17128 } 17129 17130 private static boolean isMultiArch(ApplicationInfo info) { 17131 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17132 } 17133 17134 private static boolean isExternal(PackageParser.Package pkg) { 17135 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17136 } 17137 17138 private static boolean isExternal(PackageSetting ps) { 17139 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17140 } 17141 17142 private static boolean isSystemApp(PackageParser.Package pkg) { 17143 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17144 } 17145 17146 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17147 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17148 } 17149 17150 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17151 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17152 } 17153 17154 private static boolean isSystemApp(PackageSetting ps) { 17155 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17156 } 17157 17158 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17159 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17160 } 17161 17162 private int packageFlagsToInstallFlags(PackageSetting ps) { 17163 int installFlags = 0; 17164 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17165 // This existing package was an external ASEC install when we have 17166 // the external flag without a UUID 17167 installFlags |= PackageManager.INSTALL_EXTERNAL; 17168 } 17169 if (ps.isForwardLocked()) { 17170 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17171 } 17172 return installFlags; 17173 } 17174 17175 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17176 if (isExternal(pkg)) { 17177 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17178 return StorageManager.UUID_PRIMARY_PHYSICAL; 17179 } else { 17180 return pkg.volumeUuid; 17181 } 17182 } else { 17183 return StorageManager.UUID_PRIVATE_INTERNAL; 17184 } 17185 } 17186 17187 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17188 if (isExternal(pkg)) { 17189 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17190 return mSettings.getExternalVersion(); 17191 } else { 17192 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17193 } 17194 } else { 17195 return mSettings.getInternalVersion(); 17196 } 17197 } 17198 17199 private void deleteTempPackageFiles() { 17200 final FilenameFilter filter = new FilenameFilter() { 17201 public boolean accept(File dir, String name) { 17202 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17203 } 17204 }; 17205 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17206 file.delete(); 17207 } 17208 } 17209 17210 @Override 17211 public void deletePackageAsUser(String packageName, int versionCode, 17212 IPackageDeleteObserver observer, int userId, int flags) { 17213 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17214 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17215 } 17216 17217 @Override 17218 public void deletePackageVersioned(VersionedPackage versionedPackage, 17219 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17220 mContext.enforceCallingOrSelfPermission( 17221 android.Manifest.permission.DELETE_PACKAGES, null); 17222 Preconditions.checkNotNull(versionedPackage); 17223 Preconditions.checkNotNull(observer); 17224 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17225 PackageManager.VERSION_CODE_HIGHEST, 17226 Integer.MAX_VALUE, "versionCode must be >= -1"); 17227 17228 final String packageName = versionedPackage.getPackageName(); 17229 // TODO: We will change version code to long, so in the new API it is long 17230 final int versionCode = (int) versionedPackage.getVersionCode(); 17231 final String internalPackageName; 17232 synchronized (mPackages) { 17233 // Normalize package name to handle renamed packages and static libs 17234 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17235 // TODO: We will change version code to long, so in the new API it is long 17236 (int) versionedPackage.getVersionCode()); 17237 } 17238 17239 final int uid = Binder.getCallingUid(); 17240 if (!isOrphaned(internalPackageName) 17241 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17242 try { 17243 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17244 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17245 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17246 observer.onUserActionRequired(intent); 17247 } catch (RemoteException re) { 17248 } 17249 return; 17250 } 17251 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17252 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17253 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17254 mContext.enforceCallingOrSelfPermission( 17255 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17256 "deletePackage for user " + userId); 17257 } 17258 17259 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17260 try { 17261 observer.onPackageDeleted(packageName, 17262 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17263 } catch (RemoteException re) { 17264 } 17265 return; 17266 } 17267 17268 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17269 try { 17270 observer.onPackageDeleted(packageName, 17271 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17272 } catch (RemoteException re) { 17273 } 17274 return; 17275 } 17276 17277 if (DEBUG_REMOVE) { 17278 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17279 + " deleteAllUsers: " + deleteAllUsers + " version=" 17280 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17281 ? "VERSION_CODE_HIGHEST" : versionCode)); 17282 } 17283 // Queue up an async operation since the package deletion may take a little while. 17284 mHandler.post(new Runnable() { 17285 public void run() { 17286 mHandler.removeCallbacks(this); 17287 int returnCode; 17288 if (!deleteAllUsers) { 17289 returnCode = deletePackageX(internalPackageName, versionCode, 17290 userId, deleteFlags); 17291 } else { 17292 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17293 internalPackageName, users); 17294 // If nobody is blocking uninstall, proceed with delete for all users 17295 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17296 returnCode = deletePackageX(internalPackageName, versionCode, 17297 userId, deleteFlags); 17298 } else { 17299 // Otherwise uninstall individually for users with blockUninstalls=false 17300 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17301 for (int userId : users) { 17302 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17303 returnCode = deletePackageX(internalPackageName, versionCode, 17304 userId, userFlags); 17305 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17306 Slog.w(TAG, "Package delete failed for user " + userId 17307 + ", returnCode " + returnCode); 17308 } 17309 } 17310 } 17311 // The app has only been marked uninstalled for certain users. 17312 // We still need to report that delete was blocked 17313 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17314 } 17315 } 17316 try { 17317 observer.onPackageDeleted(packageName, returnCode, null); 17318 } catch (RemoteException e) { 17319 Log.i(TAG, "Observer no longer exists."); 17320 } //end catch 17321 } //end run 17322 }); 17323 } 17324 17325 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17326 if (pkg.staticSharedLibName != null) { 17327 return pkg.manifestPackageName; 17328 } 17329 return pkg.packageName; 17330 } 17331 17332 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17333 // Handle renamed packages 17334 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17335 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17336 17337 // Is this a static library? 17338 SparseArray<SharedLibraryEntry> versionedLib = 17339 mStaticLibsByDeclaringPackage.get(packageName); 17340 if (versionedLib == null || versionedLib.size() <= 0) { 17341 return packageName; 17342 } 17343 17344 // Figure out which lib versions the caller can see 17345 SparseIntArray versionsCallerCanSee = null; 17346 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17347 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17348 && callingAppId != Process.ROOT_UID) { 17349 versionsCallerCanSee = new SparseIntArray(); 17350 String libName = versionedLib.valueAt(0).info.getName(); 17351 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17352 if (uidPackages != null) { 17353 for (String uidPackage : uidPackages) { 17354 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17355 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17356 if (libIdx >= 0) { 17357 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17358 versionsCallerCanSee.append(libVersion, libVersion); 17359 } 17360 } 17361 } 17362 } 17363 17364 // Caller can see nothing - done 17365 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17366 return packageName; 17367 } 17368 17369 // Find the version the caller can see and the app version code 17370 SharedLibraryEntry highestVersion = null; 17371 final int versionCount = versionedLib.size(); 17372 for (int i = 0; i < versionCount; i++) { 17373 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17374 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17375 libEntry.info.getVersion()) < 0) { 17376 continue; 17377 } 17378 // TODO: We will change version code to long, so in the new API it is long 17379 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17380 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17381 if (libVersionCode == versionCode) { 17382 return libEntry.apk; 17383 } 17384 } else if (highestVersion == null) { 17385 highestVersion = libEntry; 17386 } else if (libVersionCode > highestVersion.info 17387 .getDeclaringPackage().getVersionCode()) { 17388 highestVersion = libEntry; 17389 } 17390 } 17391 17392 if (highestVersion != null) { 17393 return highestVersion.apk; 17394 } 17395 17396 return packageName; 17397 } 17398 17399 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17400 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17401 || callingUid == Process.SYSTEM_UID) { 17402 return true; 17403 } 17404 final int callingUserId = UserHandle.getUserId(callingUid); 17405 // If the caller installed the pkgName, then allow it to silently uninstall. 17406 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17407 return true; 17408 } 17409 17410 // Allow package verifier to silently uninstall. 17411 if (mRequiredVerifierPackage != null && 17412 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17413 return true; 17414 } 17415 17416 // Allow package uninstaller to silently uninstall. 17417 if (mRequiredUninstallerPackage != null && 17418 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17419 return true; 17420 } 17421 17422 // Allow storage manager to silently uninstall. 17423 if (mStorageManagerPackage != null && 17424 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17425 return true; 17426 } 17427 return false; 17428 } 17429 17430 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17431 int[] result = EMPTY_INT_ARRAY; 17432 for (int userId : userIds) { 17433 if (getBlockUninstallForUser(packageName, userId)) { 17434 result = ArrayUtils.appendInt(result, userId); 17435 } 17436 } 17437 return result; 17438 } 17439 17440 @Override 17441 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17442 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17443 } 17444 17445 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17446 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17447 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17448 try { 17449 if (dpm != null) { 17450 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17451 /* callingUserOnly =*/ false); 17452 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17453 : deviceOwnerComponentName.getPackageName(); 17454 // Does the package contains the device owner? 17455 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17456 // this check is probably not needed, since DO should be registered as a device 17457 // admin on some user too. (Original bug for this: b/17657954) 17458 if (packageName.equals(deviceOwnerPackageName)) { 17459 return true; 17460 } 17461 // Does it contain a device admin for any user? 17462 int[] users; 17463 if (userId == UserHandle.USER_ALL) { 17464 users = sUserManager.getUserIds(); 17465 } else { 17466 users = new int[]{userId}; 17467 } 17468 for (int i = 0; i < users.length; ++i) { 17469 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17470 return true; 17471 } 17472 } 17473 } 17474 } catch (RemoteException e) { 17475 } 17476 return false; 17477 } 17478 17479 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17480 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17481 } 17482 17483 /** 17484 * This method is an internal method that could be get invoked either 17485 * to delete an installed package or to clean up a failed installation. 17486 * After deleting an installed package, a broadcast is sent to notify any 17487 * listeners that the package has been removed. For cleaning up a failed 17488 * installation, the broadcast is not necessary since the package's 17489 * installation wouldn't have sent the initial broadcast either 17490 * The key steps in deleting a package are 17491 * deleting the package information in internal structures like mPackages, 17492 * deleting the packages base directories through installd 17493 * updating mSettings to reflect current status 17494 * persisting settings for later use 17495 * sending a broadcast if necessary 17496 */ 17497 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17498 final PackageRemovedInfo info = new PackageRemovedInfo(); 17499 final boolean res; 17500 17501 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17502 ? UserHandle.USER_ALL : userId; 17503 17504 if (isPackageDeviceAdmin(packageName, removeUser)) { 17505 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17506 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17507 } 17508 17509 PackageSetting uninstalledPs = null; 17510 17511 // for the uninstall-updates case and restricted profiles, remember the per- 17512 // user handle installed state 17513 int[] allUsers; 17514 synchronized (mPackages) { 17515 uninstalledPs = mSettings.mPackages.get(packageName); 17516 if (uninstalledPs == null) { 17517 Slog.w(TAG, "Not removing non-existent package " + packageName); 17518 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17519 } 17520 17521 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17522 && uninstalledPs.versionCode != versionCode) { 17523 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17524 + uninstalledPs.versionCode + " != " + versionCode); 17525 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17526 } 17527 17528 // Static shared libs can be declared by any package, so let us not 17529 // allow removing a package if it provides a lib others depend on. 17530 PackageParser.Package pkg = mPackages.get(packageName); 17531 if (pkg != null && pkg.staticSharedLibName != null) { 17532 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17533 pkg.staticSharedLibVersion); 17534 if (libEntry != null) { 17535 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17536 libEntry.info, 0, userId); 17537 if (!ArrayUtils.isEmpty(libClientPackages)) { 17538 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17539 + " hosting lib " + libEntry.info.getName() + " version " 17540 + libEntry.info.getVersion() + " used by " + libClientPackages); 17541 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17542 } 17543 } 17544 } 17545 17546 allUsers = sUserManager.getUserIds(); 17547 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17548 } 17549 17550 final int freezeUser; 17551 if (isUpdatedSystemApp(uninstalledPs) 17552 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17553 // We're downgrading a system app, which will apply to all users, so 17554 // freeze them all during the downgrade 17555 freezeUser = UserHandle.USER_ALL; 17556 } else { 17557 freezeUser = removeUser; 17558 } 17559 17560 synchronized (mInstallLock) { 17561 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17562 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17563 deleteFlags, "deletePackageX")) { 17564 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17565 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17566 } 17567 synchronized (mPackages) { 17568 if (res) { 17569 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17570 info.removedUsers); 17571 updateSequenceNumberLP(packageName, info.removedUsers); 17572 } 17573 } 17574 } 17575 17576 if (res) { 17577 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17578 info.sendPackageRemovedBroadcasts(killApp); 17579 info.sendSystemPackageUpdatedBroadcasts(); 17580 info.sendSystemPackageAppearedBroadcasts(); 17581 } 17582 // Force a gc here. 17583 Runtime.getRuntime().gc(); 17584 // Delete the resources here after sending the broadcast to let 17585 // other processes clean up before deleting resources. 17586 if (info.args != null) { 17587 synchronized (mInstallLock) { 17588 info.args.doPostDeleteLI(true); 17589 } 17590 } 17591 17592 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17593 } 17594 17595 class PackageRemovedInfo { 17596 String removedPackage; 17597 int uid = -1; 17598 int removedAppId = -1; 17599 int[] origUsers; 17600 int[] removedUsers = null; 17601 SparseArray<Integer> installReasons; 17602 boolean isRemovedPackageSystemUpdate = false; 17603 boolean isUpdate; 17604 boolean dataRemoved; 17605 boolean removedForAllUsers; 17606 boolean isStaticSharedLib; 17607 // Clean up resources deleted packages. 17608 InstallArgs args = null; 17609 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17610 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17611 17612 void sendPackageRemovedBroadcasts(boolean killApp) { 17613 sendPackageRemovedBroadcastInternal(killApp); 17614 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17615 for (int i = 0; i < childCount; i++) { 17616 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17617 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17618 } 17619 } 17620 17621 void sendSystemPackageUpdatedBroadcasts() { 17622 if (isRemovedPackageSystemUpdate) { 17623 sendSystemPackageUpdatedBroadcastsInternal(); 17624 final int childCount = (removedChildPackages != null) 17625 ? removedChildPackages.size() : 0; 17626 for (int i = 0; i < childCount; i++) { 17627 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17628 if (childInfo.isRemovedPackageSystemUpdate) { 17629 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17630 } 17631 } 17632 } 17633 } 17634 17635 void sendSystemPackageAppearedBroadcasts() { 17636 final int packageCount = (appearedChildPackages != null) 17637 ? appearedChildPackages.size() : 0; 17638 for (int i = 0; i < packageCount; i++) { 17639 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17640 sendPackageAddedForNewUsers(installedInfo.name, true, 17641 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17642 } 17643 } 17644 17645 private void sendSystemPackageUpdatedBroadcastsInternal() { 17646 Bundle extras = new Bundle(2); 17647 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17648 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17649 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17650 extras, 0, null, null, null); 17651 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17652 extras, 0, null, null, null); 17653 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17654 null, 0, removedPackage, null, null); 17655 } 17656 17657 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17658 // Don't send static shared library removal broadcasts as these 17659 // libs are visible only the the apps that depend on them an one 17660 // cannot remove the library if it has a dependency. 17661 if (isStaticSharedLib) { 17662 return; 17663 } 17664 Bundle extras = new Bundle(2); 17665 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17666 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17667 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17668 if (isUpdate || isRemovedPackageSystemUpdate) { 17669 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17670 } 17671 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17672 if (removedPackage != null) { 17673 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17674 extras, 0, null, null, removedUsers); 17675 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17676 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17677 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17678 null, null, removedUsers); 17679 } 17680 } 17681 if (removedAppId >= 0) { 17682 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17683 removedUsers); 17684 } 17685 } 17686 } 17687 17688 /* 17689 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17690 * flag is not set, the data directory is removed as well. 17691 * make sure this flag is set for partially installed apps. If not its meaningless to 17692 * delete a partially installed application. 17693 */ 17694 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17695 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17696 String packageName = ps.name; 17697 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17698 // Retrieve object to delete permissions for shared user later on 17699 final PackageParser.Package deletedPkg; 17700 final PackageSetting deletedPs; 17701 // reader 17702 synchronized (mPackages) { 17703 deletedPkg = mPackages.get(packageName); 17704 deletedPs = mSettings.mPackages.get(packageName); 17705 if (outInfo != null) { 17706 outInfo.removedPackage = packageName; 17707 outInfo.isStaticSharedLib = deletedPkg != null 17708 && deletedPkg.staticSharedLibName != null; 17709 outInfo.removedUsers = deletedPs != null 17710 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17711 : null; 17712 } 17713 } 17714 17715 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17716 17717 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17718 final PackageParser.Package resolvedPkg; 17719 if (deletedPkg != null) { 17720 resolvedPkg = deletedPkg; 17721 } else { 17722 // We don't have a parsed package when it lives on an ejected 17723 // adopted storage device, so fake something together 17724 resolvedPkg = new PackageParser.Package(ps.name); 17725 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17726 } 17727 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17728 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17729 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17730 if (outInfo != null) { 17731 outInfo.dataRemoved = true; 17732 } 17733 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17734 } 17735 17736 int removedAppId = -1; 17737 17738 // writer 17739 synchronized (mPackages) { 17740 boolean installedStateChanged = false; 17741 if (deletedPs != null) { 17742 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17743 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17744 clearDefaultBrowserIfNeeded(packageName); 17745 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17746 removedAppId = mSettings.removePackageLPw(packageName); 17747 if (outInfo != null) { 17748 outInfo.removedAppId = removedAppId; 17749 } 17750 updatePermissionsLPw(deletedPs.name, null, 0); 17751 if (deletedPs.sharedUser != null) { 17752 // Remove permissions associated with package. Since runtime 17753 // permissions are per user we have to kill the removed package 17754 // or packages running under the shared user of the removed 17755 // package if revoking the permissions requested only by the removed 17756 // package is successful and this causes a change in gids. 17757 for (int userId : UserManagerService.getInstance().getUserIds()) { 17758 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17759 userId); 17760 if (userIdToKill == UserHandle.USER_ALL 17761 || userIdToKill >= UserHandle.USER_SYSTEM) { 17762 // If gids changed for this user, kill all affected packages. 17763 mHandler.post(new Runnable() { 17764 @Override 17765 public void run() { 17766 // This has to happen with no lock held. 17767 killApplication(deletedPs.name, deletedPs.appId, 17768 KILL_APP_REASON_GIDS_CHANGED); 17769 } 17770 }); 17771 break; 17772 } 17773 } 17774 } 17775 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17776 } 17777 // make sure to preserve per-user disabled state if this removal was just 17778 // a downgrade of a system app to the factory package 17779 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17780 if (DEBUG_REMOVE) { 17781 Slog.d(TAG, "Propagating install state across downgrade"); 17782 } 17783 for (int userId : allUserHandles) { 17784 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17785 if (DEBUG_REMOVE) { 17786 Slog.d(TAG, " user " + userId + " => " + installed); 17787 } 17788 if (installed != ps.getInstalled(userId)) { 17789 installedStateChanged = true; 17790 } 17791 ps.setInstalled(installed, userId); 17792 } 17793 } 17794 } 17795 // can downgrade to reader 17796 if (writeSettings) { 17797 // Save settings now 17798 mSettings.writeLPr(); 17799 } 17800 if (installedStateChanged) { 17801 mSettings.writeKernelMappingLPr(ps); 17802 } 17803 } 17804 if (removedAppId != -1) { 17805 // A user ID was deleted here. Go through all users and remove it 17806 // from KeyStore. 17807 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17808 } 17809 } 17810 17811 static boolean locationIsPrivileged(File path) { 17812 try { 17813 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17814 .getCanonicalPath(); 17815 return path.getCanonicalPath().startsWith(privilegedAppDir); 17816 } catch (IOException e) { 17817 Slog.e(TAG, "Unable to access code path " + path); 17818 } 17819 return false; 17820 } 17821 17822 /* 17823 * Tries to delete system package. 17824 */ 17825 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17826 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17827 boolean writeSettings) { 17828 if (deletedPs.parentPackageName != null) { 17829 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17830 return false; 17831 } 17832 17833 final boolean applyUserRestrictions 17834 = (allUserHandles != null) && (outInfo.origUsers != null); 17835 final PackageSetting disabledPs; 17836 // Confirm if the system package has been updated 17837 // An updated system app can be deleted. This will also have to restore 17838 // the system pkg from system partition 17839 // reader 17840 synchronized (mPackages) { 17841 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17842 } 17843 17844 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17845 + " disabledPs=" + disabledPs); 17846 17847 if (disabledPs == null) { 17848 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17849 return false; 17850 } else if (DEBUG_REMOVE) { 17851 Slog.d(TAG, "Deleting system pkg from data partition"); 17852 } 17853 17854 if (DEBUG_REMOVE) { 17855 if (applyUserRestrictions) { 17856 Slog.d(TAG, "Remembering install states:"); 17857 for (int userId : allUserHandles) { 17858 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17859 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17860 } 17861 } 17862 } 17863 17864 // Delete the updated package 17865 outInfo.isRemovedPackageSystemUpdate = true; 17866 if (outInfo.removedChildPackages != null) { 17867 final int childCount = (deletedPs.childPackageNames != null) 17868 ? deletedPs.childPackageNames.size() : 0; 17869 for (int i = 0; i < childCount; i++) { 17870 String childPackageName = deletedPs.childPackageNames.get(i); 17871 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17872 .contains(childPackageName)) { 17873 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17874 childPackageName); 17875 if (childInfo != null) { 17876 childInfo.isRemovedPackageSystemUpdate = true; 17877 } 17878 } 17879 } 17880 } 17881 17882 if (disabledPs.versionCode < deletedPs.versionCode) { 17883 // Delete data for downgrades 17884 flags &= ~PackageManager.DELETE_KEEP_DATA; 17885 } else { 17886 // Preserve data by setting flag 17887 flags |= PackageManager.DELETE_KEEP_DATA; 17888 } 17889 17890 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17891 outInfo, writeSettings, disabledPs.pkg); 17892 if (!ret) { 17893 return false; 17894 } 17895 17896 // writer 17897 synchronized (mPackages) { 17898 // Reinstate the old system package 17899 enableSystemPackageLPw(disabledPs.pkg); 17900 // Remove any native libraries from the upgraded package. 17901 removeNativeBinariesLI(deletedPs); 17902 } 17903 17904 // Install the system package 17905 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17906 int parseFlags = mDefParseFlags 17907 | PackageParser.PARSE_MUST_BE_APK 17908 | PackageParser.PARSE_IS_SYSTEM 17909 | PackageParser.PARSE_IS_SYSTEM_DIR; 17910 if (locationIsPrivileged(disabledPs.codePath)) { 17911 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17912 } 17913 17914 final PackageParser.Package newPkg; 17915 try { 17916 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17917 0 /* currentTime */, null); 17918 } catch (PackageManagerException e) { 17919 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17920 + e.getMessage()); 17921 return false; 17922 } 17923 17924 try { 17925 // update shared libraries for the newly re-installed system package 17926 updateSharedLibrariesLPr(newPkg, null); 17927 } catch (PackageManagerException e) { 17928 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17929 } 17930 17931 prepareAppDataAfterInstallLIF(newPkg); 17932 17933 // writer 17934 synchronized (mPackages) { 17935 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17936 17937 // Propagate the permissions state as we do not want to drop on the floor 17938 // runtime permissions. The update permissions method below will take 17939 // care of removing obsolete permissions and grant install permissions. 17940 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17941 updatePermissionsLPw(newPkg.packageName, newPkg, 17942 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17943 17944 if (applyUserRestrictions) { 17945 boolean installedStateChanged = false; 17946 if (DEBUG_REMOVE) { 17947 Slog.d(TAG, "Propagating install state across reinstall"); 17948 } 17949 for (int userId : allUserHandles) { 17950 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17951 if (DEBUG_REMOVE) { 17952 Slog.d(TAG, " user " + userId + " => " + installed); 17953 } 17954 if (installed != ps.getInstalled(userId)) { 17955 installedStateChanged = true; 17956 } 17957 ps.setInstalled(installed, userId); 17958 17959 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17960 } 17961 // Regardless of writeSettings we need to ensure that this restriction 17962 // state propagation is persisted 17963 mSettings.writeAllUsersPackageRestrictionsLPr(); 17964 if (installedStateChanged) { 17965 mSettings.writeKernelMappingLPr(ps); 17966 } 17967 } 17968 // can downgrade to reader here 17969 if (writeSettings) { 17970 mSettings.writeLPr(); 17971 } 17972 } 17973 return true; 17974 } 17975 17976 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17977 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17978 PackageRemovedInfo outInfo, boolean writeSettings, 17979 PackageParser.Package replacingPackage) { 17980 synchronized (mPackages) { 17981 if (outInfo != null) { 17982 outInfo.uid = ps.appId; 17983 } 17984 17985 if (outInfo != null && outInfo.removedChildPackages != null) { 17986 final int childCount = (ps.childPackageNames != null) 17987 ? ps.childPackageNames.size() : 0; 17988 for (int i = 0; i < childCount; i++) { 17989 String childPackageName = ps.childPackageNames.get(i); 17990 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17991 if (childPs == null) { 17992 return false; 17993 } 17994 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17995 childPackageName); 17996 if (childInfo != null) { 17997 childInfo.uid = childPs.appId; 17998 } 17999 } 18000 } 18001 } 18002 18003 // Delete package data from internal structures and also remove data if flag is set 18004 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18005 18006 // Delete the child packages data 18007 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18008 for (int i = 0; i < childCount; i++) { 18009 PackageSetting childPs; 18010 synchronized (mPackages) { 18011 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18012 } 18013 if (childPs != null) { 18014 PackageRemovedInfo childOutInfo = (outInfo != null 18015 && outInfo.removedChildPackages != null) 18016 ? outInfo.removedChildPackages.get(childPs.name) : null; 18017 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18018 && (replacingPackage != null 18019 && !replacingPackage.hasChildPackage(childPs.name)) 18020 ? flags & ~DELETE_KEEP_DATA : flags; 18021 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18022 deleteFlags, writeSettings); 18023 } 18024 } 18025 18026 // Delete application code and resources only for parent packages 18027 if (ps.parentPackageName == null) { 18028 if (deleteCodeAndResources && (outInfo != null)) { 18029 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18030 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18031 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18032 } 18033 } 18034 18035 return true; 18036 } 18037 18038 @Override 18039 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18040 int userId) { 18041 mContext.enforceCallingOrSelfPermission( 18042 android.Manifest.permission.DELETE_PACKAGES, null); 18043 synchronized (mPackages) { 18044 PackageSetting ps = mSettings.mPackages.get(packageName); 18045 if (ps == null) { 18046 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18047 return false; 18048 } 18049 // Cannot block uninstall of static shared libs as they are 18050 // considered a part of the using app (emulating static linking). 18051 // Also static libs are installed always on internal storage. 18052 PackageParser.Package pkg = mPackages.get(packageName); 18053 if (pkg != null && pkg.staticSharedLibName != null) { 18054 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18055 + " providing static shared library: " + pkg.staticSharedLibName); 18056 return false; 18057 } 18058 if (!ps.getInstalled(userId)) { 18059 // Can't block uninstall for an app that is not installed or enabled. 18060 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18061 return false; 18062 } 18063 ps.setBlockUninstall(blockUninstall, userId); 18064 mSettings.writePackageRestrictionsLPr(userId); 18065 } 18066 return true; 18067 } 18068 18069 @Override 18070 public boolean getBlockUninstallForUser(String packageName, int userId) { 18071 synchronized (mPackages) { 18072 PackageSetting ps = mSettings.mPackages.get(packageName); 18073 if (ps == null) { 18074 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18075 return false; 18076 } 18077 return ps.getBlockUninstall(userId); 18078 } 18079 } 18080 18081 @Override 18082 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18083 int callingUid = Binder.getCallingUid(); 18084 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18085 throw new SecurityException( 18086 "setRequiredForSystemUser can only be run by the system or root"); 18087 } 18088 synchronized (mPackages) { 18089 PackageSetting ps = mSettings.mPackages.get(packageName); 18090 if (ps == null) { 18091 Log.w(TAG, "Package doesn't exist: " + packageName); 18092 return false; 18093 } 18094 if (systemUserApp) { 18095 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18096 } else { 18097 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18098 } 18099 mSettings.writeLPr(); 18100 } 18101 return true; 18102 } 18103 18104 /* 18105 * This method handles package deletion in general 18106 */ 18107 private boolean deletePackageLIF(String packageName, UserHandle user, 18108 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18109 PackageRemovedInfo outInfo, boolean writeSettings, 18110 PackageParser.Package replacingPackage) { 18111 if (packageName == null) { 18112 Slog.w(TAG, "Attempt to delete null packageName."); 18113 return false; 18114 } 18115 18116 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18117 18118 PackageSetting ps; 18119 synchronized (mPackages) { 18120 ps = mSettings.mPackages.get(packageName); 18121 if (ps == null) { 18122 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18123 return false; 18124 } 18125 18126 if (ps.parentPackageName != null && (!isSystemApp(ps) 18127 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18128 if (DEBUG_REMOVE) { 18129 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18130 + ((user == null) ? UserHandle.USER_ALL : user)); 18131 } 18132 final int removedUserId = (user != null) ? user.getIdentifier() 18133 : UserHandle.USER_ALL; 18134 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18135 return false; 18136 } 18137 markPackageUninstalledForUserLPw(ps, user); 18138 scheduleWritePackageRestrictionsLocked(user); 18139 return true; 18140 } 18141 } 18142 18143 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18144 && user.getIdentifier() != UserHandle.USER_ALL)) { 18145 // The caller is asking that the package only be deleted for a single 18146 // user. To do this, we just mark its uninstalled state and delete 18147 // its data. If this is a system app, we only allow this to happen if 18148 // they have set the special DELETE_SYSTEM_APP which requests different 18149 // semantics than normal for uninstalling system apps. 18150 markPackageUninstalledForUserLPw(ps, user); 18151 18152 if (!isSystemApp(ps)) { 18153 // Do not uninstall the APK if an app should be cached 18154 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18155 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18156 // Other user still have this package installed, so all 18157 // we need to do is clear this user's data and save that 18158 // it is uninstalled. 18159 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18160 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18161 return false; 18162 } 18163 scheduleWritePackageRestrictionsLocked(user); 18164 return true; 18165 } else { 18166 // We need to set it back to 'installed' so the uninstall 18167 // broadcasts will be sent correctly. 18168 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18169 ps.setInstalled(true, user.getIdentifier()); 18170 mSettings.writeKernelMappingLPr(ps); 18171 } 18172 } else { 18173 // This is a system app, so we assume that the 18174 // other users still have this package installed, so all 18175 // we need to do is clear this user's data and save that 18176 // it is uninstalled. 18177 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18178 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18179 return false; 18180 } 18181 scheduleWritePackageRestrictionsLocked(user); 18182 return true; 18183 } 18184 } 18185 18186 // If we are deleting a composite package for all users, keep track 18187 // of result for each child. 18188 if (ps.childPackageNames != null && outInfo != null) { 18189 synchronized (mPackages) { 18190 final int childCount = ps.childPackageNames.size(); 18191 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18192 for (int i = 0; i < childCount; i++) { 18193 String childPackageName = ps.childPackageNames.get(i); 18194 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18195 childInfo.removedPackage = childPackageName; 18196 outInfo.removedChildPackages.put(childPackageName, childInfo); 18197 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18198 if (childPs != null) { 18199 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18200 } 18201 } 18202 } 18203 } 18204 18205 boolean ret = false; 18206 if (isSystemApp(ps)) { 18207 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18208 // When an updated system application is deleted we delete the existing resources 18209 // as well and fall back to existing code in system partition 18210 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18211 } else { 18212 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18213 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18214 outInfo, writeSettings, replacingPackage); 18215 } 18216 18217 // Take a note whether we deleted the package for all users 18218 if (outInfo != null) { 18219 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18220 if (outInfo.removedChildPackages != null) { 18221 synchronized (mPackages) { 18222 final int childCount = outInfo.removedChildPackages.size(); 18223 for (int i = 0; i < childCount; i++) { 18224 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18225 if (childInfo != null) { 18226 childInfo.removedForAllUsers = mPackages.get( 18227 childInfo.removedPackage) == null; 18228 } 18229 } 18230 } 18231 } 18232 // If we uninstalled an update to a system app there may be some 18233 // child packages that appeared as they are declared in the system 18234 // app but were not declared in the update. 18235 if (isSystemApp(ps)) { 18236 synchronized (mPackages) { 18237 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18238 final int childCount = (updatedPs.childPackageNames != null) 18239 ? updatedPs.childPackageNames.size() : 0; 18240 for (int i = 0; i < childCount; i++) { 18241 String childPackageName = updatedPs.childPackageNames.get(i); 18242 if (outInfo.removedChildPackages == null 18243 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18244 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18245 if (childPs == null) { 18246 continue; 18247 } 18248 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18249 installRes.name = childPackageName; 18250 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18251 installRes.pkg = mPackages.get(childPackageName); 18252 installRes.uid = childPs.pkg.applicationInfo.uid; 18253 if (outInfo.appearedChildPackages == null) { 18254 outInfo.appearedChildPackages = new ArrayMap<>(); 18255 } 18256 outInfo.appearedChildPackages.put(childPackageName, installRes); 18257 } 18258 } 18259 } 18260 } 18261 } 18262 18263 return ret; 18264 } 18265 18266 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18267 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18268 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18269 for (int nextUserId : userIds) { 18270 if (DEBUG_REMOVE) { 18271 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18272 } 18273 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18274 false /*installed*/, 18275 true /*stopped*/, 18276 true /*notLaunched*/, 18277 false /*hidden*/, 18278 false /*suspended*/, 18279 false /*instantApp*/, 18280 null /*lastDisableAppCaller*/, 18281 null /*enabledComponents*/, 18282 null /*disabledComponents*/, 18283 false /*blockUninstall*/, 18284 ps.readUserState(nextUserId).domainVerificationStatus, 18285 0, PackageManager.INSTALL_REASON_UNKNOWN); 18286 } 18287 mSettings.writeKernelMappingLPr(ps); 18288 } 18289 18290 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18291 PackageRemovedInfo outInfo) { 18292 final PackageParser.Package pkg; 18293 synchronized (mPackages) { 18294 pkg = mPackages.get(ps.name); 18295 } 18296 18297 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18298 : new int[] {userId}; 18299 for (int nextUserId : userIds) { 18300 if (DEBUG_REMOVE) { 18301 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18302 + nextUserId); 18303 } 18304 18305 destroyAppDataLIF(pkg, userId, 18306 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18307 destroyAppProfilesLIF(pkg, userId); 18308 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18309 schedulePackageCleaning(ps.name, nextUserId, false); 18310 synchronized (mPackages) { 18311 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18312 scheduleWritePackageRestrictionsLocked(nextUserId); 18313 } 18314 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18315 } 18316 } 18317 18318 if (outInfo != null) { 18319 outInfo.removedPackage = ps.name; 18320 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18321 outInfo.removedAppId = ps.appId; 18322 outInfo.removedUsers = userIds; 18323 } 18324 18325 return true; 18326 } 18327 18328 private final class ClearStorageConnection implements ServiceConnection { 18329 IMediaContainerService mContainerService; 18330 18331 @Override 18332 public void onServiceConnected(ComponentName name, IBinder service) { 18333 synchronized (this) { 18334 mContainerService = IMediaContainerService.Stub 18335 .asInterface(Binder.allowBlocking(service)); 18336 notifyAll(); 18337 } 18338 } 18339 18340 @Override 18341 public void onServiceDisconnected(ComponentName name) { 18342 } 18343 } 18344 18345 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18346 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18347 18348 final boolean mounted; 18349 if (Environment.isExternalStorageEmulated()) { 18350 mounted = true; 18351 } else { 18352 final String status = Environment.getExternalStorageState(); 18353 18354 mounted = status.equals(Environment.MEDIA_MOUNTED) 18355 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18356 } 18357 18358 if (!mounted) { 18359 return; 18360 } 18361 18362 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18363 int[] users; 18364 if (userId == UserHandle.USER_ALL) { 18365 users = sUserManager.getUserIds(); 18366 } else { 18367 users = new int[] { userId }; 18368 } 18369 final ClearStorageConnection conn = new ClearStorageConnection(); 18370 if (mContext.bindServiceAsUser( 18371 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18372 try { 18373 for (int curUser : users) { 18374 long timeout = SystemClock.uptimeMillis() + 5000; 18375 synchronized (conn) { 18376 long now; 18377 while (conn.mContainerService == null && 18378 (now = SystemClock.uptimeMillis()) < timeout) { 18379 try { 18380 conn.wait(timeout - now); 18381 } catch (InterruptedException e) { 18382 } 18383 } 18384 } 18385 if (conn.mContainerService == null) { 18386 return; 18387 } 18388 18389 final UserEnvironment userEnv = new UserEnvironment(curUser); 18390 clearDirectory(conn.mContainerService, 18391 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18392 if (allData) { 18393 clearDirectory(conn.mContainerService, 18394 userEnv.buildExternalStorageAppDataDirs(packageName)); 18395 clearDirectory(conn.mContainerService, 18396 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18397 } 18398 } 18399 } finally { 18400 mContext.unbindService(conn); 18401 } 18402 } 18403 } 18404 18405 @Override 18406 public void clearApplicationProfileData(String packageName) { 18407 enforceSystemOrRoot("Only the system can clear all profile data"); 18408 18409 final PackageParser.Package pkg; 18410 synchronized (mPackages) { 18411 pkg = mPackages.get(packageName); 18412 } 18413 18414 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18415 synchronized (mInstallLock) { 18416 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18417 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18418 true /* removeBaseMarker */); 18419 } 18420 } 18421 } 18422 18423 @Override 18424 public void clearApplicationUserData(final String packageName, 18425 final IPackageDataObserver observer, final int userId) { 18426 mContext.enforceCallingOrSelfPermission( 18427 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18428 18429 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18430 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18431 18432 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18433 throw new SecurityException("Cannot clear data for a protected package: " 18434 + packageName); 18435 } 18436 // Queue up an async operation since the package deletion may take a little while. 18437 mHandler.post(new Runnable() { 18438 public void run() { 18439 mHandler.removeCallbacks(this); 18440 final boolean succeeded; 18441 try (PackageFreezer freezer = freezePackage(packageName, 18442 "clearApplicationUserData")) { 18443 synchronized (mInstallLock) { 18444 succeeded = clearApplicationUserDataLIF(packageName, userId); 18445 } 18446 clearExternalStorageDataSync(packageName, userId, true); 18447 synchronized (mPackages) { 18448 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18449 packageName, userId); 18450 } 18451 } 18452 if (succeeded) { 18453 // invoke DeviceStorageMonitor's update method to clear any notifications 18454 DeviceStorageMonitorInternal dsm = LocalServices 18455 .getService(DeviceStorageMonitorInternal.class); 18456 if (dsm != null) { 18457 dsm.checkMemory(); 18458 } 18459 } 18460 if(observer != null) { 18461 try { 18462 observer.onRemoveCompleted(packageName, succeeded); 18463 } catch (RemoteException e) { 18464 Log.i(TAG, "Observer no longer exists."); 18465 } 18466 } //end if observer 18467 } //end run 18468 }); 18469 } 18470 18471 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18472 if (packageName == null) { 18473 Slog.w(TAG, "Attempt to delete null packageName."); 18474 return false; 18475 } 18476 18477 // Try finding details about the requested package 18478 PackageParser.Package pkg; 18479 synchronized (mPackages) { 18480 pkg = mPackages.get(packageName); 18481 if (pkg == null) { 18482 final PackageSetting ps = mSettings.mPackages.get(packageName); 18483 if (ps != null) { 18484 pkg = ps.pkg; 18485 } 18486 } 18487 18488 if (pkg == null) { 18489 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18490 return false; 18491 } 18492 18493 PackageSetting ps = (PackageSetting) pkg.mExtras; 18494 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18495 } 18496 18497 clearAppDataLIF(pkg, userId, 18498 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18499 18500 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18501 removeKeystoreDataIfNeeded(userId, appId); 18502 18503 UserManagerInternal umInternal = getUserManagerInternal(); 18504 final int flags; 18505 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18506 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18507 } else if (umInternal.isUserRunning(userId)) { 18508 flags = StorageManager.FLAG_STORAGE_DE; 18509 } else { 18510 flags = 0; 18511 } 18512 prepareAppDataContentsLIF(pkg, userId, flags); 18513 18514 return true; 18515 } 18516 18517 /** 18518 * Reverts user permission state changes (permissions and flags) in 18519 * all packages for a given user. 18520 * 18521 * @param userId The device user for which to do a reset. 18522 */ 18523 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18524 final int packageCount = mPackages.size(); 18525 for (int i = 0; i < packageCount; i++) { 18526 PackageParser.Package pkg = mPackages.valueAt(i); 18527 PackageSetting ps = (PackageSetting) pkg.mExtras; 18528 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18529 } 18530 } 18531 18532 private void resetNetworkPolicies(int userId) { 18533 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18534 } 18535 18536 /** 18537 * Reverts user permission state changes (permissions and flags). 18538 * 18539 * @param ps The package for which to reset. 18540 * @param userId The device user for which to do a reset. 18541 */ 18542 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18543 final PackageSetting ps, final int userId) { 18544 if (ps.pkg == null) { 18545 return; 18546 } 18547 18548 // These are flags that can change base on user actions. 18549 final int userSettableMask = FLAG_PERMISSION_USER_SET 18550 | FLAG_PERMISSION_USER_FIXED 18551 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18552 | FLAG_PERMISSION_REVIEW_REQUIRED; 18553 18554 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18555 | FLAG_PERMISSION_POLICY_FIXED; 18556 18557 boolean writeInstallPermissions = false; 18558 boolean writeRuntimePermissions = false; 18559 18560 final int permissionCount = ps.pkg.requestedPermissions.size(); 18561 for (int i = 0; i < permissionCount; i++) { 18562 String permission = ps.pkg.requestedPermissions.get(i); 18563 18564 BasePermission bp = mSettings.mPermissions.get(permission); 18565 if (bp == null) { 18566 continue; 18567 } 18568 18569 // If shared user we just reset the state to which only this app contributed. 18570 if (ps.sharedUser != null) { 18571 boolean used = false; 18572 final int packageCount = ps.sharedUser.packages.size(); 18573 for (int j = 0; j < packageCount; j++) { 18574 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18575 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18576 && pkg.pkg.requestedPermissions.contains(permission)) { 18577 used = true; 18578 break; 18579 } 18580 } 18581 if (used) { 18582 continue; 18583 } 18584 } 18585 18586 PermissionsState permissionsState = ps.getPermissionsState(); 18587 18588 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18589 18590 // Always clear the user settable flags. 18591 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18592 bp.name) != null; 18593 // If permission review is enabled and this is a legacy app, mark the 18594 // permission as requiring a review as this is the initial state. 18595 int flags = 0; 18596 if (mPermissionReviewRequired 18597 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18598 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18599 } 18600 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18601 if (hasInstallState) { 18602 writeInstallPermissions = true; 18603 } else { 18604 writeRuntimePermissions = true; 18605 } 18606 } 18607 18608 // Below is only runtime permission handling. 18609 if (!bp.isRuntime()) { 18610 continue; 18611 } 18612 18613 // Never clobber system or policy. 18614 if ((oldFlags & policyOrSystemFlags) != 0) { 18615 continue; 18616 } 18617 18618 // If this permission was granted by default, make sure it is. 18619 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18620 if (permissionsState.grantRuntimePermission(bp, userId) 18621 != PERMISSION_OPERATION_FAILURE) { 18622 writeRuntimePermissions = true; 18623 } 18624 // If permission review is enabled the permissions for a legacy apps 18625 // are represented as constantly granted runtime ones, so don't revoke. 18626 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18627 // Otherwise, reset the permission. 18628 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18629 switch (revokeResult) { 18630 case PERMISSION_OPERATION_SUCCESS: 18631 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18632 writeRuntimePermissions = true; 18633 final int appId = ps.appId; 18634 mHandler.post(new Runnable() { 18635 @Override 18636 public void run() { 18637 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18638 } 18639 }); 18640 } break; 18641 } 18642 } 18643 } 18644 18645 // Synchronously write as we are taking permissions away. 18646 if (writeRuntimePermissions) { 18647 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18648 } 18649 18650 // Synchronously write as we are taking permissions away. 18651 if (writeInstallPermissions) { 18652 mSettings.writeLPr(); 18653 } 18654 } 18655 18656 /** 18657 * Remove entries from the keystore daemon. Will only remove it if the 18658 * {@code appId} is valid. 18659 */ 18660 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18661 if (appId < 0) { 18662 return; 18663 } 18664 18665 final KeyStore keyStore = KeyStore.getInstance(); 18666 if (keyStore != null) { 18667 if (userId == UserHandle.USER_ALL) { 18668 for (final int individual : sUserManager.getUserIds()) { 18669 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18670 } 18671 } else { 18672 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18673 } 18674 } else { 18675 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18676 } 18677 } 18678 18679 @Override 18680 public void deleteApplicationCacheFiles(final String packageName, 18681 final IPackageDataObserver observer) { 18682 final int userId = UserHandle.getCallingUserId(); 18683 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18684 } 18685 18686 @Override 18687 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18688 final IPackageDataObserver observer) { 18689 mContext.enforceCallingOrSelfPermission( 18690 android.Manifest.permission.DELETE_CACHE_FILES, null); 18691 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18692 /* requireFullPermission= */ true, /* checkShell= */ false, 18693 "delete application cache files"); 18694 18695 final PackageParser.Package pkg; 18696 synchronized (mPackages) { 18697 pkg = mPackages.get(packageName); 18698 } 18699 18700 // Queue up an async operation since the package deletion may take a little while. 18701 mHandler.post(new Runnable() { 18702 public void run() { 18703 synchronized (mInstallLock) { 18704 final int flags = StorageManager.FLAG_STORAGE_DE 18705 | StorageManager.FLAG_STORAGE_CE; 18706 // We're only clearing cache files, so we don't care if the 18707 // app is unfrozen and still able to run 18708 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18709 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18710 } 18711 clearExternalStorageDataSync(packageName, userId, false); 18712 if (observer != null) { 18713 try { 18714 observer.onRemoveCompleted(packageName, true); 18715 } catch (RemoteException e) { 18716 Log.i(TAG, "Observer no longer exists."); 18717 } 18718 } 18719 } 18720 }); 18721 } 18722 18723 @Override 18724 public void getPackageSizeInfo(final String packageName, int userHandle, 18725 final IPackageStatsObserver observer) { 18726 Slog.w(TAG, "Shame on you for calling a hidden API. Shame!"); 18727 try { 18728 observer.onGetStatsCompleted(null, false); 18729 } catch (RemoteException ignored) { 18730 } 18731 } 18732 18733 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18734 final PackageSetting ps; 18735 synchronized (mPackages) { 18736 ps = mSettings.mPackages.get(packageName); 18737 if (ps == null) { 18738 Slog.w(TAG, "Failed to find settings for " + packageName); 18739 return false; 18740 } 18741 } 18742 18743 final String[] packageNames = { packageName }; 18744 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18745 final String[] codePaths = { ps.codePathString }; 18746 18747 try { 18748 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18749 ps.appId, ceDataInodes, codePaths, stats); 18750 18751 // For now, ignore code size of packages on system partition 18752 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18753 stats.codeSize = 0; 18754 } 18755 18756 // External clients expect these to be tracked separately 18757 stats.dataSize -= stats.cacheSize; 18758 18759 } catch (InstallerException e) { 18760 Slog.w(TAG, String.valueOf(e)); 18761 return false; 18762 } 18763 18764 return true; 18765 } 18766 18767 private int getUidTargetSdkVersionLockedLPr(int uid) { 18768 Object obj = mSettings.getUserIdLPr(uid); 18769 if (obj instanceof SharedUserSetting) { 18770 final SharedUserSetting sus = (SharedUserSetting) obj; 18771 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18772 final Iterator<PackageSetting> it = sus.packages.iterator(); 18773 while (it.hasNext()) { 18774 final PackageSetting ps = it.next(); 18775 if (ps.pkg != null) { 18776 int v = ps.pkg.applicationInfo.targetSdkVersion; 18777 if (v < vers) vers = v; 18778 } 18779 } 18780 return vers; 18781 } else if (obj instanceof PackageSetting) { 18782 final PackageSetting ps = (PackageSetting) obj; 18783 if (ps.pkg != null) { 18784 return ps.pkg.applicationInfo.targetSdkVersion; 18785 } 18786 } 18787 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18788 } 18789 18790 @Override 18791 public void addPreferredActivity(IntentFilter filter, int match, 18792 ComponentName[] set, ComponentName activity, int userId) { 18793 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18794 "Adding preferred"); 18795 } 18796 18797 private void addPreferredActivityInternal(IntentFilter filter, int match, 18798 ComponentName[] set, ComponentName activity, boolean always, int userId, 18799 String opname) { 18800 // writer 18801 int callingUid = Binder.getCallingUid(); 18802 enforceCrossUserPermission(callingUid, userId, 18803 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18804 if (filter.countActions() == 0) { 18805 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18806 return; 18807 } 18808 synchronized (mPackages) { 18809 if (mContext.checkCallingOrSelfPermission( 18810 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18811 != PackageManager.PERMISSION_GRANTED) { 18812 if (getUidTargetSdkVersionLockedLPr(callingUid) 18813 < Build.VERSION_CODES.FROYO) { 18814 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18815 + callingUid); 18816 return; 18817 } 18818 mContext.enforceCallingOrSelfPermission( 18819 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18820 } 18821 18822 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18823 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18824 + userId + ":"); 18825 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18826 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18827 scheduleWritePackageRestrictionsLocked(userId); 18828 postPreferredActivityChangedBroadcast(userId); 18829 } 18830 } 18831 18832 private void postPreferredActivityChangedBroadcast(int userId) { 18833 mHandler.post(() -> { 18834 final IActivityManager am = ActivityManager.getService(); 18835 if (am == null) { 18836 return; 18837 } 18838 18839 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18840 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18841 try { 18842 am.broadcastIntent(null, intent, null, null, 18843 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18844 null, false, false, userId); 18845 } catch (RemoteException e) { 18846 } 18847 }); 18848 } 18849 18850 @Override 18851 public void replacePreferredActivity(IntentFilter filter, int match, 18852 ComponentName[] set, ComponentName activity, int userId) { 18853 if (filter.countActions() != 1) { 18854 throw new IllegalArgumentException( 18855 "replacePreferredActivity expects filter to have only 1 action."); 18856 } 18857 if (filter.countDataAuthorities() != 0 18858 || filter.countDataPaths() != 0 18859 || filter.countDataSchemes() > 1 18860 || filter.countDataTypes() != 0) { 18861 throw new IllegalArgumentException( 18862 "replacePreferredActivity expects filter to have no data authorities, " + 18863 "paths, or types; and at most one scheme."); 18864 } 18865 18866 final int callingUid = Binder.getCallingUid(); 18867 enforceCrossUserPermission(callingUid, userId, 18868 true /* requireFullPermission */, false /* checkShell */, 18869 "replace preferred activity"); 18870 synchronized (mPackages) { 18871 if (mContext.checkCallingOrSelfPermission( 18872 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18873 != PackageManager.PERMISSION_GRANTED) { 18874 if (getUidTargetSdkVersionLockedLPr(callingUid) 18875 < Build.VERSION_CODES.FROYO) { 18876 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18877 + Binder.getCallingUid()); 18878 return; 18879 } 18880 mContext.enforceCallingOrSelfPermission( 18881 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18882 } 18883 18884 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18885 if (pir != null) { 18886 // Get all of the existing entries that exactly match this filter. 18887 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18888 if (existing != null && existing.size() == 1) { 18889 PreferredActivity cur = existing.get(0); 18890 if (DEBUG_PREFERRED) { 18891 Slog.i(TAG, "Checking replace of preferred:"); 18892 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18893 if (!cur.mPref.mAlways) { 18894 Slog.i(TAG, " -- CUR; not mAlways!"); 18895 } else { 18896 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18897 Slog.i(TAG, " -- CUR: mSet=" 18898 + Arrays.toString(cur.mPref.mSetComponents)); 18899 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18900 Slog.i(TAG, " -- NEW: mMatch=" 18901 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18902 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18903 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18904 } 18905 } 18906 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18907 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18908 && cur.mPref.sameSet(set)) { 18909 // Setting the preferred activity to what it happens to be already 18910 if (DEBUG_PREFERRED) { 18911 Slog.i(TAG, "Replacing with same preferred activity " 18912 + cur.mPref.mShortComponent + " for user " 18913 + userId + ":"); 18914 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18915 } 18916 return; 18917 } 18918 } 18919 18920 if (existing != null) { 18921 if (DEBUG_PREFERRED) { 18922 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18923 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18924 } 18925 for (int i = 0; i < existing.size(); i++) { 18926 PreferredActivity pa = existing.get(i); 18927 if (DEBUG_PREFERRED) { 18928 Slog.i(TAG, "Removing existing preferred activity " 18929 + pa.mPref.mComponent + ":"); 18930 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18931 } 18932 pir.removeFilter(pa); 18933 } 18934 } 18935 } 18936 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18937 "Replacing preferred"); 18938 } 18939 } 18940 18941 @Override 18942 public void clearPackagePreferredActivities(String packageName) { 18943 final int uid = Binder.getCallingUid(); 18944 // writer 18945 synchronized (mPackages) { 18946 PackageParser.Package pkg = mPackages.get(packageName); 18947 if (pkg == null || pkg.applicationInfo.uid != uid) { 18948 if (mContext.checkCallingOrSelfPermission( 18949 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18950 != PackageManager.PERMISSION_GRANTED) { 18951 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18952 < Build.VERSION_CODES.FROYO) { 18953 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18954 + Binder.getCallingUid()); 18955 return; 18956 } 18957 mContext.enforceCallingOrSelfPermission( 18958 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18959 } 18960 } 18961 18962 int user = UserHandle.getCallingUserId(); 18963 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18964 scheduleWritePackageRestrictionsLocked(user); 18965 } 18966 } 18967 } 18968 18969 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18970 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18971 ArrayList<PreferredActivity> removed = null; 18972 boolean changed = false; 18973 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18974 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18975 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18976 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18977 continue; 18978 } 18979 Iterator<PreferredActivity> it = pir.filterIterator(); 18980 while (it.hasNext()) { 18981 PreferredActivity pa = it.next(); 18982 // Mark entry for removal only if it matches the package name 18983 // and the entry is of type "always". 18984 if (packageName == null || 18985 (pa.mPref.mComponent.getPackageName().equals(packageName) 18986 && pa.mPref.mAlways)) { 18987 if (removed == null) { 18988 removed = new ArrayList<PreferredActivity>(); 18989 } 18990 removed.add(pa); 18991 } 18992 } 18993 if (removed != null) { 18994 for (int j=0; j<removed.size(); j++) { 18995 PreferredActivity pa = removed.get(j); 18996 pir.removeFilter(pa); 18997 } 18998 changed = true; 18999 } 19000 } 19001 if (changed) { 19002 postPreferredActivityChangedBroadcast(userId); 19003 } 19004 return changed; 19005 } 19006 19007 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19008 private void clearIntentFilterVerificationsLPw(int userId) { 19009 final int packageCount = mPackages.size(); 19010 for (int i = 0; i < packageCount; i++) { 19011 PackageParser.Package pkg = mPackages.valueAt(i); 19012 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19013 } 19014 } 19015 19016 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19017 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19018 if (userId == UserHandle.USER_ALL) { 19019 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19020 sUserManager.getUserIds())) { 19021 for (int oneUserId : sUserManager.getUserIds()) { 19022 scheduleWritePackageRestrictionsLocked(oneUserId); 19023 } 19024 } 19025 } else { 19026 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19027 scheduleWritePackageRestrictionsLocked(userId); 19028 } 19029 } 19030 } 19031 19032 void clearDefaultBrowserIfNeeded(String packageName) { 19033 for (int oneUserId : sUserManager.getUserIds()) { 19034 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19035 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19036 if (packageName.equals(defaultBrowserPackageName)) { 19037 setDefaultBrowserPackageName(null, oneUserId); 19038 } 19039 } 19040 } 19041 19042 @Override 19043 public void resetApplicationPreferences(int userId) { 19044 mContext.enforceCallingOrSelfPermission( 19045 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19046 final long identity = Binder.clearCallingIdentity(); 19047 // writer 19048 try { 19049 synchronized (mPackages) { 19050 clearPackagePreferredActivitiesLPw(null, userId); 19051 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19052 // TODO: We have to reset the default SMS and Phone. This requires 19053 // significant refactoring to keep all default apps in the package 19054 // manager (cleaner but more work) or have the services provide 19055 // callbacks to the package manager to request a default app reset. 19056 applyFactoryDefaultBrowserLPw(userId); 19057 clearIntentFilterVerificationsLPw(userId); 19058 primeDomainVerificationsLPw(userId); 19059 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19060 scheduleWritePackageRestrictionsLocked(userId); 19061 } 19062 resetNetworkPolicies(userId); 19063 } finally { 19064 Binder.restoreCallingIdentity(identity); 19065 } 19066 } 19067 19068 @Override 19069 public int getPreferredActivities(List<IntentFilter> outFilters, 19070 List<ComponentName> outActivities, String packageName) { 19071 19072 int num = 0; 19073 final int userId = UserHandle.getCallingUserId(); 19074 // reader 19075 synchronized (mPackages) { 19076 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19077 if (pir != null) { 19078 final Iterator<PreferredActivity> it = pir.filterIterator(); 19079 while (it.hasNext()) { 19080 final PreferredActivity pa = it.next(); 19081 if (packageName == null 19082 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19083 && pa.mPref.mAlways)) { 19084 if (outFilters != null) { 19085 outFilters.add(new IntentFilter(pa)); 19086 } 19087 if (outActivities != null) { 19088 outActivities.add(pa.mPref.mComponent); 19089 } 19090 } 19091 } 19092 } 19093 } 19094 19095 return num; 19096 } 19097 19098 @Override 19099 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19100 int userId) { 19101 int callingUid = Binder.getCallingUid(); 19102 if (callingUid != Process.SYSTEM_UID) { 19103 throw new SecurityException( 19104 "addPersistentPreferredActivity can only be run by the system"); 19105 } 19106 if (filter.countActions() == 0) { 19107 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19108 return; 19109 } 19110 synchronized (mPackages) { 19111 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19112 ":"); 19113 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19114 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19115 new PersistentPreferredActivity(filter, activity)); 19116 scheduleWritePackageRestrictionsLocked(userId); 19117 postPreferredActivityChangedBroadcast(userId); 19118 } 19119 } 19120 19121 @Override 19122 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19123 int callingUid = Binder.getCallingUid(); 19124 if (callingUid != Process.SYSTEM_UID) { 19125 throw new SecurityException( 19126 "clearPackagePersistentPreferredActivities can only be run by the system"); 19127 } 19128 ArrayList<PersistentPreferredActivity> removed = null; 19129 boolean changed = false; 19130 synchronized (mPackages) { 19131 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19132 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19133 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19134 .valueAt(i); 19135 if (userId != thisUserId) { 19136 continue; 19137 } 19138 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19139 while (it.hasNext()) { 19140 PersistentPreferredActivity ppa = it.next(); 19141 // Mark entry for removal only if it matches the package name. 19142 if (ppa.mComponent.getPackageName().equals(packageName)) { 19143 if (removed == null) { 19144 removed = new ArrayList<PersistentPreferredActivity>(); 19145 } 19146 removed.add(ppa); 19147 } 19148 } 19149 if (removed != null) { 19150 for (int j=0; j<removed.size(); j++) { 19151 PersistentPreferredActivity ppa = removed.get(j); 19152 ppir.removeFilter(ppa); 19153 } 19154 changed = true; 19155 } 19156 } 19157 19158 if (changed) { 19159 scheduleWritePackageRestrictionsLocked(userId); 19160 postPreferredActivityChangedBroadcast(userId); 19161 } 19162 } 19163 } 19164 19165 /** 19166 * Common machinery for picking apart a restored XML blob and passing 19167 * it to a caller-supplied functor to be applied to the running system. 19168 */ 19169 private void restoreFromXml(XmlPullParser parser, int userId, 19170 String expectedStartTag, BlobXmlRestorer functor) 19171 throws IOException, XmlPullParserException { 19172 int type; 19173 while ((type = parser.next()) != XmlPullParser.START_TAG 19174 && type != XmlPullParser.END_DOCUMENT) { 19175 } 19176 if (type != XmlPullParser.START_TAG) { 19177 // oops didn't find a start tag?! 19178 if (DEBUG_BACKUP) { 19179 Slog.e(TAG, "Didn't find start tag during restore"); 19180 } 19181 return; 19182 } 19183Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19184 // this is supposed to be TAG_PREFERRED_BACKUP 19185 if (!expectedStartTag.equals(parser.getName())) { 19186 if (DEBUG_BACKUP) { 19187 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19188 } 19189 return; 19190 } 19191 19192 // skip interfering stuff, then we're aligned with the backing implementation 19193 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19194Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19195 functor.apply(parser, userId); 19196 } 19197 19198 private interface BlobXmlRestorer { 19199 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19200 } 19201 19202 /** 19203 * Non-Binder method, support for the backup/restore mechanism: write the 19204 * full set of preferred activities in its canonical XML format. Returns the 19205 * XML output as a byte array, or null if there is none. 19206 */ 19207 @Override 19208 public byte[] getPreferredActivityBackup(int userId) { 19209 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19210 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19211 } 19212 19213 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19214 try { 19215 final XmlSerializer serializer = new FastXmlSerializer(); 19216 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19217 serializer.startDocument(null, true); 19218 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19219 19220 synchronized (mPackages) { 19221 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19222 } 19223 19224 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19225 serializer.endDocument(); 19226 serializer.flush(); 19227 } catch (Exception e) { 19228 if (DEBUG_BACKUP) { 19229 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19230 } 19231 return null; 19232 } 19233 19234 return dataStream.toByteArray(); 19235 } 19236 19237 @Override 19238 public void restorePreferredActivities(byte[] backup, int userId) { 19239 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19240 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19241 } 19242 19243 try { 19244 final XmlPullParser parser = Xml.newPullParser(); 19245 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19246 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19247 new BlobXmlRestorer() { 19248 @Override 19249 public void apply(XmlPullParser parser, int userId) 19250 throws XmlPullParserException, IOException { 19251 synchronized (mPackages) { 19252 mSettings.readPreferredActivitiesLPw(parser, userId); 19253 } 19254 } 19255 } ); 19256 } catch (Exception e) { 19257 if (DEBUG_BACKUP) { 19258 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19259 } 19260 } 19261 } 19262 19263 /** 19264 * Non-Binder method, support for the backup/restore mechanism: write the 19265 * default browser (etc) settings in its canonical XML format. Returns the default 19266 * browser XML representation as a byte array, or null if there is none. 19267 */ 19268 @Override 19269 public byte[] getDefaultAppsBackup(int userId) { 19270 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19271 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19272 } 19273 19274 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19275 try { 19276 final XmlSerializer serializer = new FastXmlSerializer(); 19277 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19278 serializer.startDocument(null, true); 19279 serializer.startTag(null, TAG_DEFAULT_APPS); 19280 19281 synchronized (mPackages) { 19282 mSettings.writeDefaultAppsLPr(serializer, userId); 19283 } 19284 19285 serializer.endTag(null, TAG_DEFAULT_APPS); 19286 serializer.endDocument(); 19287 serializer.flush(); 19288 } catch (Exception e) { 19289 if (DEBUG_BACKUP) { 19290 Slog.e(TAG, "Unable to write default apps for backup", e); 19291 } 19292 return null; 19293 } 19294 19295 return dataStream.toByteArray(); 19296 } 19297 19298 @Override 19299 public void restoreDefaultApps(byte[] backup, int userId) { 19300 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19301 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19302 } 19303 19304 try { 19305 final XmlPullParser parser = Xml.newPullParser(); 19306 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19307 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19308 new BlobXmlRestorer() { 19309 @Override 19310 public void apply(XmlPullParser parser, int userId) 19311 throws XmlPullParserException, IOException { 19312 synchronized (mPackages) { 19313 mSettings.readDefaultAppsLPw(parser, userId); 19314 } 19315 } 19316 } ); 19317 } catch (Exception e) { 19318 if (DEBUG_BACKUP) { 19319 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19320 } 19321 } 19322 } 19323 19324 @Override 19325 public byte[] getIntentFilterVerificationBackup(int userId) { 19326 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19327 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19328 } 19329 19330 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19331 try { 19332 final XmlSerializer serializer = new FastXmlSerializer(); 19333 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19334 serializer.startDocument(null, true); 19335 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19336 19337 synchronized (mPackages) { 19338 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19339 } 19340 19341 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19342 serializer.endDocument(); 19343 serializer.flush(); 19344 } catch (Exception e) { 19345 if (DEBUG_BACKUP) { 19346 Slog.e(TAG, "Unable to write default apps for backup", e); 19347 } 19348 return null; 19349 } 19350 19351 return dataStream.toByteArray(); 19352 } 19353 19354 @Override 19355 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19356 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19357 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19358 } 19359 19360 try { 19361 final XmlPullParser parser = Xml.newPullParser(); 19362 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19363 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19364 new BlobXmlRestorer() { 19365 @Override 19366 public void apply(XmlPullParser parser, int userId) 19367 throws XmlPullParserException, IOException { 19368 synchronized (mPackages) { 19369 mSettings.readAllDomainVerificationsLPr(parser, userId); 19370 mSettings.writeLPr(); 19371 } 19372 } 19373 } ); 19374 } catch (Exception e) { 19375 if (DEBUG_BACKUP) { 19376 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19377 } 19378 } 19379 } 19380 19381 @Override 19382 public byte[] getPermissionGrantBackup(int userId) { 19383 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19384 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19385 } 19386 19387 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19388 try { 19389 final XmlSerializer serializer = new FastXmlSerializer(); 19390 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19391 serializer.startDocument(null, true); 19392 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19393 19394 synchronized (mPackages) { 19395 serializeRuntimePermissionGrantsLPr(serializer, userId); 19396 } 19397 19398 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19399 serializer.endDocument(); 19400 serializer.flush(); 19401 } catch (Exception e) { 19402 if (DEBUG_BACKUP) { 19403 Slog.e(TAG, "Unable to write default apps for backup", e); 19404 } 19405 return null; 19406 } 19407 19408 return dataStream.toByteArray(); 19409 } 19410 19411 @Override 19412 public void restorePermissionGrants(byte[] backup, int userId) { 19413 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19414 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19415 } 19416 19417 try { 19418 final XmlPullParser parser = Xml.newPullParser(); 19419 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19420 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19421 new BlobXmlRestorer() { 19422 @Override 19423 public void apply(XmlPullParser parser, int userId) 19424 throws XmlPullParserException, IOException { 19425 synchronized (mPackages) { 19426 processRestoredPermissionGrantsLPr(parser, userId); 19427 } 19428 } 19429 } ); 19430 } catch (Exception e) { 19431 if (DEBUG_BACKUP) { 19432 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19433 } 19434 } 19435 } 19436 19437 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19438 throws IOException { 19439 serializer.startTag(null, TAG_ALL_GRANTS); 19440 19441 final int N = mSettings.mPackages.size(); 19442 for (int i = 0; i < N; i++) { 19443 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19444 boolean pkgGrantsKnown = false; 19445 19446 PermissionsState packagePerms = ps.getPermissionsState(); 19447 19448 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19449 final int grantFlags = state.getFlags(); 19450 // only look at grants that are not system/policy fixed 19451 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19452 final boolean isGranted = state.isGranted(); 19453 // And only back up the user-twiddled state bits 19454 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19455 final String packageName = mSettings.mPackages.keyAt(i); 19456 if (!pkgGrantsKnown) { 19457 serializer.startTag(null, TAG_GRANT); 19458 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19459 pkgGrantsKnown = true; 19460 } 19461 19462 final boolean userSet = 19463 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19464 final boolean userFixed = 19465 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19466 final boolean revoke = 19467 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19468 19469 serializer.startTag(null, TAG_PERMISSION); 19470 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19471 if (isGranted) { 19472 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19473 } 19474 if (userSet) { 19475 serializer.attribute(null, ATTR_USER_SET, "true"); 19476 } 19477 if (userFixed) { 19478 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19479 } 19480 if (revoke) { 19481 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19482 } 19483 serializer.endTag(null, TAG_PERMISSION); 19484 } 19485 } 19486 } 19487 19488 if (pkgGrantsKnown) { 19489 serializer.endTag(null, TAG_GRANT); 19490 } 19491 } 19492 19493 serializer.endTag(null, TAG_ALL_GRANTS); 19494 } 19495 19496 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19497 throws XmlPullParserException, IOException { 19498 String pkgName = null; 19499 int outerDepth = parser.getDepth(); 19500 int type; 19501 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19502 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19503 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19504 continue; 19505 } 19506 19507 final String tagName = parser.getName(); 19508 if (tagName.equals(TAG_GRANT)) { 19509 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19510 if (DEBUG_BACKUP) { 19511 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19512 } 19513 } else if (tagName.equals(TAG_PERMISSION)) { 19514 19515 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19516 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19517 19518 int newFlagSet = 0; 19519 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19520 newFlagSet |= FLAG_PERMISSION_USER_SET; 19521 } 19522 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19523 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19524 } 19525 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19526 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19527 } 19528 if (DEBUG_BACKUP) { 19529 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19530 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19531 } 19532 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19533 if (ps != null) { 19534 // Already installed so we apply the grant immediately 19535 if (DEBUG_BACKUP) { 19536 Slog.v(TAG, " + already installed; applying"); 19537 } 19538 PermissionsState perms = ps.getPermissionsState(); 19539 BasePermission bp = mSettings.mPermissions.get(permName); 19540 if (bp != null) { 19541 if (isGranted) { 19542 perms.grantRuntimePermission(bp, userId); 19543 } 19544 if (newFlagSet != 0) { 19545 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19546 } 19547 } 19548 } else { 19549 // Need to wait for post-restore install to apply the grant 19550 if (DEBUG_BACKUP) { 19551 Slog.v(TAG, " - not yet installed; saving for later"); 19552 } 19553 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19554 isGranted, newFlagSet, userId); 19555 } 19556 } else { 19557 PackageManagerService.reportSettingsProblem(Log.WARN, 19558 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19559 XmlUtils.skipCurrentTag(parser); 19560 } 19561 } 19562 19563 scheduleWriteSettingsLocked(); 19564 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19565 } 19566 19567 @Override 19568 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19569 int sourceUserId, int targetUserId, int flags) { 19570 mContext.enforceCallingOrSelfPermission( 19571 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19572 int callingUid = Binder.getCallingUid(); 19573 enforceOwnerRights(ownerPackage, callingUid); 19574 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19575 if (intentFilter.countActions() == 0) { 19576 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19577 return; 19578 } 19579 synchronized (mPackages) { 19580 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19581 ownerPackage, targetUserId, flags); 19582 CrossProfileIntentResolver resolver = 19583 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19584 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19585 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19586 if (existing != null) { 19587 int size = existing.size(); 19588 for (int i = 0; i < size; i++) { 19589 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19590 return; 19591 } 19592 } 19593 } 19594 resolver.addFilter(newFilter); 19595 scheduleWritePackageRestrictionsLocked(sourceUserId); 19596 } 19597 } 19598 19599 @Override 19600 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19601 mContext.enforceCallingOrSelfPermission( 19602 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19603 int callingUid = Binder.getCallingUid(); 19604 enforceOwnerRights(ownerPackage, callingUid); 19605 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19606 synchronized (mPackages) { 19607 CrossProfileIntentResolver resolver = 19608 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19609 ArraySet<CrossProfileIntentFilter> set = 19610 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19611 for (CrossProfileIntentFilter filter : set) { 19612 if (filter.getOwnerPackage().equals(ownerPackage)) { 19613 resolver.removeFilter(filter); 19614 } 19615 } 19616 scheduleWritePackageRestrictionsLocked(sourceUserId); 19617 } 19618 } 19619 19620 // Enforcing that callingUid is owning pkg on userId 19621 private void enforceOwnerRights(String pkg, int callingUid) { 19622 // The system owns everything. 19623 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19624 return; 19625 } 19626 int callingUserId = UserHandle.getUserId(callingUid); 19627 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19628 if (pi == null) { 19629 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19630 + callingUserId); 19631 } 19632 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19633 throw new SecurityException("Calling uid " + callingUid 19634 + " does not own package " + pkg); 19635 } 19636 } 19637 19638 @Override 19639 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19640 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19641 } 19642 19643 private Intent getHomeIntent() { 19644 Intent intent = new Intent(Intent.ACTION_MAIN); 19645 intent.addCategory(Intent.CATEGORY_HOME); 19646 intent.addCategory(Intent.CATEGORY_DEFAULT); 19647 return intent; 19648 } 19649 19650 private IntentFilter getHomeFilter() { 19651 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19652 filter.addCategory(Intent.CATEGORY_HOME); 19653 filter.addCategory(Intent.CATEGORY_DEFAULT); 19654 return filter; 19655 } 19656 19657 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19658 int userId) { 19659 Intent intent = getHomeIntent(); 19660 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19661 PackageManager.GET_META_DATA, userId); 19662 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19663 true, false, false, userId); 19664 19665 allHomeCandidates.clear(); 19666 if (list != null) { 19667 for (ResolveInfo ri : list) { 19668 allHomeCandidates.add(ri); 19669 } 19670 } 19671 return (preferred == null || preferred.activityInfo == null) 19672 ? null 19673 : new ComponentName(preferred.activityInfo.packageName, 19674 preferred.activityInfo.name); 19675 } 19676 19677 @Override 19678 public void setHomeActivity(ComponentName comp, int userId) { 19679 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19680 getHomeActivitiesAsUser(homeActivities, userId); 19681 19682 boolean found = false; 19683 19684 final int size = homeActivities.size(); 19685 final ComponentName[] set = new ComponentName[size]; 19686 for (int i = 0; i < size; i++) { 19687 final ResolveInfo candidate = homeActivities.get(i); 19688 final ActivityInfo info = candidate.activityInfo; 19689 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19690 set[i] = activityName; 19691 if (!found && activityName.equals(comp)) { 19692 found = true; 19693 } 19694 } 19695 if (!found) { 19696 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19697 + userId); 19698 } 19699 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19700 set, comp, userId); 19701 } 19702 19703 private @Nullable String getSetupWizardPackageName() { 19704 final Intent intent = new Intent(Intent.ACTION_MAIN); 19705 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19706 19707 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19708 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19709 | MATCH_DISABLED_COMPONENTS, 19710 UserHandle.myUserId()); 19711 if (matches.size() == 1) { 19712 return matches.get(0).getComponentInfo().packageName; 19713 } else { 19714 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19715 + ": matches=" + matches); 19716 return null; 19717 } 19718 } 19719 19720 private @Nullable String getStorageManagerPackageName() { 19721 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19722 19723 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19724 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19725 | MATCH_DISABLED_COMPONENTS, 19726 UserHandle.myUserId()); 19727 if (matches.size() == 1) { 19728 return matches.get(0).getComponentInfo().packageName; 19729 } else { 19730 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19731 + matches.size() + ": matches=" + matches); 19732 return null; 19733 } 19734 } 19735 19736 @Override 19737 public void setApplicationEnabledSetting(String appPackageName, 19738 int newState, int flags, int userId, String callingPackage) { 19739 if (!sUserManager.exists(userId)) return; 19740 if (callingPackage == null) { 19741 callingPackage = Integer.toString(Binder.getCallingUid()); 19742 } 19743 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19744 } 19745 19746 @Override 19747 public void setComponentEnabledSetting(ComponentName componentName, 19748 int newState, int flags, int userId) { 19749 if (!sUserManager.exists(userId)) return; 19750 setEnabledSetting(componentName.getPackageName(), 19751 componentName.getClassName(), newState, flags, userId, null); 19752 } 19753 19754 private void setEnabledSetting(final String packageName, String className, int newState, 19755 final int flags, int userId, String callingPackage) { 19756 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19757 || newState == COMPONENT_ENABLED_STATE_ENABLED 19758 || newState == COMPONENT_ENABLED_STATE_DISABLED 19759 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19760 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19761 throw new IllegalArgumentException("Invalid new component state: " 19762 + newState); 19763 } 19764 PackageSetting pkgSetting; 19765 final int uid = Binder.getCallingUid(); 19766 final int permission; 19767 if (uid == Process.SYSTEM_UID) { 19768 permission = PackageManager.PERMISSION_GRANTED; 19769 } else { 19770 permission = mContext.checkCallingOrSelfPermission( 19771 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19772 } 19773 enforceCrossUserPermission(uid, userId, 19774 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19775 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19776 boolean sendNow = false; 19777 boolean isApp = (className == null); 19778 String componentName = isApp ? packageName : className; 19779 int packageUid = -1; 19780 ArrayList<String> components; 19781 19782 // writer 19783 synchronized (mPackages) { 19784 pkgSetting = mSettings.mPackages.get(packageName); 19785 if (pkgSetting == null) { 19786 if (className == null) { 19787 throw new IllegalArgumentException("Unknown package: " + packageName); 19788 } 19789 throw new IllegalArgumentException( 19790 "Unknown component: " + packageName + "/" + className); 19791 } 19792 } 19793 19794 // Limit who can change which apps 19795 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19796 // Don't allow apps that don't have permission to modify other apps 19797 if (!allowedByPermission) { 19798 throw new SecurityException( 19799 "Permission Denial: attempt to change component state from pid=" 19800 + Binder.getCallingPid() 19801 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19802 } 19803 // Don't allow changing protected packages. 19804 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19805 throw new SecurityException("Cannot disable a protected package: " + packageName); 19806 } 19807 } 19808 19809 synchronized (mPackages) { 19810 if (uid == Process.SHELL_UID 19811 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19812 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19813 // unless it is a test package. 19814 int oldState = pkgSetting.getEnabled(userId); 19815 if (className == null 19816 && 19817 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19818 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19819 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19820 && 19821 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19822 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19823 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19824 // ok 19825 } else { 19826 throw new SecurityException( 19827 "Shell cannot change component state for " + packageName + "/" 19828 + className + " to " + newState); 19829 } 19830 } 19831 if (className == null) { 19832 // We're dealing with an application/package level state change 19833 if (pkgSetting.getEnabled(userId) == newState) { 19834 // Nothing to do 19835 return; 19836 } 19837 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19838 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19839 // Don't care about who enables an app. 19840 callingPackage = null; 19841 } 19842 pkgSetting.setEnabled(newState, userId, callingPackage); 19843 // pkgSetting.pkg.mSetEnabled = newState; 19844 } else { 19845 // We're dealing with a component level state change 19846 // First, verify that this is a valid class name. 19847 PackageParser.Package pkg = pkgSetting.pkg; 19848 if (pkg == null || !pkg.hasComponentClassName(className)) { 19849 if (pkg != null && 19850 pkg.applicationInfo.targetSdkVersion >= 19851 Build.VERSION_CODES.JELLY_BEAN) { 19852 throw new IllegalArgumentException("Component class " + className 19853 + " does not exist in " + packageName); 19854 } else { 19855 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19856 + className + " does not exist in " + packageName); 19857 } 19858 } 19859 switch (newState) { 19860 case COMPONENT_ENABLED_STATE_ENABLED: 19861 if (!pkgSetting.enableComponentLPw(className, userId)) { 19862 return; 19863 } 19864 break; 19865 case COMPONENT_ENABLED_STATE_DISABLED: 19866 if (!pkgSetting.disableComponentLPw(className, userId)) { 19867 return; 19868 } 19869 break; 19870 case COMPONENT_ENABLED_STATE_DEFAULT: 19871 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19872 return; 19873 } 19874 break; 19875 default: 19876 Slog.e(TAG, "Invalid new component state: " + newState); 19877 return; 19878 } 19879 } 19880 scheduleWritePackageRestrictionsLocked(userId); 19881 updateSequenceNumberLP(packageName, new int[] { userId }); 19882 components = mPendingBroadcasts.get(userId, packageName); 19883 final boolean newPackage = components == null; 19884 if (newPackage) { 19885 components = new ArrayList<String>(); 19886 } 19887 if (!components.contains(componentName)) { 19888 components.add(componentName); 19889 } 19890 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19891 sendNow = true; 19892 // Purge entry from pending broadcast list if another one exists already 19893 // since we are sending one right away. 19894 mPendingBroadcasts.remove(userId, packageName); 19895 } else { 19896 if (newPackage) { 19897 mPendingBroadcasts.put(userId, packageName, components); 19898 } 19899 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19900 // Schedule a message 19901 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19902 } 19903 } 19904 } 19905 19906 long callingId = Binder.clearCallingIdentity(); 19907 try { 19908 if (sendNow) { 19909 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19910 sendPackageChangedBroadcast(packageName, 19911 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19912 } 19913 } finally { 19914 Binder.restoreCallingIdentity(callingId); 19915 } 19916 } 19917 19918 @Override 19919 public void flushPackageRestrictionsAsUser(int userId) { 19920 if (!sUserManager.exists(userId)) { 19921 return; 19922 } 19923 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19924 false /* checkShell */, "flushPackageRestrictions"); 19925 synchronized (mPackages) { 19926 mSettings.writePackageRestrictionsLPr(userId); 19927 mDirtyUsers.remove(userId); 19928 if (mDirtyUsers.isEmpty()) { 19929 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19930 } 19931 } 19932 } 19933 19934 private void sendPackageChangedBroadcast(String packageName, 19935 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19936 if (DEBUG_INSTALL) 19937 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19938 + componentNames); 19939 Bundle extras = new Bundle(4); 19940 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19941 String nameList[] = new String[componentNames.size()]; 19942 componentNames.toArray(nameList); 19943 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19944 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19945 extras.putInt(Intent.EXTRA_UID, packageUid); 19946 // If this is not reporting a change of the overall package, then only send it 19947 // to registered receivers. We don't want to launch a swath of apps for every 19948 // little component state change. 19949 final int flags = !componentNames.contains(packageName) 19950 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19951 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19952 new int[] {UserHandle.getUserId(packageUid)}); 19953 } 19954 19955 @Override 19956 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19957 if (!sUserManager.exists(userId)) return; 19958 final int uid = Binder.getCallingUid(); 19959 final int permission = mContext.checkCallingOrSelfPermission( 19960 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19961 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19962 enforceCrossUserPermission(uid, userId, 19963 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19964 // writer 19965 synchronized (mPackages) { 19966 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19967 allowedByPermission, uid, userId)) { 19968 scheduleWritePackageRestrictionsLocked(userId); 19969 } 19970 } 19971 } 19972 19973 @Override 19974 public String getInstallerPackageName(String packageName) { 19975 // reader 19976 synchronized (mPackages) { 19977 return mSettings.getInstallerPackageNameLPr(packageName); 19978 } 19979 } 19980 19981 public boolean isOrphaned(String packageName) { 19982 // reader 19983 synchronized (mPackages) { 19984 return mSettings.isOrphaned(packageName); 19985 } 19986 } 19987 19988 @Override 19989 public int getApplicationEnabledSetting(String packageName, int userId) { 19990 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19991 int uid = Binder.getCallingUid(); 19992 enforceCrossUserPermission(uid, userId, 19993 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19994 // reader 19995 synchronized (mPackages) { 19996 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19997 } 19998 } 19999 20000 @Override 20001 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20002 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20003 int uid = Binder.getCallingUid(); 20004 enforceCrossUserPermission(uid, userId, 20005 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20006 // reader 20007 synchronized (mPackages) { 20008 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20009 } 20010 } 20011 20012 @Override 20013 public void enterSafeMode() { 20014 enforceSystemOrRoot("Only the system can request entering safe mode"); 20015 20016 if (!mSystemReady) { 20017 mSafeMode = true; 20018 } 20019 } 20020 20021 @Override 20022 public void systemReady() { 20023 mSystemReady = true; 20024 20025 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20026 // disabled after already being started. 20027 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20028 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20029 20030 // Read the compatibilty setting when the system is ready. 20031 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20032 mContext.getContentResolver(), 20033 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20034 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20035 if (DEBUG_SETTINGS) { 20036 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20037 } 20038 20039 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20040 20041 synchronized (mPackages) { 20042 // Verify that all of the preferred activity components actually 20043 // exist. It is possible for applications to be updated and at 20044 // that point remove a previously declared activity component that 20045 // had been set as a preferred activity. We try to clean this up 20046 // the next time we encounter that preferred activity, but it is 20047 // possible for the user flow to never be able to return to that 20048 // situation so here we do a sanity check to make sure we haven't 20049 // left any junk around. 20050 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20051 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20052 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20053 removed.clear(); 20054 for (PreferredActivity pa : pir.filterSet()) { 20055 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20056 removed.add(pa); 20057 } 20058 } 20059 if (removed.size() > 0) { 20060 for (int r=0; r<removed.size(); r++) { 20061 PreferredActivity pa = removed.get(r); 20062 Slog.w(TAG, "Removing dangling preferred activity: " 20063 + pa.mPref.mComponent); 20064 pir.removeFilter(pa); 20065 } 20066 mSettings.writePackageRestrictionsLPr( 20067 mSettings.mPreferredActivities.keyAt(i)); 20068 } 20069 } 20070 20071 for (int userId : UserManagerService.getInstance().getUserIds()) { 20072 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20073 grantPermissionsUserIds = ArrayUtils.appendInt( 20074 grantPermissionsUserIds, userId); 20075 } 20076 } 20077 } 20078 sUserManager.systemReady(); 20079 20080 // If we upgraded grant all default permissions before kicking off. 20081 for (int userId : grantPermissionsUserIds) { 20082 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20083 } 20084 20085 // If we did not grant default permissions, we preload from this the 20086 // default permission exceptions lazily to ensure we don't hit the 20087 // disk on a new user creation. 20088 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20089 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20090 } 20091 20092 // Kick off any messages waiting for system ready 20093 if (mPostSystemReadyMessages != null) { 20094 for (Message msg : mPostSystemReadyMessages) { 20095 msg.sendToTarget(); 20096 } 20097 mPostSystemReadyMessages = null; 20098 } 20099 20100 // Watch for external volumes that come and go over time 20101 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20102 storage.registerListener(mStorageListener); 20103 20104 mInstallerService.systemReady(); 20105 mPackageDexOptimizer.systemReady(); 20106 20107 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20108 StorageManagerInternal.class); 20109 StorageManagerInternal.addExternalStoragePolicy( 20110 new StorageManagerInternal.ExternalStorageMountPolicy() { 20111 @Override 20112 public int getMountMode(int uid, String packageName) { 20113 if (Process.isIsolated(uid)) { 20114 return Zygote.MOUNT_EXTERNAL_NONE; 20115 } 20116 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20117 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20118 } 20119 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20120 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20121 } 20122 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20123 return Zygote.MOUNT_EXTERNAL_READ; 20124 } 20125 return Zygote.MOUNT_EXTERNAL_WRITE; 20126 } 20127 20128 @Override 20129 public boolean hasExternalStorage(int uid, String packageName) { 20130 return true; 20131 } 20132 }); 20133 20134 // Now that we're mostly running, clean up stale users and apps 20135 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20136 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20137 20138 if (mPrivappPermissionsViolations != null) { 20139 Slog.wtf(TAG,"Signature|privileged permissions not in " 20140 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20141 mPrivappPermissionsViolations = null; 20142 } 20143 } 20144 20145 public void waitForAppDataPrepared() { 20146 if (mPrepareAppDataFuture == null) { 20147 return; 20148 } 20149 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20150 mPrepareAppDataFuture = null; 20151 } 20152 20153 @Override 20154 public boolean isSafeMode() { 20155 return mSafeMode; 20156 } 20157 20158 @Override 20159 public boolean hasSystemUidErrors() { 20160 return mHasSystemUidErrors; 20161 } 20162 20163 static String arrayToString(int[] array) { 20164 StringBuffer buf = new StringBuffer(128); 20165 buf.append('['); 20166 if (array != null) { 20167 for (int i=0; i<array.length; i++) { 20168 if (i > 0) buf.append(", "); 20169 buf.append(array[i]); 20170 } 20171 } 20172 buf.append(']'); 20173 return buf.toString(); 20174 } 20175 20176 static class DumpState { 20177 public static final int DUMP_LIBS = 1 << 0; 20178 public static final int DUMP_FEATURES = 1 << 1; 20179 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20180 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20181 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20182 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20183 public static final int DUMP_PERMISSIONS = 1 << 6; 20184 public static final int DUMP_PACKAGES = 1 << 7; 20185 public static final int DUMP_SHARED_USERS = 1 << 8; 20186 public static final int DUMP_MESSAGES = 1 << 9; 20187 public static final int DUMP_PROVIDERS = 1 << 10; 20188 public static final int DUMP_VERIFIERS = 1 << 11; 20189 public static final int DUMP_PREFERRED = 1 << 12; 20190 public static final int DUMP_PREFERRED_XML = 1 << 13; 20191 public static final int DUMP_KEYSETS = 1 << 14; 20192 public static final int DUMP_VERSION = 1 << 15; 20193 public static final int DUMP_INSTALLS = 1 << 16; 20194 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20195 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20196 public static final int DUMP_FROZEN = 1 << 19; 20197 public static final int DUMP_DEXOPT = 1 << 20; 20198 public static final int DUMP_COMPILER_STATS = 1 << 21; 20199 20200 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20201 20202 private int mTypes; 20203 20204 private int mOptions; 20205 20206 private boolean mTitlePrinted; 20207 20208 private SharedUserSetting mSharedUser; 20209 20210 public boolean isDumping(int type) { 20211 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20212 return true; 20213 } 20214 20215 return (mTypes & type) != 0; 20216 } 20217 20218 public void setDump(int type) { 20219 mTypes |= type; 20220 } 20221 20222 public boolean isOptionEnabled(int option) { 20223 return (mOptions & option) != 0; 20224 } 20225 20226 public void setOptionEnabled(int option) { 20227 mOptions |= option; 20228 } 20229 20230 public boolean onTitlePrinted() { 20231 final boolean printed = mTitlePrinted; 20232 mTitlePrinted = true; 20233 return printed; 20234 } 20235 20236 public boolean getTitlePrinted() { 20237 return mTitlePrinted; 20238 } 20239 20240 public void setTitlePrinted(boolean enabled) { 20241 mTitlePrinted = enabled; 20242 } 20243 20244 public SharedUserSetting getSharedUser() { 20245 return mSharedUser; 20246 } 20247 20248 public void setSharedUser(SharedUserSetting user) { 20249 mSharedUser = user; 20250 } 20251 } 20252 20253 @Override 20254 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20255 FileDescriptor err, String[] args, ShellCallback callback, 20256 ResultReceiver resultReceiver) { 20257 (new PackageManagerShellCommand(this)).exec( 20258 this, in, out, err, args, callback, resultReceiver); 20259 } 20260 20261 @Override 20262 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20263 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20264 != PackageManager.PERMISSION_GRANTED) { 20265 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20266 + Binder.getCallingPid() 20267 + ", uid=" + Binder.getCallingUid() 20268 + " without permission " 20269 + android.Manifest.permission.DUMP); 20270 return; 20271 } 20272 20273 DumpState dumpState = new DumpState(); 20274 boolean fullPreferred = false; 20275 boolean checkin = false; 20276 20277 String packageName = null; 20278 ArraySet<String> permissionNames = null; 20279 20280 int opti = 0; 20281 while (opti < args.length) { 20282 String opt = args[opti]; 20283 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20284 break; 20285 } 20286 opti++; 20287 20288 if ("-a".equals(opt)) { 20289 // Right now we only know how to print all. 20290 } else if ("-h".equals(opt)) { 20291 pw.println("Package manager dump options:"); 20292 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20293 pw.println(" --checkin: dump for a checkin"); 20294 pw.println(" -f: print details of intent filters"); 20295 pw.println(" -h: print this help"); 20296 pw.println(" cmd may be one of:"); 20297 pw.println(" l[ibraries]: list known shared libraries"); 20298 pw.println(" f[eatures]: list device features"); 20299 pw.println(" k[eysets]: print known keysets"); 20300 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20301 pw.println(" perm[issions]: dump permissions"); 20302 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20303 pw.println(" pref[erred]: print preferred package settings"); 20304 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20305 pw.println(" prov[iders]: dump content providers"); 20306 pw.println(" p[ackages]: dump installed packages"); 20307 pw.println(" s[hared-users]: dump shared user IDs"); 20308 pw.println(" m[essages]: print collected runtime messages"); 20309 pw.println(" v[erifiers]: print package verifier info"); 20310 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20311 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20312 pw.println(" version: print database version info"); 20313 pw.println(" write: write current settings now"); 20314 pw.println(" installs: details about install sessions"); 20315 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20316 pw.println(" dexopt: dump dexopt state"); 20317 pw.println(" compiler-stats: dump compiler statistics"); 20318 pw.println(" <package.name>: info about given package"); 20319 return; 20320 } else if ("--checkin".equals(opt)) { 20321 checkin = true; 20322 } else if ("-f".equals(opt)) { 20323 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20324 } else { 20325 pw.println("Unknown argument: " + opt + "; use -h for help"); 20326 } 20327 } 20328 20329 // Is the caller requesting to dump a particular piece of data? 20330 if (opti < args.length) { 20331 String cmd = args[opti]; 20332 opti++; 20333 // Is this a package name? 20334 if ("android".equals(cmd) || cmd.contains(".")) { 20335 packageName = cmd; 20336 // When dumping a single package, we always dump all of its 20337 // filter information since the amount of data will be reasonable. 20338 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20339 } else if ("check-permission".equals(cmd)) { 20340 if (opti >= args.length) { 20341 pw.println("Error: check-permission missing permission argument"); 20342 return; 20343 } 20344 String perm = args[opti]; 20345 opti++; 20346 if (opti >= args.length) { 20347 pw.println("Error: check-permission missing package argument"); 20348 return; 20349 } 20350 20351 String pkg = args[opti]; 20352 opti++; 20353 int user = UserHandle.getUserId(Binder.getCallingUid()); 20354 if (opti < args.length) { 20355 try { 20356 user = Integer.parseInt(args[opti]); 20357 } catch (NumberFormatException e) { 20358 pw.println("Error: check-permission user argument is not a number: " 20359 + args[opti]); 20360 return; 20361 } 20362 } 20363 20364 // Normalize package name to handle renamed packages and static libs 20365 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20366 20367 pw.println(checkPermission(perm, pkg, user)); 20368 return; 20369 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20370 dumpState.setDump(DumpState.DUMP_LIBS); 20371 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20372 dumpState.setDump(DumpState.DUMP_FEATURES); 20373 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20374 if (opti >= args.length) { 20375 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20376 | DumpState.DUMP_SERVICE_RESOLVERS 20377 | DumpState.DUMP_RECEIVER_RESOLVERS 20378 | DumpState.DUMP_CONTENT_RESOLVERS); 20379 } else { 20380 while (opti < args.length) { 20381 String name = args[opti]; 20382 if ("a".equals(name) || "activity".equals(name)) { 20383 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20384 } else if ("s".equals(name) || "service".equals(name)) { 20385 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20386 } else if ("r".equals(name) || "receiver".equals(name)) { 20387 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20388 } else if ("c".equals(name) || "content".equals(name)) { 20389 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20390 } else { 20391 pw.println("Error: unknown resolver table type: " + name); 20392 return; 20393 } 20394 opti++; 20395 } 20396 } 20397 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20398 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20399 } else if ("permission".equals(cmd)) { 20400 if (opti >= args.length) { 20401 pw.println("Error: permission requires permission name"); 20402 return; 20403 } 20404 permissionNames = new ArraySet<>(); 20405 while (opti < args.length) { 20406 permissionNames.add(args[opti]); 20407 opti++; 20408 } 20409 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20410 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20411 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20412 dumpState.setDump(DumpState.DUMP_PREFERRED); 20413 } else if ("preferred-xml".equals(cmd)) { 20414 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20415 if (opti < args.length && "--full".equals(args[opti])) { 20416 fullPreferred = true; 20417 opti++; 20418 } 20419 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20420 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20421 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20422 dumpState.setDump(DumpState.DUMP_PACKAGES); 20423 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20424 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20425 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20426 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20427 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20428 dumpState.setDump(DumpState.DUMP_MESSAGES); 20429 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20430 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20431 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20432 || "intent-filter-verifiers".equals(cmd)) { 20433 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20434 } else if ("version".equals(cmd)) { 20435 dumpState.setDump(DumpState.DUMP_VERSION); 20436 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20437 dumpState.setDump(DumpState.DUMP_KEYSETS); 20438 } else if ("installs".equals(cmd)) { 20439 dumpState.setDump(DumpState.DUMP_INSTALLS); 20440 } else if ("frozen".equals(cmd)) { 20441 dumpState.setDump(DumpState.DUMP_FROZEN); 20442 } else if ("dexopt".equals(cmd)) { 20443 dumpState.setDump(DumpState.DUMP_DEXOPT); 20444 } else if ("compiler-stats".equals(cmd)) { 20445 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20446 } else if ("write".equals(cmd)) { 20447 synchronized (mPackages) { 20448 mSettings.writeLPr(); 20449 pw.println("Settings written."); 20450 return; 20451 } 20452 } 20453 } 20454 20455 if (checkin) { 20456 pw.println("vers,1"); 20457 } 20458 20459 // reader 20460 synchronized (mPackages) { 20461 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20462 if (!checkin) { 20463 if (dumpState.onTitlePrinted()) 20464 pw.println(); 20465 pw.println("Database versions:"); 20466 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20467 } 20468 } 20469 20470 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20471 if (!checkin) { 20472 if (dumpState.onTitlePrinted()) 20473 pw.println(); 20474 pw.println("Verifiers:"); 20475 pw.print(" Required: "); 20476 pw.print(mRequiredVerifierPackage); 20477 pw.print(" (uid="); 20478 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20479 UserHandle.USER_SYSTEM)); 20480 pw.println(")"); 20481 } else if (mRequiredVerifierPackage != null) { 20482 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20483 pw.print(","); 20484 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20485 UserHandle.USER_SYSTEM)); 20486 } 20487 } 20488 20489 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20490 packageName == null) { 20491 if (mIntentFilterVerifierComponent != null) { 20492 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20493 if (!checkin) { 20494 if (dumpState.onTitlePrinted()) 20495 pw.println(); 20496 pw.println("Intent Filter Verifier:"); 20497 pw.print(" Using: "); 20498 pw.print(verifierPackageName); 20499 pw.print(" (uid="); 20500 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20501 UserHandle.USER_SYSTEM)); 20502 pw.println(")"); 20503 } else if (verifierPackageName != null) { 20504 pw.print("ifv,"); pw.print(verifierPackageName); 20505 pw.print(","); 20506 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20507 UserHandle.USER_SYSTEM)); 20508 } 20509 } else { 20510 pw.println(); 20511 pw.println("No Intent Filter Verifier available!"); 20512 } 20513 } 20514 20515 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20516 boolean printedHeader = false; 20517 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20518 while (it.hasNext()) { 20519 String libName = it.next(); 20520 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20521 if (versionedLib == null) { 20522 continue; 20523 } 20524 final int versionCount = versionedLib.size(); 20525 for (int i = 0; i < versionCount; i++) { 20526 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20527 if (!checkin) { 20528 if (!printedHeader) { 20529 if (dumpState.onTitlePrinted()) 20530 pw.println(); 20531 pw.println("Libraries:"); 20532 printedHeader = true; 20533 } 20534 pw.print(" "); 20535 } else { 20536 pw.print("lib,"); 20537 } 20538 pw.print(libEntry.info.getName()); 20539 if (libEntry.info.isStatic()) { 20540 pw.print(" version=" + libEntry.info.getVersion()); 20541 } 20542 if (!checkin) { 20543 pw.print(" -> "); 20544 } 20545 if (libEntry.path != null) { 20546 pw.print(" (jar) "); 20547 pw.print(libEntry.path); 20548 } else { 20549 pw.print(" (apk) "); 20550 pw.print(libEntry.apk); 20551 } 20552 pw.println(); 20553 } 20554 } 20555 } 20556 20557 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20558 if (dumpState.onTitlePrinted()) 20559 pw.println(); 20560 if (!checkin) { 20561 pw.println("Features:"); 20562 } 20563 20564 synchronized (mAvailableFeatures) { 20565 for (FeatureInfo feat : mAvailableFeatures.values()) { 20566 if (checkin) { 20567 pw.print("feat,"); 20568 pw.print(feat.name); 20569 pw.print(","); 20570 pw.println(feat.version); 20571 } else { 20572 pw.print(" "); 20573 pw.print(feat.name); 20574 if (feat.version > 0) { 20575 pw.print(" version="); 20576 pw.print(feat.version); 20577 } 20578 pw.println(); 20579 } 20580 } 20581 } 20582 } 20583 20584 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20585 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20586 : "Activity Resolver Table:", " ", packageName, 20587 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20588 dumpState.setTitlePrinted(true); 20589 } 20590 } 20591 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20592 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20593 : "Receiver Resolver Table:", " ", packageName, 20594 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20595 dumpState.setTitlePrinted(true); 20596 } 20597 } 20598 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20599 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20600 : "Service Resolver Table:", " ", packageName, 20601 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20602 dumpState.setTitlePrinted(true); 20603 } 20604 } 20605 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20606 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20607 : "Provider Resolver Table:", " ", packageName, 20608 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20609 dumpState.setTitlePrinted(true); 20610 } 20611 } 20612 20613 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20614 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20615 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20616 int user = mSettings.mPreferredActivities.keyAt(i); 20617 if (pir.dump(pw, 20618 dumpState.getTitlePrinted() 20619 ? "\nPreferred Activities User " + user + ":" 20620 : "Preferred Activities User " + user + ":", " ", 20621 packageName, true, false)) { 20622 dumpState.setTitlePrinted(true); 20623 } 20624 } 20625 } 20626 20627 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20628 pw.flush(); 20629 FileOutputStream fout = new FileOutputStream(fd); 20630 BufferedOutputStream str = new BufferedOutputStream(fout); 20631 XmlSerializer serializer = new FastXmlSerializer(); 20632 try { 20633 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20634 serializer.startDocument(null, true); 20635 serializer.setFeature( 20636 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20637 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20638 serializer.endDocument(); 20639 serializer.flush(); 20640 } catch (IllegalArgumentException e) { 20641 pw.println("Failed writing: " + e); 20642 } catch (IllegalStateException e) { 20643 pw.println("Failed writing: " + e); 20644 } catch (IOException e) { 20645 pw.println("Failed writing: " + e); 20646 } 20647 } 20648 20649 if (!checkin 20650 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20651 && packageName == null) { 20652 pw.println(); 20653 int count = mSettings.mPackages.size(); 20654 if (count == 0) { 20655 pw.println("No applications!"); 20656 pw.println(); 20657 } else { 20658 final String prefix = " "; 20659 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20660 if (allPackageSettings.size() == 0) { 20661 pw.println("No domain preferred apps!"); 20662 pw.println(); 20663 } else { 20664 pw.println("App verification status:"); 20665 pw.println(); 20666 count = 0; 20667 for (PackageSetting ps : allPackageSettings) { 20668 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20669 if (ivi == null || ivi.getPackageName() == null) continue; 20670 pw.println(prefix + "Package: " + ivi.getPackageName()); 20671 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20672 pw.println(prefix + "Status: " + ivi.getStatusString()); 20673 pw.println(); 20674 count++; 20675 } 20676 if (count == 0) { 20677 pw.println(prefix + "No app verification established."); 20678 pw.println(); 20679 } 20680 for (int userId : sUserManager.getUserIds()) { 20681 pw.println("App linkages for user " + userId + ":"); 20682 pw.println(); 20683 count = 0; 20684 for (PackageSetting ps : allPackageSettings) { 20685 final long status = ps.getDomainVerificationStatusForUser(userId); 20686 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20687 && !DEBUG_DOMAIN_VERIFICATION) { 20688 continue; 20689 } 20690 pw.println(prefix + "Package: " + ps.name); 20691 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20692 String statusStr = IntentFilterVerificationInfo. 20693 getStatusStringFromValue(status); 20694 pw.println(prefix + "Status: " + statusStr); 20695 pw.println(); 20696 count++; 20697 } 20698 if (count == 0) { 20699 pw.println(prefix + "No configured app linkages."); 20700 pw.println(); 20701 } 20702 } 20703 } 20704 } 20705 } 20706 20707 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20708 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20709 if (packageName == null && permissionNames == null) { 20710 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20711 if (iperm == 0) { 20712 if (dumpState.onTitlePrinted()) 20713 pw.println(); 20714 pw.println("AppOp Permissions:"); 20715 } 20716 pw.print(" AppOp Permission "); 20717 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20718 pw.println(":"); 20719 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20720 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20721 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20722 } 20723 } 20724 } 20725 } 20726 20727 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20728 boolean printedSomething = false; 20729 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20730 if (packageName != null && !packageName.equals(p.info.packageName)) { 20731 continue; 20732 } 20733 if (!printedSomething) { 20734 if (dumpState.onTitlePrinted()) 20735 pw.println(); 20736 pw.println("Registered ContentProviders:"); 20737 printedSomething = true; 20738 } 20739 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20740 pw.print(" "); pw.println(p.toString()); 20741 } 20742 printedSomething = false; 20743 for (Map.Entry<String, PackageParser.Provider> entry : 20744 mProvidersByAuthority.entrySet()) { 20745 PackageParser.Provider p = entry.getValue(); 20746 if (packageName != null && !packageName.equals(p.info.packageName)) { 20747 continue; 20748 } 20749 if (!printedSomething) { 20750 if (dumpState.onTitlePrinted()) 20751 pw.println(); 20752 pw.println("ContentProvider Authorities:"); 20753 printedSomething = true; 20754 } 20755 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20756 pw.print(" "); pw.println(p.toString()); 20757 if (p.info != null && p.info.applicationInfo != null) { 20758 final String appInfo = p.info.applicationInfo.toString(); 20759 pw.print(" applicationInfo="); pw.println(appInfo); 20760 } 20761 } 20762 } 20763 20764 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20765 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20766 } 20767 20768 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20769 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20770 } 20771 20772 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20773 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20774 } 20775 20776 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20777 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20778 } 20779 20780 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20781 // XXX should handle packageName != null by dumping only install data that 20782 // the given package is involved with. 20783 if (dumpState.onTitlePrinted()) pw.println(); 20784 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20785 } 20786 20787 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20788 // XXX should handle packageName != null by dumping only install data that 20789 // the given package is involved with. 20790 if (dumpState.onTitlePrinted()) pw.println(); 20791 20792 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20793 ipw.println(); 20794 ipw.println("Frozen packages:"); 20795 ipw.increaseIndent(); 20796 if (mFrozenPackages.size() == 0) { 20797 ipw.println("(none)"); 20798 } else { 20799 for (int i = 0; i < mFrozenPackages.size(); i++) { 20800 ipw.println(mFrozenPackages.valueAt(i)); 20801 } 20802 } 20803 ipw.decreaseIndent(); 20804 } 20805 20806 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20807 if (dumpState.onTitlePrinted()) pw.println(); 20808 dumpDexoptStateLPr(pw, packageName); 20809 } 20810 20811 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20812 if (dumpState.onTitlePrinted()) pw.println(); 20813 dumpCompilerStatsLPr(pw, packageName); 20814 } 20815 20816 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20817 if (dumpState.onTitlePrinted()) pw.println(); 20818 mSettings.dumpReadMessagesLPr(pw, dumpState); 20819 20820 pw.println(); 20821 pw.println("Package warning messages:"); 20822 BufferedReader in = null; 20823 String line = null; 20824 try { 20825 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20826 while ((line = in.readLine()) != null) { 20827 if (line.contains("ignored: updated version")) continue; 20828 pw.println(line); 20829 } 20830 } catch (IOException ignored) { 20831 } finally { 20832 IoUtils.closeQuietly(in); 20833 } 20834 } 20835 20836 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20837 BufferedReader in = null; 20838 String line = null; 20839 try { 20840 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20841 while ((line = in.readLine()) != null) { 20842 if (line.contains("ignored: updated version")) continue; 20843 pw.print("msg,"); 20844 pw.println(line); 20845 } 20846 } catch (IOException ignored) { 20847 } finally { 20848 IoUtils.closeQuietly(in); 20849 } 20850 } 20851 } 20852 } 20853 20854 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20855 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20856 ipw.println(); 20857 ipw.println("Dexopt state:"); 20858 ipw.increaseIndent(); 20859 Collection<PackageParser.Package> packages = null; 20860 if (packageName != null) { 20861 PackageParser.Package targetPackage = mPackages.get(packageName); 20862 if (targetPackage != null) { 20863 packages = Collections.singletonList(targetPackage); 20864 } else { 20865 ipw.println("Unable to find package: " + packageName); 20866 return; 20867 } 20868 } else { 20869 packages = mPackages.values(); 20870 } 20871 20872 for (PackageParser.Package pkg : packages) { 20873 ipw.println("[" + pkg.packageName + "]"); 20874 ipw.increaseIndent(); 20875 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20876 ipw.decreaseIndent(); 20877 } 20878 } 20879 20880 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20881 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20882 ipw.println(); 20883 ipw.println("Compiler stats:"); 20884 ipw.increaseIndent(); 20885 Collection<PackageParser.Package> packages = null; 20886 if (packageName != null) { 20887 PackageParser.Package targetPackage = mPackages.get(packageName); 20888 if (targetPackage != null) { 20889 packages = Collections.singletonList(targetPackage); 20890 } else { 20891 ipw.println("Unable to find package: " + packageName); 20892 return; 20893 } 20894 } else { 20895 packages = mPackages.values(); 20896 } 20897 20898 for (PackageParser.Package pkg : packages) { 20899 ipw.println("[" + pkg.packageName + "]"); 20900 ipw.increaseIndent(); 20901 20902 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20903 if (stats == null) { 20904 ipw.println("(No recorded stats)"); 20905 } else { 20906 stats.dump(ipw); 20907 } 20908 ipw.decreaseIndent(); 20909 } 20910 } 20911 20912 private String dumpDomainString(String packageName) { 20913 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20914 .getList(); 20915 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20916 20917 ArraySet<String> result = new ArraySet<>(); 20918 if (iviList.size() > 0) { 20919 for (IntentFilterVerificationInfo ivi : iviList) { 20920 for (String host : ivi.getDomains()) { 20921 result.add(host); 20922 } 20923 } 20924 } 20925 if (filters != null && filters.size() > 0) { 20926 for (IntentFilter filter : filters) { 20927 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 20928 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 20929 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 20930 result.addAll(filter.getHostsList()); 20931 } 20932 } 20933 } 20934 20935 StringBuilder sb = new StringBuilder(result.size() * 16); 20936 for (String domain : result) { 20937 if (sb.length() > 0) sb.append(" "); 20938 sb.append(domain); 20939 } 20940 return sb.toString(); 20941 } 20942 20943 // ------- apps on sdcard specific code ------- 20944 static final boolean DEBUG_SD_INSTALL = false; 20945 20946 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 20947 20948 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 20949 20950 private boolean mMediaMounted = false; 20951 20952 static String getEncryptKey() { 20953 try { 20954 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 20955 SD_ENCRYPTION_KEYSTORE_NAME); 20956 if (sdEncKey == null) { 20957 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 20958 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 20959 if (sdEncKey == null) { 20960 Slog.e(TAG, "Failed to create encryption keys"); 20961 return null; 20962 } 20963 } 20964 return sdEncKey; 20965 } catch (NoSuchAlgorithmException nsae) { 20966 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 20967 return null; 20968 } catch (IOException ioe) { 20969 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 20970 return null; 20971 } 20972 } 20973 20974 /* 20975 * Update media status on PackageManager. 20976 */ 20977 @Override 20978 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 20979 int callingUid = Binder.getCallingUid(); 20980 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 20981 throw new SecurityException("Media status can only be updated by the system"); 20982 } 20983 // reader; this apparently protects mMediaMounted, but should probably 20984 // be a different lock in that case. 20985 synchronized (mPackages) { 20986 Log.i(TAG, "Updating external media status from " 20987 + (mMediaMounted ? "mounted" : "unmounted") + " to " 20988 + (mediaStatus ? "mounted" : "unmounted")); 20989 if (DEBUG_SD_INSTALL) 20990 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 20991 + ", mMediaMounted=" + mMediaMounted); 20992 if (mediaStatus == mMediaMounted) { 20993 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 20994 : 0, -1); 20995 mHandler.sendMessage(msg); 20996 return; 20997 } 20998 mMediaMounted = mediaStatus; 20999 } 21000 // Queue up an async operation since the package installation may take a 21001 // little while. 21002 mHandler.post(new Runnable() { 21003 public void run() { 21004 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21005 } 21006 }); 21007 } 21008 21009 /** 21010 * Called by StorageManagerService when the initial ASECs to scan are available. 21011 * Should block until all the ASEC containers are finished being scanned. 21012 */ 21013 public void scanAvailableAsecs() { 21014 updateExternalMediaStatusInner(true, false, false); 21015 } 21016 21017 /* 21018 * Collect information of applications on external media, map them against 21019 * existing containers and update information based on current mount status. 21020 * Please note that we always have to report status if reportStatus has been 21021 * set to true especially when unloading packages. 21022 */ 21023 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21024 boolean externalStorage) { 21025 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21026 int[] uidArr = EmptyArray.INT; 21027 21028 final String[] list = PackageHelper.getSecureContainerList(); 21029 if (ArrayUtils.isEmpty(list)) { 21030 Log.i(TAG, "No secure containers found"); 21031 } else { 21032 // Process list of secure containers and categorize them 21033 // as active or stale based on their package internal state. 21034 21035 // reader 21036 synchronized (mPackages) { 21037 for (String cid : list) { 21038 // Leave stages untouched for now; installer service owns them 21039 if (PackageInstallerService.isStageName(cid)) continue; 21040 21041 if (DEBUG_SD_INSTALL) 21042 Log.i(TAG, "Processing container " + cid); 21043 String pkgName = getAsecPackageName(cid); 21044 if (pkgName == null) { 21045 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21046 continue; 21047 } 21048 if (DEBUG_SD_INSTALL) 21049 Log.i(TAG, "Looking for pkg : " + pkgName); 21050 21051 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21052 if (ps == null) { 21053 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21054 continue; 21055 } 21056 21057 /* 21058 * Skip packages that are not external if we're unmounting 21059 * external storage. 21060 */ 21061 if (externalStorage && !isMounted && !isExternal(ps)) { 21062 continue; 21063 } 21064 21065 final AsecInstallArgs args = new AsecInstallArgs(cid, 21066 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21067 // The package status is changed only if the code path 21068 // matches between settings and the container id. 21069 if (ps.codePathString != null 21070 && ps.codePathString.startsWith(args.getCodePath())) { 21071 if (DEBUG_SD_INSTALL) { 21072 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21073 + " at code path: " + ps.codePathString); 21074 } 21075 21076 // We do have a valid package installed on sdcard 21077 processCids.put(args, ps.codePathString); 21078 final int uid = ps.appId; 21079 if (uid != -1) { 21080 uidArr = ArrayUtils.appendInt(uidArr, uid); 21081 } 21082 } else { 21083 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21084 + ps.codePathString); 21085 } 21086 } 21087 } 21088 21089 Arrays.sort(uidArr); 21090 } 21091 21092 // Process packages with valid entries. 21093 if (isMounted) { 21094 if (DEBUG_SD_INSTALL) 21095 Log.i(TAG, "Loading packages"); 21096 loadMediaPackages(processCids, uidArr, externalStorage); 21097 startCleaningPackages(); 21098 mInstallerService.onSecureContainersAvailable(); 21099 } else { 21100 if (DEBUG_SD_INSTALL) 21101 Log.i(TAG, "Unloading packages"); 21102 unloadMediaPackages(processCids, uidArr, reportStatus); 21103 } 21104 } 21105 21106 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21107 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21108 final int size = infos.size(); 21109 final String[] packageNames = new String[size]; 21110 final int[] packageUids = new int[size]; 21111 for (int i = 0; i < size; i++) { 21112 final ApplicationInfo info = infos.get(i); 21113 packageNames[i] = info.packageName; 21114 packageUids[i] = info.uid; 21115 } 21116 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21117 finishedReceiver); 21118 } 21119 21120 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21121 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21122 sendResourcesChangedBroadcast(mediaStatus, replacing, 21123 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21124 } 21125 21126 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21127 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21128 int size = pkgList.length; 21129 if (size > 0) { 21130 // Send broadcasts here 21131 Bundle extras = new Bundle(); 21132 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21133 if (uidArr != null) { 21134 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21135 } 21136 if (replacing) { 21137 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21138 } 21139 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21140 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21141 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21142 } 21143 } 21144 21145 /* 21146 * Look at potentially valid container ids from processCids If package 21147 * information doesn't match the one on record or package scanning fails, 21148 * the cid is added to list of removeCids. We currently don't delete stale 21149 * containers. 21150 */ 21151 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21152 boolean externalStorage) { 21153 ArrayList<String> pkgList = new ArrayList<String>(); 21154 Set<AsecInstallArgs> keys = processCids.keySet(); 21155 21156 for (AsecInstallArgs args : keys) { 21157 String codePath = processCids.get(args); 21158 if (DEBUG_SD_INSTALL) 21159 Log.i(TAG, "Loading container : " + args.cid); 21160 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21161 try { 21162 // Make sure there are no container errors first. 21163 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21164 Slog.e(TAG, "Failed to mount cid : " + args.cid 21165 + " when installing from sdcard"); 21166 continue; 21167 } 21168 // Check code path here. 21169 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21170 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21171 + " does not match one in settings " + codePath); 21172 continue; 21173 } 21174 // Parse package 21175 int parseFlags = mDefParseFlags; 21176 if (args.isExternalAsec()) { 21177 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21178 } 21179 if (args.isFwdLocked()) { 21180 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21181 } 21182 21183 synchronized (mInstallLock) { 21184 PackageParser.Package pkg = null; 21185 try { 21186 // Sadly we don't know the package name yet to freeze it 21187 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21188 SCAN_IGNORE_FROZEN, 0, null); 21189 } catch (PackageManagerException e) { 21190 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21191 } 21192 // Scan the package 21193 if (pkg != null) { 21194 /* 21195 * TODO why is the lock being held? doPostInstall is 21196 * called in other places without the lock. This needs 21197 * to be straightened out. 21198 */ 21199 // writer 21200 synchronized (mPackages) { 21201 retCode = PackageManager.INSTALL_SUCCEEDED; 21202 pkgList.add(pkg.packageName); 21203 // Post process args 21204 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21205 pkg.applicationInfo.uid); 21206 } 21207 } else { 21208 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21209 } 21210 } 21211 21212 } finally { 21213 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21214 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21215 } 21216 } 21217 } 21218 // writer 21219 synchronized (mPackages) { 21220 // If the platform SDK has changed since the last time we booted, 21221 // we need to re-grant app permission to catch any new ones that 21222 // appear. This is really a hack, and means that apps can in some 21223 // cases get permissions that the user didn't initially explicitly 21224 // allow... it would be nice to have some better way to handle 21225 // this situation. 21226 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21227 : mSettings.getInternalVersion(); 21228 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21229 : StorageManager.UUID_PRIVATE_INTERNAL; 21230 21231 int updateFlags = UPDATE_PERMISSIONS_ALL; 21232 if (ver.sdkVersion != mSdkVersion) { 21233 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21234 + mSdkVersion + "; regranting permissions for external"); 21235 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21236 } 21237 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21238 21239 // Yay, everything is now upgraded 21240 ver.forceCurrent(); 21241 21242 // can downgrade to reader 21243 // Persist settings 21244 mSettings.writeLPr(); 21245 } 21246 // Send a broadcast to let everyone know we are done processing 21247 if (pkgList.size() > 0) { 21248 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21249 } 21250 } 21251 21252 /* 21253 * Utility method to unload a list of specified containers 21254 */ 21255 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21256 // Just unmount all valid containers. 21257 for (AsecInstallArgs arg : cidArgs) { 21258 synchronized (mInstallLock) { 21259 arg.doPostDeleteLI(false); 21260 } 21261 } 21262 } 21263 21264 /* 21265 * Unload packages mounted on external media. This involves deleting package 21266 * data from internal structures, sending broadcasts about disabled packages, 21267 * gc'ing to free up references, unmounting all secure containers 21268 * corresponding to packages on external media, and posting a 21269 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21270 * that we always have to post this message if status has been requested no 21271 * matter what. 21272 */ 21273 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21274 final boolean reportStatus) { 21275 if (DEBUG_SD_INSTALL) 21276 Log.i(TAG, "unloading media packages"); 21277 ArrayList<String> pkgList = new ArrayList<String>(); 21278 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21279 final Set<AsecInstallArgs> keys = processCids.keySet(); 21280 for (AsecInstallArgs args : keys) { 21281 String pkgName = args.getPackageName(); 21282 if (DEBUG_SD_INSTALL) 21283 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21284 // Delete package internally 21285 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21286 synchronized (mInstallLock) { 21287 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21288 final boolean res; 21289 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21290 "unloadMediaPackages")) { 21291 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21292 null); 21293 } 21294 if (res) { 21295 pkgList.add(pkgName); 21296 } else { 21297 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21298 failedList.add(args); 21299 } 21300 } 21301 } 21302 21303 // reader 21304 synchronized (mPackages) { 21305 // We didn't update the settings after removing each package; 21306 // write them now for all packages. 21307 mSettings.writeLPr(); 21308 } 21309 21310 // We have to absolutely send UPDATED_MEDIA_STATUS only 21311 // after confirming that all the receivers processed the ordered 21312 // broadcast when packages get disabled, force a gc to clean things up. 21313 // and unload all the containers. 21314 if (pkgList.size() > 0) { 21315 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21316 new IIntentReceiver.Stub() { 21317 public void performReceive(Intent intent, int resultCode, String data, 21318 Bundle extras, boolean ordered, boolean sticky, 21319 int sendingUser) throws RemoteException { 21320 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21321 reportStatus ? 1 : 0, 1, keys); 21322 mHandler.sendMessage(msg); 21323 } 21324 }); 21325 } else { 21326 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21327 keys); 21328 mHandler.sendMessage(msg); 21329 } 21330 } 21331 21332 private void loadPrivatePackages(final VolumeInfo vol) { 21333 mHandler.post(new Runnable() { 21334 @Override 21335 public void run() { 21336 loadPrivatePackagesInner(vol); 21337 } 21338 }); 21339 } 21340 21341 private void loadPrivatePackagesInner(VolumeInfo vol) { 21342 final String volumeUuid = vol.fsUuid; 21343 if (TextUtils.isEmpty(volumeUuid)) { 21344 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21345 return; 21346 } 21347 21348 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21349 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21350 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21351 21352 final VersionInfo ver; 21353 final List<PackageSetting> packages; 21354 synchronized (mPackages) { 21355 ver = mSettings.findOrCreateVersion(volumeUuid); 21356 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21357 } 21358 21359 for (PackageSetting ps : packages) { 21360 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21361 synchronized (mInstallLock) { 21362 final PackageParser.Package pkg; 21363 try { 21364 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21365 loaded.add(pkg.applicationInfo); 21366 21367 } catch (PackageManagerException e) { 21368 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21369 } 21370 21371 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21372 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21373 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21374 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21375 } 21376 } 21377 } 21378 21379 // Reconcile app data for all started/unlocked users 21380 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21381 final UserManager um = mContext.getSystemService(UserManager.class); 21382 UserManagerInternal umInternal = getUserManagerInternal(); 21383 for (UserInfo user : um.getUsers()) { 21384 final int flags; 21385 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21386 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21387 } else if (umInternal.isUserRunning(user.id)) { 21388 flags = StorageManager.FLAG_STORAGE_DE; 21389 } else { 21390 continue; 21391 } 21392 21393 try { 21394 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21395 synchronized (mInstallLock) { 21396 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21397 } 21398 } catch (IllegalStateException e) { 21399 // Device was probably ejected, and we'll process that event momentarily 21400 Slog.w(TAG, "Failed to prepare storage: " + e); 21401 } 21402 } 21403 21404 synchronized (mPackages) { 21405 int updateFlags = UPDATE_PERMISSIONS_ALL; 21406 if (ver.sdkVersion != mSdkVersion) { 21407 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21408 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21409 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21410 } 21411 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21412 21413 // Yay, everything is now upgraded 21414 ver.forceCurrent(); 21415 21416 mSettings.writeLPr(); 21417 } 21418 21419 for (PackageFreezer freezer : freezers) { 21420 freezer.close(); 21421 } 21422 21423 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21424 sendResourcesChangedBroadcast(true, false, loaded, null); 21425 } 21426 21427 private void unloadPrivatePackages(final VolumeInfo vol) { 21428 mHandler.post(new Runnable() { 21429 @Override 21430 public void run() { 21431 unloadPrivatePackagesInner(vol); 21432 } 21433 }); 21434 } 21435 21436 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21437 final String volumeUuid = vol.fsUuid; 21438 if (TextUtils.isEmpty(volumeUuid)) { 21439 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21440 return; 21441 } 21442 21443 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21444 synchronized (mInstallLock) { 21445 synchronized (mPackages) { 21446 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21447 for (PackageSetting ps : packages) { 21448 if (ps.pkg == null) continue; 21449 21450 final ApplicationInfo info = ps.pkg.applicationInfo; 21451 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21452 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21453 21454 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21455 "unloadPrivatePackagesInner")) { 21456 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21457 false, null)) { 21458 unloaded.add(info); 21459 } else { 21460 Slog.w(TAG, "Failed to unload " + ps.codePath); 21461 } 21462 } 21463 21464 // Try very hard to release any references to this package 21465 // so we don't risk the system server being killed due to 21466 // open FDs 21467 AttributeCache.instance().removePackage(ps.name); 21468 } 21469 21470 mSettings.writeLPr(); 21471 } 21472 } 21473 21474 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21475 sendResourcesChangedBroadcast(false, false, unloaded, null); 21476 21477 // Try very hard to release any references to this path so we don't risk 21478 // the system server being killed due to open FDs 21479 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21480 21481 for (int i = 0; i < 3; i++) { 21482 System.gc(); 21483 System.runFinalization(); 21484 } 21485 } 21486 21487 private void assertPackageKnown(String volumeUuid, String packageName) 21488 throws PackageManagerException { 21489 synchronized (mPackages) { 21490 // Normalize package name to handle renamed packages 21491 packageName = normalizePackageNameLPr(packageName); 21492 21493 final PackageSetting ps = mSettings.mPackages.get(packageName); 21494 if (ps == null) { 21495 throw new PackageManagerException("Package " + packageName + " is unknown"); 21496 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21497 throw new PackageManagerException( 21498 "Package " + packageName + " found on unknown volume " + volumeUuid 21499 + "; expected volume " + ps.volumeUuid); 21500 } 21501 } 21502 } 21503 21504 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21505 throws PackageManagerException { 21506 synchronized (mPackages) { 21507 // Normalize package name to handle renamed packages 21508 packageName = normalizePackageNameLPr(packageName); 21509 21510 final PackageSetting ps = mSettings.mPackages.get(packageName); 21511 if (ps == null) { 21512 throw new PackageManagerException("Package " + packageName + " is unknown"); 21513 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21514 throw new PackageManagerException( 21515 "Package " + packageName + " found on unknown volume " + volumeUuid 21516 + "; expected volume " + ps.volumeUuid); 21517 } else if (!ps.getInstalled(userId)) { 21518 throw new PackageManagerException( 21519 "Package " + packageName + " not installed for user " + userId); 21520 } 21521 } 21522 } 21523 21524 private List<String> collectAbsoluteCodePaths() { 21525 synchronized (mPackages) { 21526 List<String> codePaths = new ArrayList<>(); 21527 final int packageCount = mSettings.mPackages.size(); 21528 for (int i = 0; i < packageCount; i++) { 21529 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21530 codePaths.add(ps.codePath.getAbsolutePath()); 21531 } 21532 return codePaths; 21533 } 21534 } 21535 21536 /** 21537 * Examine all apps present on given mounted volume, and destroy apps that 21538 * aren't expected, either due to uninstallation or reinstallation on 21539 * another volume. 21540 */ 21541 private void reconcileApps(String volumeUuid) { 21542 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21543 List<File> filesToDelete = null; 21544 21545 final File[] files = FileUtils.listFilesOrEmpty( 21546 Environment.getDataAppDirectory(volumeUuid)); 21547 for (File file : files) { 21548 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21549 && !PackageInstallerService.isStageName(file.getName()); 21550 if (!isPackage) { 21551 // Ignore entries which are not packages 21552 continue; 21553 } 21554 21555 String absolutePath = file.getAbsolutePath(); 21556 21557 boolean pathValid = false; 21558 final int absoluteCodePathCount = absoluteCodePaths.size(); 21559 for (int i = 0; i < absoluteCodePathCount; i++) { 21560 String absoluteCodePath = absoluteCodePaths.get(i); 21561 if (absolutePath.startsWith(absoluteCodePath)) { 21562 pathValid = true; 21563 break; 21564 } 21565 } 21566 21567 if (!pathValid) { 21568 if (filesToDelete == null) { 21569 filesToDelete = new ArrayList<>(); 21570 } 21571 filesToDelete.add(file); 21572 } 21573 } 21574 21575 if (filesToDelete != null) { 21576 final int fileToDeleteCount = filesToDelete.size(); 21577 for (int i = 0; i < fileToDeleteCount; i++) { 21578 File fileToDelete = filesToDelete.get(i); 21579 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21580 synchronized (mInstallLock) { 21581 removeCodePathLI(fileToDelete); 21582 } 21583 } 21584 } 21585 } 21586 21587 /** 21588 * Reconcile all app data for the given user. 21589 * <p> 21590 * Verifies that directories exist and that ownership and labeling is 21591 * correct for all installed apps on all mounted volumes. 21592 */ 21593 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21594 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21595 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21596 final String volumeUuid = vol.getFsUuid(); 21597 synchronized (mInstallLock) { 21598 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21599 } 21600 } 21601 } 21602 21603 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21604 boolean migrateAppData) { 21605 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21606 } 21607 21608 /** 21609 * Reconcile all app data on given mounted volume. 21610 * <p> 21611 * Destroys app data that isn't expected, either due to uninstallation or 21612 * reinstallation on another volume. 21613 * <p> 21614 * Verifies that directories exist and that ownership and labeling is 21615 * correct for all installed apps. 21616 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21617 */ 21618 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21619 boolean migrateAppData, boolean onlyCoreApps) { 21620 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21621 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21622 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21623 21624 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21625 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21626 21627 // First look for stale data that doesn't belong, and check if things 21628 // have changed since we did our last restorecon 21629 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21630 if (StorageManager.isFileEncryptedNativeOrEmulated() 21631 && !StorageManager.isUserKeyUnlocked(userId)) { 21632 throw new RuntimeException( 21633 "Yikes, someone asked us to reconcile CE storage while " + userId 21634 + " was still locked; this would have caused massive data loss!"); 21635 } 21636 21637 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21638 for (File file : files) { 21639 final String packageName = file.getName(); 21640 try { 21641 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21642 } catch (PackageManagerException e) { 21643 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21644 try { 21645 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21646 StorageManager.FLAG_STORAGE_CE, 0); 21647 } catch (InstallerException e2) { 21648 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21649 } 21650 } 21651 } 21652 } 21653 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21654 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21655 for (File file : files) { 21656 final String packageName = file.getName(); 21657 try { 21658 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21659 } catch (PackageManagerException e) { 21660 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21661 try { 21662 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21663 StorageManager.FLAG_STORAGE_DE, 0); 21664 } catch (InstallerException e2) { 21665 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21666 } 21667 } 21668 } 21669 } 21670 21671 // Ensure that data directories are ready to roll for all packages 21672 // installed for this volume and user 21673 final List<PackageSetting> packages; 21674 synchronized (mPackages) { 21675 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21676 } 21677 int preparedCount = 0; 21678 for (PackageSetting ps : packages) { 21679 final String packageName = ps.name; 21680 if (ps.pkg == null) { 21681 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21682 // TODO: might be due to legacy ASEC apps; we should circle back 21683 // and reconcile again once they're scanned 21684 continue; 21685 } 21686 // Skip non-core apps if requested 21687 if (onlyCoreApps && !ps.pkg.coreApp) { 21688 result.add(packageName); 21689 continue; 21690 } 21691 21692 if (ps.getInstalled(userId)) { 21693 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21694 preparedCount++; 21695 } 21696 } 21697 21698 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21699 return result; 21700 } 21701 21702 /** 21703 * Prepare app data for the given app just after it was installed or 21704 * upgraded. This method carefully only touches users that it's installed 21705 * for, and it forces a restorecon to handle any seinfo changes. 21706 * <p> 21707 * Verifies that directories exist and that ownership and labeling is 21708 * correct for all installed apps. If there is an ownership mismatch, it 21709 * will try recovering system apps by wiping data; third-party app data is 21710 * left intact. 21711 * <p> 21712 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21713 */ 21714 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21715 final PackageSetting ps; 21716 synchronized (mPackages) { 21717 ps = mSettings.mPackages.get(pkg.packageName); 21718 mSettings.writeKernelMappingLPr(ps); 21719 } 21720 21721 final UserManager um = mContext.getSystemService(UserManager.class); 21722 UserManagerInternal umInternal = getUserManagerInternal(); 21723 for (UserInfo user : um.getUsers()) { 21724 final int flags; 21725 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21726 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21727 } else if (umInternal.isUserRunning(user.id)) { 21728 flags = StorageManager.FLAG_STORAGE_DE; 21729 } else { 21730 continue; 21731 } 21732 21733 if (ps.getInstalled(user.id)) { 21734 // TODO: when user data is locked, mark that we're still dirty 21735 prepareAppDataLIF(pkg, user.id, flags); 21736 } 21737 } 21738 } 21739 21740 /** 21741 * Prepare app data for the given app. 21742 * <p> 21743 * Verifies that directories exist and that ownership and labeling is 21744 * correct for all installed apps. If there is an ownership mismatch, this 21745 * will try recovering system apps by wiping data; third-party app data is 21746 * left intact. 21747 */ 21748 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21749 if (pkg == null) { 21750 Slog.wtf(TAG, "Package was null!", new Throwable()); 21751 return; 21752 } 21753 prepareAppDataLeafLIF(pkg, userId, flags); 21754 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21755 for (int i = 0; i < childCount; i++) { 21756 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21757 } 21758 } 21759 21760 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21761 boolean maybeMigrateAppData) { 21762 prepareAppDataLIF(pkg, userId, flags); 21763 21764 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21765 // We may have just shuffled around app data directories, so 21766 // prepare them one more time 21767 prepareAppDataLIF(pkg, userId, flags); 21768 } 21769 } 21770 21771 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21772 if (DEBUG_APP_DATA) { 21773 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21774 + Integer.toHexString(flags)); 21775 } 21776 21777 final String volumeUuid = pkg.volumeUuid; 21778 final String packageName = pkg.packageName; 21779 final ApplicationInfo app = pkg.applicationInfo; 21780 final int appId = UserHandle.getAppId(app.uid); 21781 21782 Preconditions.checkNotNull(app.seInfo); 21783 21784 long ceDataInode = -1; 21785 try { 21786 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21787 appId, app.seInfo, app.targetSdkVersion); 21788 } catch (InstallerException e) { 21789 if (app.isSystemApp()) { 21790 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21791 + ", but trying to recover: " + e); 21792 destroyAppDataLeafLIF(pkg, userId, flags); 21793 try { 21794 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21795 appId, app.seInfo, app.targetSdkVersion); 21796 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21797 } catch (InstallerException e2) { 21798 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21799 } 21800 } else { 21801 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21802 } 21803 } 21804 21805 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21806 // TODO: mark this structure as dirty so we persist it! 21807 synchronized (mPackages) { 21808 final PackageSetting ps = mSettings.mPackages.get(packageName); 21809 if (ps != null) { 21810 ps.setCeDataInode(ceDataInode, userId); 21811 } 21812 } 21813 } 21814 21815 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21816 } 21817 21818 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21819 if (pkg == null) { 21820 Slog.wtf(TAG, "Package was null!", new Throwable()); 21821 return; 21822 } 21823 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21825 for (int i = 0; i < childCount; i++) { 21826 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21827 } 21828 } 21829 21830 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21831 final String volumeUuid = pkg.volumeUuid; 21832 final String packageName = pkg.packageName; 21833 final ApplicationInfo app = pkg.applicationInfo; 21834 21835 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21836 // Create a native library symlink only if we have native libraries 21837 // and if the native libraries are 32 bit libraries. We do not provide 21838 // this symlink for 64 bit libraries. 21839 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21840 final String nativeLibPath = app.nativeLibraryDir; 21841 try { 21842 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21843 nativeLibPath, userId); 21844 } catch (InstallerException e) { 21845 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21846 } 21847 } 21848 } 21849 } 21850 21851 /** 21852 * For system apps on non-FBE devices, this method migrates any existing 21853 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21854 * requested by the app. 21855 */ 21856 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21857 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21858 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21859 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21860 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21861 try { 21862 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21863 storageTarget); 21864 } catch (InstallerException e) { 21865 logCriticalInfo(Log.WARN, 21866 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21867 } 21868 return true; 21869 } else { 21870 return false; 21871 } 21872 } 21873 21874 public PackageFreezer freezePackage(String packageName, String killReason) { 21875 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21876 } 21877 21878 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21879 return new PackageFreezer(packageName, userId, killReason); 21880 } 21881 21882 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21883 String killReason) { 21884 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21885 } 21886 21887 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21888 String killReason) { 21889 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21890 return new PackageFreezer(); 21891 } else { 21892 return freezePackage(packageName, userId, killReason); 21893 } 21894 } 21895 21896 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21897 String killReason) { 21898 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21899 } 21900 21901 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21902 String killReason) { 21903 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21904 return new PackageFreezer(); 21905 } else { 21906 return freezePackage(packageName, userId, killReason); 21907 } 21908 } 21909 21910 /** 21911 * Class that freezes and kills the given package upon creation, and 21912 * unfreezes it upon closing. This is typically used when doing surgery on 21913 * app code/data to prevent the app from running while you're working. 21914 */ 21915 private class PackageFreezer implements AutoCloseable { 21916 private final String mPackageName; 21917 private final PackageFreezer[] mChildren; 21918 21919 private final boolean mWeFroze; 21920 21921 private final AtomicBoolean mClosed = new AtomicBoolean(); 21922 private final CloseGuard mCloseGuard = CloseGuard.get(); 21923 21924 /** 21925 * Create and return a stub freezer that doesn't actually do anything, 21926 * typically used when someone requested 21927 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 21928 * {@link PackageManager#DELETE_DONT_KILL_APP}. 21929 */ 21930 public PackageFreezer() { 21931 mPackageName = null; 21932 mChildren = null; 21933 mWeFroze = false; 21934 mCloseGuard.open("close"); 21935 } 21936 21937 public PackageFreezer(String packageName, int userId, String killReason) { 21938 synchronized (mPackages) { 21939 mPackageName = packageName; 21940 mWeFroze = mFrozenPackages.add(mPackageName); 21941 21942 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 21943 if (ps != null) { 21944 killApplication(ps.name, ps.appId, userId, killReason); 21945 } 21946 21947 final PackageParser.Package p = mPackages.get(packageName); 21948 if (p != null && p.childPackages != null) { 21949 final int N = p.childPackages.size(); 21950 mChildren = new PackageFreezer[N]; 21951 for (int i = 0; i < N; i++) { 21952 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 21953 userId, killReason); 21954 } 21955 } else { 21956 mChildren = null; 21957 } 21958 } 21959 mCloseGuard.open("close"); 21960 } 21961 21962 @Override 21963 protected void finalize() throws Throwable { 21964 try { 21965 mCloseGuard.warnIfOpen(); 21966 close(); 21967 } finally { 21968 super.finalize(); 21969 } 21970 } 21971 21972 @Override 21973 public void close() { 21974 mCloseGuard.close(); 21975 if (mClosed.compareAndSet(false, true)) { 21976 synchronized (mPackages) { 21977 if (mWeFroze) { 21978 mFrozenPackages.remove(mPackageName); 21979 } 21980 21981 if (mChildren != null) { 21982 for (PackageFreezer freezer : mChildren) { 21983 freezer.close(); 21984 } 21985 } 21986 } 21987 } 21988 } 21989 } 21990 21991 /** 21992 * Verify that given package is currently frozen. 21993 */ 21994 private void checkPackageFrozen(String packageName) { 21995 synchronized (mPackages) { 21996 if (!mFrozenPackages.contains(packageName)) { 21997 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 21998 } 21999 } 22000 } 22001 22002 @Override 22003 public int movePackage(final String packageName, final String volumeUuid) { 22004 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22005 22006 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22007 final int moveId = mNextMoveId.getAndIncrement(); 22008 mHandler.post(new Runnable() { 22009 @Override 22010 public void run() { 22011 try { 22012 movePackageInternal(packageName, volumeUuid, moveId, user); 22013 } catch (PackageManagerException e) { 22014 Slog.w(TAG, "Failed to move " + packageName, e); 22015 mMoveCallbacks.notifyStatusChanged(moveId, 22016 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22017 } 22018 } 22019 }); 22020 return moveId; 22021 } 22022 22023 private void movePackageInternal(final String packageName, final String volumeUuid, 22024 final int moveId, UserHandle user) throws PackageManagerException { 22025 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22026 final PackageManager pm = mContext.getPackageManager(); 22027 22028 final boolean currentAsec; 22029 final String currentVolumeUuid; 22030 final File codeFile; 22031 final String installerPackageName; 22032 final String packageAbiOverride; 22033 final int appId; 22034 final String seinfo; 22035 final String label; 22036 final int targetSdkVersion; 22037 final PackageFreezer freezer; 22038 final int[] installedUserIds; 22039 22040 // reader 22041 synchronized (mPackages) { 22042 final PackageParser.Package pkg = mPackages.get(packageName); 22043 final PackageSetting ps = mSettings.mPackages.get(packageName); 22044 if (pkg == null || ps == null) { 22045 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22046 } 22047 22048 if (pkg.applicationInfo.isSystemApp()) { 22049 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22050 "Cannot move system application"); 22051 } 22052 22053 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22054 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22055 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22056 if (isInternalStorage && !allow3rdPartyOnInternal) { 22057 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22058 "3rd party apps are not allowed on internal storage"); 22059 } 22060 22061 if (pkg.applicationInfo.isExternalAsec()) { 22062 currentAsec = true; 22063 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22064 } else if (pkg.applicationInfo.isForwardLocked()) { 22065 currentAsec = true; 22066 currentVolumeUuid = "forward_locked"; 22067 } else { 22068 currentAsec = false; 22069 currentVolumeUuid = ps.volumeUuid; 22070 22071 final File probe = new File(pkg.codePath); 22072 final File probeOat = new File(probe, "oat"); 22073 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22074 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22075 "Move only supported for modern cluster style installs"); 22076 } 22077 } 22078 22079 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22080 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22081 "Package already moved to " + volumeUuid); 22082 } 22083 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22084 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22085 "Device admin cannot be moved"); 22086 } 22087 22088 if (mFrozenPackages.contains(packageName)) { 22089 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22090 "Failed to move already frozen package"); 22091 } 22092 22093 codeFile = new File(pkg.codePath); 22094 installerPackageName = ps.installerPackageName; 22095 packageAbiOverride = ps.cpuAbiOverrideString; 22096 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22097 seinfo = pkg.applicationInfo.seInfo; 22098 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22099 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22100 freezer = freezePackage(packageName, "movePackageInternal"); 22101 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22102 } 22103 22104 final Bundle extras = new Bundle(); 22105 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22106 extras.putString(Intent.EXTRA_TITLE, label); 22107 mMoveCallbacks.notifyCreated(moveId, extras); 22108 22109 int installFlags; 22110 final boolean moveCompleteApp; 22111 final File measurePath; 22112 22113 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22114 installFlags = INSTALL_INTERNAL; 22115 moveCompleteApp = !currentAsec; 22116 measurePath = Environment.getDataAppDirectory(volumeUuid); 22117 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22118 installFlags = INSTALL_EXTERNAL; 22119 moveCompleteApp = false; 22120 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22121 } else { 22122 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22123 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22124 || !volume.isMountedWritable()) { 22125 freezer.close(); 22126 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22127 "Move location not mounted private volume"); 22128 } 22129 22130 Preconditions.checkState(!currentAsec); 22131 22132 installFlags = INSTALL_INTERNAL; 22133 moveCompleteApp = true; 22134 measurePath = Environment.getDataAppDirectory(volumeUuid); 22135 } 22136 22137 final PackageStats stats = new PackageStats(null, -1); 22138 synchronized (mInstaller) { 22139 for (int userId : installedUserIds) { 22140 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22141 freezer.close(); 22142 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22143 "Failed to measure package size"); 22144 } 22145 } 22146 } 22147 22148 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22149 + stats.dataSize); 22150 22151 final long startFreeBytes = measurePath.getFreeSpace(); 22152 final long sizeBytes; 22153 if (moveCompleteApp) { 22154 sizeBytes = stats.codeSize + stats.dataSize; 22155 } else { 22156 sizeBytes = stats.codeSize; 22157 } 22158 22159 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22160 freezer.close(); 22161 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22162 "Not enough free space to move"); 22163 } 22164 22165 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22166 22167 final CountDownLatch installedLatch = new CountDownLatch(1); 22168 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22169 @Override 22170 public void onUserActionRequired(Intent intent) throws RemoteException { 22171 throw new IllegalStateException(); 22172 } 22173 22174 @Override 22175 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22176 Bundle extras) throws RemoteException { 22177 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22178 + PackageManager.installStatusToString(returnCode, msg)); 22179 22180 installedLatch.countDown(); 22181 freezer.close(); 22182 22183 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22184 switch (status) { 22185 case PackageInstaller.STATUS_SUCCESS: 22186 mMoveCallbacks.notifyStatusChanged(moveId, 22187 PackageManager.MOVE_SUCCEEDED); 22188 break; 22189 case PackageInstaller.STATUS_FAILURE_STORAGE: 22190 mMoveCallbacks.notifyStatusChanged(moveId, 22191 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22192 break; 22193 default: 22194 mMoveCallbacks.notifyStatusChanged(moveId, 22195 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22196 break; 22197 } 22198 } 22199 }; 22200 22201 final MoveInfo move; 22202 if (moveCompleteApp) { 22203 // Kick off a thread to report progress estimates 22204 new Thread() { 22205 @Override 22206 public void run() { 22207 while (true) { 22208 try { 22209 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22210 break; 22211 } 22212 } catch (InterruptedException ignored) { 22213 } 22214 22215 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22216 final int progress = 10 + (int) MathUtils.constrain( 22217 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22218 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22219 } 22220 } 22221 }.start(); 22222 22223 final String dataAppName = codeFile.getName(); 22224 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22225 dataAppName, appId, seinfo, targetSdkVersion); 22226 } else { 22227 move = null; 22228 } 22229 22230 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22231 22232 final Message msg = mHandler.obtainMessage(INIT_COPY); 22233 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22234 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22235 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22236 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22237 PackageManager.INSTALL_REASON_UNKNOWN); 22238 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22239 msg.obj = params; 22240 22241 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22242 System.identityHashCode(msg.obj)); 22243 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22244 System.identityHashCode(msg.obj)); 22245 22246 mHandler.sendMessage(msg); 22247 } 22248 22249 @Override 22250 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22251 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22252 22253 final int realMoveId = mNextMoveId.getAndIncrement(); 22254 final Bundle extras = new Bundle(); 22255 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22256 mMoveCallbacks.notifyCreated(realMoveId, extras); 22257 22258 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22259 @Override 22260 public void onCreated(int moveId, Bundle extras) { 22261 // Ignored 22262 } 22263 22264 @Override 22265 public void onStatusChanged(int moveId, int status, long estMillis) { 22266 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22267 } 22268 }; 22269 22270 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22271 storage.setPrimaryStorageUuid(volumeUuid, callback); 22272 return realMoveId; 22273 } 22274 22275 @Override 22276 public int getMoveStatus(int moveId) { 22277 mContext.enforceCallingOrSelfPermission( 22278 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22279 return mMoveCallbacks.mLastStatus.get(moveId); 22280 } 22281 22282 @Override 22283 public void registerMoveCallback(IPackageMoveObserver callback) { 22284 mContext.enforceCallingOrSelfPermission( 22285 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22286 mMoveCallbacks.register(callback); 22287 } 22288 22289 @Override 22290 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22291 mContext.enforceCallingOrSelfPermission( 22292 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22293 mMoveCallbacks.unregister(callback); 22294 } 22295 22296 @Override 22297 public boolean setInstallLocation(int loc) { 22298 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22299 null); 22300 if (getInstallLocation() == loc) { 22301 return true; 22302 } 22303 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22304 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22305 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22306 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22307 return true; 22308 } 22309 return false; 22310 } 22311 22312 @Override 22313 public int getInstallLocation() { 22314 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22315 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22316 PackageHelper.APP_INSTALL_AUTO); 22317 } 22318 22319 /** Called by UserManagerService */ 22320 void cleanUpUser(UserManagerService userManager, int userHandle) { 22321 synchronized (mPackages) { 22322 mDirtyUsers.remove(userHandle); 22323 mUserNeedsBadging.delete(userHandle); 22324 mSettings.removeUserLPw(userHandle); 22325 mPendingBroadcasts.remove(userHandle); 22326 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22327 removeUnusedPackagesLPw(userManager, userHandle); 22328 } 22329 } 22330 22331 /** 22332 * We're removing userHandle and would like to remove any downloaded packages 22333 * that are no longer in use by any other user. 22334 * @param userHandle the user being removed 22335 */ 22336 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22337 final boolean DEBUG_CLEAN_APKS = false; 22338 int [] users = userManager.getUserIds(); 22339 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22340 while (psit.hasNext()) { 22341 PackageSetting ps = psit.next(); 22342 if (ps.pkg == null) { 22343 continue; 22344 } 22345 final String packageName = ps.pkg.packageName; 22346 // Skip over if system app 22347 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22348 continue; 22349 } 22350 if (DEBUG_CLEAN_APKS) { 22351 Slog.i(TAG, "Checking package " + packageName); 22352 } 22353 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22354 if (keep) { 22355 if (DEBUG_CLEAN_APKS) { 22356 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22357 } 22358 } else { 22359 for (int i = 0; i < users.length; i++) { 22360 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22361 keep = true; 22362 if (DEBUG_CLEAN_APKS) { 22363 Slog.i(TAG, " Keeping package " + packageName + " for user " 22364 + users[i]); 22365 } 22366 break; 22367 } 22368 } 22369 } 22370 if (!keep) { 22371 if (DEBUG_CLEAN_APKS) { 22372 Slog.i(TAG, " Removing package " + packageName); 22373 } 22374 mHandler.post(new Runnable() { 22375 public void run() { 22376 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22377 userHandle, 0); 22378 } //end run 22379 }); 22380 } 22381 } 22382 } 22383 22384 /** Called by UserManagerService */ 22385 void createNewUser(int userId, String[] disallowedPackages) { 22386 synchronized (mInstallLock) { 22387 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22388 } 22389 synchronized (mPackages) { 22390 scheduleWritePackageRestrictionsLocked(userId); 22391 scheduleWritePackageListLocked(userId); 22392 applyFactoryDefaultBrowserLPw(userId); 22393 primeDomainVerificationsLPw(userId); 22394 } 22395 } 22396 22397 void onNewUserCreated(final int userId) { 22398 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22399 // If permission review for legacy apps is required, we represent 22400 // dagerous permissions for such apps as always granted runtime 22401 // permissions to keep per user flag state whether review is needed. 22402 // Hence, if a new user is added we have to propagate dangerous 22403 // permission grants for these legacy apps. 22404 if (mPermissionReviewRequired) { 22405 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22406 | UPDATE_PERMISSIONS_REPLACE_ALL); 22407 } 22408 } 22409 22410 @Override 22411 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22412 mContext.enforceCallingOrSelfPermission( 22413 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22414 "Only package verification agents can read the verifier device identity"); 22415 22416 synchronized (mPackages) { 22417 return mSettings.getVerifierDeviceIdentityLPw(); 22418 } 22419 } 22420 22421 @Override 22422 public void setPermissionEnforced(String permission, boolean enforced) { 22423 // TODO: Now that we no longer change GID for storage, this should to away. 22424 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22425 "setPermissionEnforced"); 22426 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22427 synchronized (mPackages) { 22428 if (mSettings.mReadExternalStorageEnforced == null 22429 || mSettings.mReadExternalStorageEnforced != enforced) { 22430 mSettings.mReadExternalStorageEnforced = enforced; 22431 mSettings.writeLPr(); 22432 } 22433 } 22434 // kill any non-foreground processes so we restart them and 22435 // grant/revoke the GID. 22436 final IActivityManager am = ActivityManager.getService(); 22437 if (am != null) { 22438 final long token = Binder.clearCallingIdentity(); 22439 try { 22440 am.killProcessesBelowForeground("setPermissionEnforcement"); 22441 } catch (RemoteException e) { 22442 } finally { 22443 Binder.restoreCallingIdentity(token); 22444 } 22445 } 22446 } else { 22447 throw new IllegalArgumentException("No selective enforcement for " + permission); 22448 } 22449 } 22450 22451 @Override 22452 @Deprecated 22453 public boolean isPermissionEnforced(String permission) { 22454 return true; 22455 } 22456 22457 @Override 22458 public boolean isStorageLow() { 22459 final long token = Binder.clearCallingIdentity(); 22460 try { 22461 final DeviceStorageMonitorInternal 22462 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22463 if (dsm != null) { 22464 return dsm.isMemoryLow(); 22465 } else { 22466 return false; 22467 } 22468 } finally { 22469 Binder.restoreCallingIdentity(token); 22470 } 22471 } 22472 22473 @Override 22474 public IPackageInstaller getPackageInstaller() { 22475 return mInstallerService; 22476 } 22477 22478 private boolean userNeedsBadging(int userId) { 22479 int index = mUserNeedsBadging.indexOfKey(userId); 22480 if (index < 0) { 22481 final UserInfo userInfo; 22482 final long token = Binder.clearCallingIdentity(); 22483 try { 22484 userInfo = sUserManager.getUserInfo(userId); 22485 } finally { 22486 Binder.restoreCallingIdentity(token); 22487 } 22488 final boolean b; 22489 if (userInfo != null && userInfo.isManagedProfile()) { 22490 b = true; 22491 } else { 22492 b = false; 22493 } 22494 mUserNeedsBadging.put(userId, b); 22495 return b; 22496 } 22497 return mUserNeedsBadging.valueAt(index); 22498 } 22499 22500 @Override 22501 public KeySet getKeySetByAlias(String packageName, String alias) { 22502 if (packageName == null || alias == null) { 22503 return null; 22504 } 22505 synchronized(mPackages) { 22506 final PackageParser.Package pkg = mPackages.get(packageName); 22507 if (pkg == null) { 22508 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22509 throw new IllegalArgumentException("Unknown package: " + packageName); 22510 } 22511 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22512 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22513 } 22514 } 22515 22516 @Override 22517 public KeySet getSigningKeySet(String packageName) { 22518 if (packageName == null) { 22519 return null; 22520 } 22521 synchronized(mPackages) { 22522 final PackageParser.Package pkg = mPackages.get(packageName); 22523 if (pkg == null) { 22524 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22525 throw new IllegalArgumentException("Unknown package: " + packageName); 22526 } 22527 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22528 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22529 throw new SecurityException("May not access signing KeySet of other apps."); 22530 } 22531 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22532 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22533 } 22534 } 22535 22536 @Override 22537 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22538 if (packageName == null || ks == null) { 22539 return false; 22540 } 22541 synchronized(mPackages) { 22542 final PackageParser.Package pkg = mPackages.get(packageName); 22543 if (pkg == null) { 22544 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22545 throw new IllegalArgumentException("Unknown package: " + packageName); 22546 } 22547 IBinder ksh = ks.getToken(); 22548 if (ksh instanceof KeySetHandle) { 22549 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22550 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22551 } 22552 return false; 22553 } 22554 } 22555 22556 @Override 22557 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22558 if (packageName == null || ks == null) { 22559 return false; 22560 } 22561 synchronized(mPackages) { 22562 final PackageParser.Package pkg = mPackages.get(packageName); 22563 if (pkg == null) { 22564 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22565 throw new IllegalArgumentException("Unknown package: " + packageName); 22566 } 22567 IBinder ksh = ks.getToken(); 22568 if (ksh instanceof KeySetHandle) { 22569 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22570 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22571 } 22572 return false; 22573 } 22574 } 22575 22576 private void deletePackageIfUnusedLPr(final String packageName) { 22577 PackageSetting ps = mSettings.mPackages.get(packageName); 22578 if (ps == null) { 22579 return; 22580 } 22581 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22582 // TODO Implement atomic delete if package is unused 22583 // It is currently possible that the package will be deleted even if it is installed 22584 // after this method returns. 22585 mHandler.post(new Runnable() { 22586 public void run() { 22587 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22588 0, PackageManager.DELETE_ALL_USERS); 22589 } 22590 }); 22591 } 22592 } 22593 22594 /** 22595 * Check and throw if the given before/after packages would be considered a 22596 * downgrade. 22597 */ 22598 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22599 throws PackageManagerException { 22600 if (after.versionCode < before.mVersionCode) { 22601 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22602 "Update version code " + after.versionCode + " is older than current " 22603 + before.mVersionCode); 22604 } else if (after.versionCode == before.mVersionCode) { 22605 if (after.baseRevisionCode < before.baseRevisionCode) { 22606 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22607 "Update base revision code " + after.baseRevisionCode 22608 + " is older than current " + before.baseRevisionCode); 22609 } 22610 22611 if (!ArrayUtils.isEmpty(after.splitNames)) { 22612 for (int i = 0; i < after.splitNames.length; i++) { 22613 final String splitName = after.splitNames[i]; 22614 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22615 if (j != -1) { 22616 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22617 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22618 "Update split " + splitName + " revision code " 22619 + after.splitRevisionCodes[i] + " is older than current " 22620 + before.splitRevisionCodes[j]); 22621 } 22622 } 22623 } 22624 } 22625 } 22626 } 22627 22628 private static class MoveCallbacks extends Handler { 22629 private static final int MSG_CREATED = 1; 22630 private static final int MSG_STATUS_CHANGED = 2; 22631 22632 private final RemoteCallbackList<IPackageMoveObserver> 22633 mCallbacks = new RemoteCallbackList<>(); 22634 22635 private final SparseIntArray mLastStatus = new SparseIntArray(); 22636 22637 public MoveCallbacks(Looper looper) { 22638 super(looper); 22639 } 22640 22641 public void register(IPackageMoveObserver callback) { 22642 mCallbacks.register(callback); 22643 } 22644 22645 public void unregister(IPackageMoveObserver callback) { 22646 mCallbacks.unregister(callback); 22647 } 22648 22649 @Override 22650 public void handleMessage(Message msg) { 22651 final SomeArgs args = (SomeArgs) msg.obj; 22652 final int n = mCallbacks.beginBroadcast(); 22653 for (int i = 0; i < n; i++) { 22654 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22655 try { 22656 invokeCallback(callback, msg.what, args); 22657 } catch (RemoteException ignored) { 22658 } 22659 } 22660 mCallbacks.finishBroadcast(); 22661 args.recycle(); 22662 } 22663 22664 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22665 throws RemoteException { 22666 switch (what) { 22667 case MSG_CREATED: { 22668 callback.onCreated(args.argi1, (Bundle) args.arg2); 22669 break; 22670 } 22671 case MSG_STATUS_CHANGED: { 22672 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22673 break; 22674 } 22675 } 22676 } 22677 22678 private void notifyCreated(int moveId, Bundle extras) { 22679 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22680 22681 final SomeArgs args = SomeArgs.obtain(); 22682 args.argi1 = moveId; 22683 args.arg2 = extras; 22684 obtainMessage(MSG_CREATED, args).sendToTarget(); 22685 } 22686 22687 private void notifyStatusChanged(int moveId, int status) { 22688 notifyStatusChanged(moveId, status, -1); 22689 } 22690 22691 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22692 Slog.v(TAG, "Move " + moveId + " status " + status); 22693 22694 final SomeArgs args = SomeArgs.obtain(); 22695 args.argi1 = moveId; 22696 args.argi2 = status; 22697 args.arg3 = estMillis; 22698 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22699 22700 synchronized (mLastStatus) { 22701 mLastStatus.put(moveId, status); 22702 } 22703 } 22704 } 22705 22706 private final static class OnPermissionChangeListeners extends Handler { 22707 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22708 22709 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22710 new RemoteCallbackList<>(); 22711 22712 public OnPermissionChangeListeners(Looper looper) { 22713 super(looper); 22714 } 22715 22716 @Override 22717 public void handleMessage(Message msg) { 22718 switch (msg.what) { 22719 case MSG_ON_PERMISSIONS_CHANGED: { 22720 final int uid = msg.arg1; 22721 handleOnPermissionsChanged(uid); 22722 } break; 22723 } 22724 } 22725 22726 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22727 mPermissionListeners.register(listener); 22728 22729 } 22730 22731 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22732 mPermissionListeners.unregister(listener); 22733 } 22734 22735 public void onPermissionsChanged(int uid) { 22736 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22737 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22738 } 22739 } 22740 22741 private void handleOnPermissionsChanged(int uid) { 22742 final int count = mPermissionListeners.beginBroadcast(); 22743 try { 22744 for (int i = 0; i < count; i++) { 22745 IOnPermissionsChangeListener callback = mPermissionListeners 22746 .getBroadcastItem(i); 22747 try { 22748 callback.onPermissionsChanged(uid); 22749 } catch (RemoteException e) { 22750 Log.e(TAG, "Permission listener is dead", e); 22751 } 22752 } 22753 } finally { 22754 mPermissionListeners.finishBroadcast(); 22755 } 22756 } 22757 } 22758 22759 private class PackageManagerInternalImpl extends PackageManagerInternal { 22760 @Override 22761 public void setLocationPackagesProvider(PackagesProvider provider) { 22762 synchronized (mPackages) { 22763 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22764 } 22765 } 22766 22767 @Override 22768 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22769 synchronized (mPackages) { 22770 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22771 } 22772 } 22773 22774 @Override 22775 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22776 synchronized (mPackages) { 22777 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22778 } 22779 } 22780 22781 @Override 22782 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22783 synchronized (mPackages) { 22784 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22785 } 22786 } 22787 22788 @Override 22789 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22790 synchronized (mPackages) { 22791 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22792 } 22793 } 22794 22795 @Override 22796 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22797 synchronized (mPackages) { 22798 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22799 } 22800 } 22801 22802 @Override 22803 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22804 synchronized (mPackages) { 22805 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22806 packageName, userId); 22807 } 22808 } 22809 22810 @Override 22811 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22812 synchronized (mPackages) { 22813 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22814 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22815 packageName, userId); 22816 } 22817 } 22818 22819 @Override 22820 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22821 synchronized (mPackages) { 22822 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22823 packageName, userId); 22824 } 22825 } 22826 22827 @Override 22828 public void setKeepUninstalledPackages(final List<String> packageList) { 22829 Preconditions.checkNotNull(packageList); 22830 List<String> removedFromList = null; 22831 synchronized (mPackages) { 22832 if (mKeepUninstalledPackages != null) { 22833 final int packagesCount = mKeepUninstalledPackages.size(); 22834 for (int i = 0; i < packagesCount; i++) { 22835 String oldPackage = mKeepUninstalledPackages.get(i); 22836 if (packageList != null && packageList.contains(oldPackage)) { 22837 continue; 22838 } 22839 if (removedFromList == null) { 22840 removedFromList = new ArrayList<>(); 22841 } 22842 removedFromList.add(oldPackage); 22843 } 22844 } 22845 mKeepUninstalledPackages = new ArrayList<>(packageList); 22846 if (removedFromList != null) { 22847 final int removedCount = removedFromList.size(); 22848 for (int i = 0; i < removedCount; i++) { 22849 deletePackageIfUnusedLPr(removedFromList.get(i)); 22850 } 22851 } 22852 } 22853 } 22854 22855 @Override 22856 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22857 synchronized (mPackages) { 22858 // If we do not support permission review, done. 22859 if (!mPermissionReviewRequired) { 22860 return false; 22861 } 22862 22863 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22864 if (packageSetting == null) { 22865 return false; 22866 } 22867 22868 // Permission review applies only to apps not supporting the new permission model. 22869 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22870 return false; 22871 } 22872 22873 // Legacy apps have the permission and get user consent on launch. 22874 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22875 return permissionsState.isPermissionReviewRequired(userId); 22876 } 22877 } 22878 22879 @Override 22880 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22881 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22882 } 22883 22884 @Override 22885 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22886 int userId) { 22887 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22888 } 22889 22890 @Override 22891 public void setDeviceAndProfileOwnerPackages( 22892 int deviceOwnerUserId, String deviceOwnerPackage, 22893 SparseArray<String> profileOwnerPackages) { 22894 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22895 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22896 } 22897 22898 @Override 22899 public boolean isPackageDataProtected(int userId, String packageName) { 22900 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22901 } 22902 22903 @Override 22904 public boolean isPackageEphemeral(int userId, String packageName) { 22905 synchronized (mPackages) { 22906 final PackageSetting ps = mSettings.mPackages.get(packageName); 22907 return ps != null ? ps.getInstantApp(userId) : false; 22908 } 22909 } 22910 22911 @Override 22912 public boolean wasPackageEverLaunched(String packageName, int userId) { 22913 synchronized (mPackages) { 22914 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22915 } 22916 } 22917 22918 @Override 22919 public void grantRuntimePermission(String packageName, String name, int userId, 22920 boolean overridePolicy) { 22921 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 22922 overridePolicy); 22923 } 22924 22925 @Override 22926 public void revokeRuntimePermission(String packageName, String name, int userId, 22927 boolean overridePolicy) { 22928 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 22929 overridePolicy); 22930 } 22931 22932 @Override 22933 public String getNameForUid(int uid) { 22934 return PackageManagerService.this.getNameForUid(uid); 22935 } 22936 22937 @Override 22938 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 22939 Intent origIntent, String resolvedType, String callingPackage, int userId) { 22940 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 22941 responseObj, origIntent, resolvedType, callingPackage, userId); 22942 } 22943 22944 @Override 22945 public void grantEphemeralAccess(int userId, Intent intent, 22946 int targetAppId, int ephemeralAppId) { 22947 synchronized (mPackages) { 22948 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 22949 targetAppId, ephemeralAppId); 22950 } 22951 } 22952 22953 @Override 22954 public void pruneInstantApps() { 22955 synchronized (mPackages) { 22956 mInstantAppRegistry.pruneInstantAppsLPw(); 22957 } 22958 } 22959 22960 @Override 22961 public String getSetupWizardPackageName() { 22962 return mSetupWizardPackage; 22963 } 22964 22965 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 22966 if (policy != null) { 22967 mExternalSourcesPolicy = policy; 22968 } 22969 } 22970 22971 @Override 22972 public boolean isPackagePersistent(String packageName) { 22973 synchronized (mPackages) { 22974 PackageParser.Package pkg = mPackages.get(packageName); 22975 return pkg != null 22976 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 22977 | ApplicationInfo.FLAG_PERSISTENT)) == 22978 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 22979 : false; 22980 } 22981 } 22982 22983 @Override 22984 public List<PackageInfo> getOverlayPackages(int userId) { 22985 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 22986 synchronized (mPackages) { 22987 for (PackageParser.Package p : mPackages.values()) { 22988 if (p.mOverlayTarget != null) { 22989 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 22990 if (pkg != null) { 22991 overlayPackages.add(pkg); 22992 } 22993 } 22994 } 22995 } 22996 return overlayPackages; 22997 } 22998 22999 @Override 23000 public List<String> getTargetPackageNames(int userId) { 23001 List<String> targetPackages = new ArrayList<>(); 23002 synchronized (mPackages) { 23003 for (PackageParser.Package p : mPackages.values()) { 23004 if (p.mOverlayTarget == null) { 23005 targetPackages.add(p.packageName); 23006 } 23007 } 23008 } 23009 return targetPackages; 23010 } 23011 23012 23013 @Override 23014 public boolean setEnabledOverlayPackages(int userId, String targetPackageName, 23015 List<String> overlayPackageNames) { 23016 // TODO: implement when we integrate OMS properly 23017 return false; 23018 } 23019 } 23020 23021 @Override 23022 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23023 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23024 synchronized (mPackages) { 23025 final long identity = Binder.clearCallingIdentity(); 23026 try { 23027 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23028 packageNames, userId); 23029 } finally { 23030 Binder.restoreCallingIdentity(identity); 23031 } 23032 } 23033 } 23034 23035 @Override 23036 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23037 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23038 synchronized (mPackages) { 23039 final long identity = Binder.clearCallingIdentity(); 23040 try { 23041 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23042 packageNames, userId); 23043 } finally { 23044 Binder.restoreCallingIdentity(identity); 23045 } 23046 } 23047 } 23048 23049 private static void enforceSystemOrPhoneCaller(String tag) { 23050 int callingUid = Binder.getCallingUid(); 23051 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23052 throw new SecurityException( 23053 "Cannot call " + tag + " from UID " + callingUid); 23054 } 23055 } 23056 23057 boolean isHistoricalPackageUsageAvailable() { 23058 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23059 } 23060 23061 /** 23062 * Return a <b>copy</b> of the collection of packages known to the package manager. 23063 * @return A copy of the values of mPackages. 23064 */ 23065 Collection<PackageParser.Package> getPackages() { 23066 synchronized (mPackages) { 23067 return new ArrayList<>(mPackages.values()); 23068 } 23069 } 23070 23071 /** 23072 * Logs process start information (including base APK hash) to the security log. 23073 * @hide 23074 */ 23075 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23076 String apkFile, int pid) { 23077 if (!SecurityLog.isLoggingEnabled()) { 23078 return; 23079 } 23080 Bundle data = new Bundle(); 23081 data.putLong("startTimestamp", System.currentTimeMillis()); 23082 data.putString("processName", processName); 23083 data.putInt("uid", uid); 23084 data.putString("seinfo", seinfo); 23085 data.putString("apkFile", apkFile); 23086 data.putInt("pid", pid); 23087 Message msg = mProcessLoggingHandler.obtainMessage( 23088 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23089 msg.setData(data); 23090 mProcessLoggingHandler.sendMessage(msg); 23091 } 23092 23093 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23094 return mCompilerStats.getPackageStats(pkgName); 23095 } 23096 23097 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23098 return getOrCreateCompilerPackageStats(pkg.packageName); 23099 } 23100 23101 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23102 return mCompilerStats.getOrCreatePackageStats(pkgName); 23103 } 23104 23105 public void deleteCompilerPackageStats(String pkgName) { 23106 mCompilerStats.deletePackageStats(pkgName); 23107 } 23108 23109 @Override 23110 public int getInstallReason(String packageName, int userId) { 23111 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23112 true /* requireFullPermission */, false /* checkShell */, 23113 "get install reason"); 23114 synchronized (mPackages) { 23115 final PackageSetting ps = mSettings.mPackages.get(packageName); 23116 if (ps != null) { 23117 return ps.getInstallReason(userId); 23118 } 23119 } 23120 return PackageManager.INSTALL_REASON_UNKNOWN; 23121 } 23122 23123 @Override 23124 public boolean canRequestPackageInstalls(String packageName, int userId) { 23125 int callingUid = Binder.getCallingUid(); 23126 int uid = getPackageUid(packageName, 0, userId); 23127 if (callingUid != uid && callingUid != Process.ROOT_UID 23128 && callingUid != Process.SYSTEM_UID) { 23129 throw new SecurityException( 23130 "Caller uid " + callingUid + " does not own package " + packageName); 23131 } 23132 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23133 if (info == null) { 23134 return false; 23135 } 23136 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23137 throw new UnsupportedOperationException( 23138 "Operation only supported on apps targeting Android O or higher"); 23139 } 23140 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23141 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23142 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23143 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23144 } 23145 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23146 return false; 23147 } 23148 if (mExternalSourcesPolicy != null) { 23149 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23150 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23151 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23152 } 23153 } 23154 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23155 } 23156} 23157