PackageManagerService.java revision 0751546c16d1aae0632220dbaca6a29722708617
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.InstantAppRequest; 132import android.content.pm.AuxiliaryResolveInfo; 133import android.content.pm.FallbackCategoryProvider; 134import android.content.pm.FeatureInfo; 135import android.content.pm.IOnPermissionsChangeListener; 136import android.content.pm.IPackageDataObserver; 137import android.content.pm.IPackageDeleteObserver; 138import android.content.pm.IPackageDeleteObserver2; 139import android.content.pm.IPackageInstallObserver2; 140import android.content.pm.IPackageInstaller; 141import android.content.pm.IPackageManager; 142import android.content.pm.IPackageMoveObserver; 143import android.content.pm.IPackageStatsObserver; 144import android.content.pm.InstantAppInfo; 145import android.content.pm.InstantAppResolveInfo; 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.StorageEventListener; 208import android.os.storage.StorageManager; 209import android.os.storage.StorageManagerInternal; 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.service.pm.PackageServiceDumpProto; 217import android.system.ErrnoException; 218import android.system.Os; 219import android.text.TextUtils; 220import android.text.format.DateUtils; 221import android.util.ArrayMap; 222import android.util.ArraySet; 223import android.util.Base64; 224import android.util.DisplayMetrics; 225import android.util.EventLog; 226import android.util.ExceptionUtils; 227import android.util.Log; 228import android.util.LogPrinter; 229import android.util.MathUtils; 230import android.util.PackageUtils; 231import android.util.Pair; 232import android.util.PrintStreamPrinter; 233import android.util.Slog; 234import android.util.SparseArray; 235import android.util.SparseBooleanArray; 236import android.util.SparseIntArray; 237import android.util.Xml; 238import android.util.jar.StrictJarFile; 239import android.util.proto.ProtoOutputStream; 240import android.view.Display; 241 242import com.android.internal.R; 243import com.android.internal.annotations.GuardedBy; 244import com.android.internal.app.IMediaContainerService; 245import com.android.internal.app.ResolverActivity; 246import com.android.internal.content.NativeLibraryHelper; 247import com.android.internal.content.PackageHelper; 248import com.android.internal.logging.MetricsLogger; 249import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 250import com.android.internal.os.IParcelFileDescriptorFactory; 251import com.android.internal.os.RoSystemProperties; 252import com.android.internal.os.SomeArgs; 253import com.android.internal.os.Zygote; 254import com.android.internal.telephony.CarrierAppUtils; 255import com.android.internal.util.ArrayUtils; 256import com.android.internal.util.ConcurrentUtils; 257import com.android.internal.util.DumpUtils; 258import com.android.internal.util.FastPrintWriter; 259import com.android.internal.util.FastXmlSerializer; 260import com.android.internal.util.IndentingPrintWriter; 261import com.android.internal.util.Preconditions; 262import com.android.internal.util.XmlUtils; 263import com.android.server.AttributeCache; 264import com.android.server.DeviceIdleController; 265import com.android.server.EventLogTags; 266import com.android.server.FgThread; 267import com.android.server.IntentResolver; 268import com.android.server.LocalServices; 269import com.android.server.LockGuard; 270import com.android.server.ServiceThread; 271import com.android.server.SystemConfig; 272import com.android.server.SystemServerInitThreadPool; 273import com.android.server.Watchdog; 274import com.android.server.net.NetworkPolicyManagerInternal; 275import com.android.server.pm.BackgroundDexOptService; 276import com.android.server.pm.Installer.InstallerException; 277import com.android.server.pm.PermissionsState.PermissionState; 278import com.android.server.pm.Settings.DatabaseVersion; 279import com.android.server.pm.Settings.VersionInfo; 280import com.android.server.pm.dex.DexManager; 281import com.android.server.storage.DeviceStorageMonitorInternal; 282 283import dalvik.system.CloseGuard; 284import dalvik.system.DexFile; 285import dalvik.system.VMRuntime; 286 287import libcore.io.IoUtils; 288import libcore.util.EmptyArray; 289 290import org.xmlpull.v1.XmlPullParser; 291import org.xmlpull.v1.XmlPullParserException; 292import org.xmlpull.v1.XmlSerializer; 293 294import java.io.BufferedOutputStream; 295import java.io.BufferedReader; 296import java.io.ByteArrayInputStream; 297import java.io.ByteArrayOutputStream; 298import java.io.File; 299import java.io.FileDescriptor; 300import java.io.FileInputStream; 301import java.io.FileNotFoundException; 302import java.io.FileOutputStream; 303import java.io.FileReader; 304import java.io.FilenameFilter; 305import java.io.IOException; 306import java.io.PrintWriter; 307import java.nio.charset.StandardCharsets; 308import java.security.DigestInputStream; 309import java.security.MessageDigest; 310import java.security.NoSuchAlgorithmException; 311import java.security.PublicKey; 312import java.security.SecureRandom; 313import java.security.cert.Certificate; 314import java.security.cert.CertificateEncodingException; 315import java.security.cert.CertificateException; 316import java.text.SimpleDateFormat; 317import java.util.ArrayList; 318import java.util.Arrays; 319import java.util.Collection; 320import java.util.Collections; 321import java.util.Comparator; 322import java.util.Date; 323import java.util.HashMap; 324import java.util.HashSet; 325import java.util.Iterator; 326import java.util.List; 327import java.util.Map; 328import java.util.Objects; 329import java.util.Set; 330import java.util.concurrent.CountDownLatch; 331import java.util.concurrent.Future; 332import java.util.concurrent.TimeUnit; 333import java.util.concurrent.atomic.AtomicBoolean; 334import java.util.concurrent.atomic.AtomicInteger; 335 336/** 337 * Keep track of all those APKs everywhere. 338 * <p> 339 * Internally there are two important locks: 340 * <ul> 341 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 342 * and other related state. It is a fine-grained lock that should only be held 343 * momentarily, as it's one of the most contended locks in the system. 344 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 345 * operations typically involve heavy lifting of application data on disk. Since 346 * {@code installd} is single-threaded, and it's operations can often be slow, 347 * this lock should never be acquired while already holding {@link #mPackages}. 348 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 349 * holding {@link #mInstallLock}. 350 * </ul> 351 * Many internal methods rely on the caller to hold the appropriate locks, and 352 * this contract is expressed through method name suffixes: 353 * <ul> 354 * <li>fooLI(): the caller must hold {@link #mInstallLock} 355 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 356 * being modified must be frozen 357 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 358 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 359 * </ul> 360 * <p> 361 * Because this class is very central to the platform's security; please run all 362 * CTS and unit tests whenever making modifications: 363 * 364 * <pre> 365 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 366 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 367 * </pre> 368 */ 369public class PackageManagerService extends IPackageManager.Stub { 370 static final String TAG = "PackageManager"; 371 static final boolean DEBUG_SETTINGS = false; 372 static final boolean DEBUG_PREFERRED = false; 373 static final boolean DEBUG_UPGRADE = false; 374 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 375 private static final boolean DEBUG_BACKUP = false; 376 private static final boolean DEBUG_INSTALL = false; 377 private static final boolean DEBUG_REMOVE = false; 378 private static final boolean DEBUG_BROADCASTS = false; 379 private static final boolean DEBUG_SHOW_INFO = false; 380 private static final boolean DEBUG_PACKAGE_INFO = false; 381 private static final boolean DEBUG_INTENT_MATCHING = false; 382 private static final boolean DEBUG_PACKAGE_SCANNING = false; 383 private static final boolean DEBUG_VERIFY = false; 384 private static final boolean DEBUG_FILTERS = false; 385 386 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 387 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 388 // user, but by default initialize to this. 389 public static final boolean DEBUG_DEXOPT = false; 390 391 private static final boolean DEBUG_ABI_SELECTION = false; 392 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 393 private static final boolean DEBUG_TRIAGED_MISSING = false; 394 private static final boolean DEBUG_APP_DATA = false; 395 396 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 397 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 398 399 private static final boolean DISABLE_EPHEMERAL_APPS = false; 400 private static final boolean HIDE_EPHEMERAL_APIS = false; 401 402 private static final boolean ENABLE_FREE_CACHE_V2 = 403 SystemProperties.getBoolean("fw.free_cache_v2", true); 404 405 private static final int RADIO_UID = Process.PHONE_UID; 406 private static final int LOG_UID = Process.LOG_UID; 407 private static final int NFC_UID = Process.NFC_UID; 408 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 409 private static final int SHELL_UID = Process.SHELL_UID; 410 411 // Cap the size of permission trees that 3rd party apps can define 412 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 413 414 // Suffix used during package installation when copying/moving 415 // package apks to install directory. 416 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 417 418 static final int SCAN_NO_DEX = 1<<1; 419 static final int SCAN_FORCE_DEX = 1<<2; 420 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 421 static final int SCAN_NEW_INSTALL = 1<<4; 422 static final int SCAN_UPDATE_TIME = 1<<5; 423 static final int SCAN_BOOTING = 1<<6; 424 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 425 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 426 static final int SCAN_REPLACING = 1<<9; 427 static final int SCAN_REQUIRE_KNOWN = 1<<10; 428 static final int SCAN_MOVE = 1<<11; 429 static final int SCAN_INITIAL = 1<<12; 430 static final int SCAN_CHECK_ONLY = 1<<13; 431 static final int SCAN_DONT_KILL_APP = 1<<14; 432 static final int SCAN_IGNORE_FROZEN = 1<<15; 433 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 434 static final int SCAN_AS_INSTANT_APP = 1<<17; 435 static final int SCAN_AS_FULL_APP = 1<<18; 436 /** Should not be with the scan flags */ 437 static final int FLAGS_REMOVE_CHATTY = 1<<31; 438 439 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 440 441 private static final int[] EMPTY_INT_ARRAY = new int[0]; 442 443 /** 444 * Timeout (in milliseconds) after which the watchdog should declare that 445 * our handler thread is wedged. The usual default for such things is one 446 * minute but we sometimes do very lengthy I/O operations on this thread, 447 * such as installing multi-gigabyte applications, so ours needs to be longer. 448 */ 449 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 450 451 /** 452 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 453 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 454 * settings entry if available, otherwise we use the hardcoded default. If it's been 455 * more than this long since the last fstrim, we force one during the boot sequence. 456 * 457 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 458 * one gets run at the next available charging+idle time. This final mandatory 459 * no-fstrim check kicks in only of the other scheduling criteria is never met. 460 */ 461 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 462 463 /** 464 * Whether verification is enabled by default. 465 */ 466 private static final boolean DEFAULT_VERIFY_ENABLE = true; 467 468 /** 469 * The default maximum time to wait for the verification agent to return in 470 * milliseconds. 471 */ 472 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 473 474 /** 475 * The default response for package verification timeout. 476 * 477 * This can be either PackageManager.VERIFICATION_ALLOW or 478 * PackageManager.VERIFICATION_REJECT. 479 */ 480 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 481 482 static final String PLATFORM_PACKAGE_NAME = "android"; 483 484 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 485 486 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 487 DEFAULT_CONTAINER_PACKAGE, 488 "com.android.defcontainer.DefaultContainerService"); 489 490 private static final String KILL_APP_REASON_GIDS_CHANGED = 491 "permission grant or revoke changed gids"; 492 493 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 494 "permissions revoked"; 495 496 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 497 498 private static final String PACKAGE_SCHEME = "package"; 499 500 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 501 502 /** Permission grant: not grant the permission. */ 503 private static final int GRANT_DENIED = 1; 504 505 /** Permission grant: grant the permission as an install permission. */ 506 private static final int GRANT_INSTALL = 2; 507 508 /** Permission grant: grant the permission as a runtime one. */ 509 private static final int GRANT_RUNTIME = 3; 510 511 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 512 private static final int GRANT_UPGRADE = 4; 513 514 /** Canonical intent used to identify what counts as a "web browser" app */ 515 private static final Intent sBrowserIntent; 516 static { 517 sBrowserIntent = new Intent(); 518 sBrowserIntent.setAction(Intent.ACTION_VIEW); 519 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 520 sBrowserIntent.setData(Uri.parse("http:")); 521 } 522 523 /** 524 * The set of all protected actions [i.e. those actions for which a high priority 525 * intent filter is disallowed]. 526 */ 527 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 528 static { 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 531 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 532 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 533 } 534 535 // Compilation reasons. 536 public static final int REASON_FIRST_BOOT = 0; 537 public static final int REASON_BOOT = 1; 538 public static final int REASON_INSTALL = 2; 539 public static final int REASON_BACKGROUND_DEXOPT = 3; 540 public static final int REASON_AB_OTA = 4; 541 public static final int REASON_FORCED_DEXOPT = 5; 542 543 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 544 545 /** All dangerous permission names in the same order as the events in MetricsEvent */ 546 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 547 Manifest.permission.READ_CALENDAR, 548 Manifest.permission.WRITE_CALENDAR, 549 Manifest.permission.CAMERA, 550 Manifest.permission.READ_CONTACTS, 551 Manifest.permission.WRITE_CONTACTS, 552 Manifest.permission.GET_ACCOUNTS, 553 Manifest.permission.ACCESS_FINE_LOCATION, 554 Manifest.permission.ACCESS_COARSE_LOCATION, 555 Manifest.permission.RECORD_AUDIO, 556 Manifest.permission.READ_PHONE_STATE, 557 Manifest.permission.CALL_PHONE, 558 Manifest.permission.READ_CALL_LOG, 559 Manifest.permission.WRITE_CALL_LOG, 560 Manifest.permission.ADD_VOICEMAIL, 561 Manifest.permission.USE_SIP, 562 Manifest.permission.PROCESS_OUTGOING_CALLS, 563 Manifest.permission.READ_CELL_BROADCASTS, 564 Manifest.permission.BODY_SENSORS, 565 Manifest.permission.SEND_SMS, 566 Manifest.permission.RECEIVE_SMS, 567 Manifest.permission.READ_SMS, 568 Manifest.permission.RECEIVE_WAP_PUSH, 569 Manifest.permission.RECEIVE_MMS, 570 Manifest.permission.READ_EXTERNAL_STORAGE, 571 Manifest.permission.WRITE_EXTERNAL_STORAGE, 572 Manifest.permission.READ_PHONE_NUMBER, 573 Manifest.permission.ANSWER_PHONE_CALLS); 574 575 576 /** 577 * Version number for the package parser cache. Increment this whenever the format or 578 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 579 */ 580 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 581 582 /** 583 * Whether the package parser cache is enabled. 584 */ 585 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 586 587 final ServiceThread mHandlerThread; 588 589 final PackageHandler mHandler; 590 591 private final ProcessLoggingHandler mProcessLoggingHandler; 592 593 /** 594 * Messages for {@link #mHandler} that need to wait for system ready before 595 * being dispatched. 596 */ 597 private ArrayList<Message> mPostSystemReadyMessages; 598 599 final int mSdkVersion = Build.VERSION.SDK_INT; 600 601 final Context mContext; 602 final boolean mFactoryTest; 603 final boolean mOnlyCore; 604 final DisplayMetrics mMetrics; 605 final int mDefParseFlags; 606 final String[] mSeparateProcesses; 607 final boolean mIsUpgrade; 608 final boolean mIsPreNUpgrade; 609 final boolean mIsPreNMR1Upgrade; 610 611 @GuardedBy("mPackages") 612 private boolean mDexOptDialogShown; 613 614 /** The location for ASEC container files on internal storage. */ 615 final String mAsecInternalPath; 616 617 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 618 // LOCK HELD. Can be called with mInstallLock held. 619 @GuardedBy("mInstallLock") 620 final Installer mInstaller; 621 622 /** Directory where installed third-party apps stored */ 623 final File mAppInstallDir; 624 625 /** 626 * Directory to which applications installed internally have their 627 * 32 bit native libraries copied. 628 */ 629 private File mAppLib32InstallDir; 630 631 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 632 // apps. 633 final File mDrmAppPrivateInstallDir; 634 635 // ---------------------------------------------------------------- 636 637 // Lock for state used when installing and doing other long running 638 // operations. Methods that must be called with this lock held have 639 // the suffix "LI". 640 final Object mInstallLock = new Object(); 641 642 // ---------------------------------------------------------------- 643 644 // Keys are String (package name), values are Package. This also serves 645 // as the lock for the global state. Methods that must be called with 646 // this lock held have the prefix "LP". 647 @GuardedBy("mPackages") 648 final ArrayMap<String, PackageParser.Package> mPackages = 649 new ArrayMap<String, PackageParser.Package>(); 650 651 final ArrayMap<String, Set<String>> mKnownCodebase = 652 new ArrayMap<String, Set<String>>(); 653 654 // Keys are isolated uids and values are the uid of the application 655 // that created the isolated proccess. 656 @GuardedBy("mPackages") 657 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 658 659 // List of APK paths to load for each user and package. This data is never 660 // persisted by the package manager. Instead, the overlay manager will 661 // ensure the data is up-to-date in runtime. 662 @GuardedBy("mPackages") 663 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 664 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 665 666 /** 667 * Tracks new system packages [received in an OTA] that we expect to 668 * find updated user-installed versions. Keys are package name, values 669 * are package location. 670 */ 671 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 672 /** 673 * Tracks high priority intent filters for protected actions. During boot, certain 674 * filter actions are protected and should never be allowed to have a high priority 675 * intent filter for them. However, there is one, and only one exception -- the 676 * setup wizard. It must be able to define a high priority intent filter for these 677 * actions to ensure there are no escapes from the wizard. We need to delay processing 678 * of these during boot as we need to look at all of the system packages in order 679 * to know which component is the setup wizard. 680 */ 681 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 682 /** 683 * Whether or not processing protected filters should be deferred. 684 */ 685 private boolean mDeferProtectedFilters = true; 686 687 /** 688 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 689 */ 690 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 691 /** 692 * Whether or not system app permissions should be promoted from install to runtime. 693 */ 694 boolean mPromoteSystemApps; 695 696 @GuardedBy("mPackages") 697 final Settings mSettings; 698 699 /** 700 * Set of package names that are currently "frozen", which means active 701 * surgery is being done on the code/data for that package. The platform 702 * will refuse to launch frozen packages to avoid race conditions. 703 * 704 * @see PackageFreezer 705 */ 706 @GuardedBy("mPackages") 707 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 708 709 final ProtectedPackages mProtectedPackages; 710 711 boolean mFirstBoot; 712 713 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 714 715 // System configuration read by SystemConfig. 716 final int[] mGlobalGids; 717 final SparseArray<ArraySet<String>> mSystemPermissions; 718 @GuardedBy("mAvailableFeatures") 719 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 720 721 // If mac_permissions.xml was found for seinfo labeling. 722 boolean mFoundPolicyFile; 723 724 private final InstantAppRegistry mInstantAppRegistry; 725 726 @GuardedBy("mPackages") 727 int mChangedPackagesSequenceNumber; 728 /** 729 * List of changed [installed, removed or updated] packages. 730 * mapping from user id -> sequence number -> package name 731 */ 732 @GuardedBy("mPackages") 733 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 734 /** 735 * The sequence number of the last change to a package. 736 * mapping from user id -> package name -> sequence number 737 */ 738 @GuardedBy("mPackages") 739 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 740 741 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 742 @Override public boolean hasFeature(String feature) { 743 return PackageManagerService.this.hasSystemFeature(feature, 0); 744 } 745 }; 746 747 public static final class SharedLibraryEntry { 748 public final String path; 749 public final String apk; 750 public final SharedLibraryInfo info; 751 752 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 753 String declaringPackageName, int declaringPackageVersionCode) { 754 path = _path; 755 apk = _apk; 756 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 757 declaringPackageName, declaringPackageVersionCode), null); 758 } 759 } 760 761 // Currently known shared libraries. 762 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 763 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 764 new ArrayMap<>(); 765 766 // All available activities, for your resolving pleasure. 767 final ActivityIntentResolver mActivities = 768 new ActivityIntentResolver(); 769 770 // All available receivers, for your resolving pleasure. 771 final ActivityIntentResolver mReceivers = 772 new ActivityIntentResolver(); 773 774 // All available services, for your resolving pleasure. 775 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 776 777 // All available providers, for your resolving pleasure. 778 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 779 780 // Mapping from provider base names (first directory in content URI codePath) 781 // to the provider information. 782 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 783 new ArrayMap<String, PackageParser.Provider>(); 784 785 // Mapping from instrumentation class names to info about them. 786 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 787 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 788 789 // Mapping from permission names to info about them. 790 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 791 new ArrayMap<String, PackageParser.PermissionGroup>(); 792 793 // Packages whose data we have transfered into another package, thus 794 // should no longer exist. 795 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 796 797 // Broadcast actions that are only available to the system. 798 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 799 800 /** List of packages waiting for verification. */ 801 final SparseArray<PackageVerificationState> mPendingVerification 802 = new SparseArray<PackageVerificationState>(); 803 804 /** Set of packages associated with each app op permission. */ 805 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 806 807 final PackageInstallerService mInstallerService; 808 809 private final PackageDexOptimizer mPackageDexOptimizer; 810 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 811 // is used by other apps). 812 private final DexManager mDexManager; 813 814 private AtomicInteger mNextMoveId = new AtomicInteger(); 815 private final MoveCallbacks mMoveCallbacks; 816 817 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 818 819 // Cache of users who need badging. 820 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 821 822 /** Token for keys in mPendingVerification. */ 823 private int mPendingVerificationToken = 0; 824 825 volatile boolean mSystemReady; 826 volatile boolean mSafeMode; 827 volatile boolean mHasSystemUidErrors; 828 829 ApplicationInfo mAndroidApplication; 830 final ActivityInfo mResolveActivity = new ActivityInfo(); 831 final ResolveInfo mResolveInfo = new ResolveInfo(); 832 ComponentName mResolveComponentName; 833 PackageParser.Package mPlatformPackage; 834 ComponentName mCustomResolverComponentName; 835 836 boolean mResolverReplaced = false; 837 838 private final @Nullable ComponentName mIntentFilterVerifierComponent; 839 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 840 841 private int mIntentFilterVerificationToken = 0; 842 843 /** The service connection to the ephemeral resolver */ 844 final EphemeralResolverConnection mInstantAppResolverConnection; 845 846 /** Component used to install ephemeral applications */ 847 ComponentName mInstantAppInstallerComponent; 848 /** Component used to show resolver settings for Instant Apps */ 849 ComponentName mInstantAppResolverSettingsComponent; 850 ActivityInfo mInstantAppInstallerActivity; 851 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 852 853 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 854 = new SparseArray<IntentFilterVerificationState>(); 855 856 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 857 858 // List of packages names to keep cached, even if they are uninstalled for all users 859 private List<String> mKeepUninstalledPackages; 860 861 private UserManagerInternal mUserManagerInternal; 862 863 private DeviceIdleController.LocalService mDeviceIdleController; 864 865 private File mCacheDir; 866 867 private ArraySet<String> mPrivappPermissionsViolations; 868 869 private Future<?> mPrepareAppDataFuture; 870 871 private static class IFVerificationParams { 872 PackageParser.Package pkg; 873 boolean replacing; 874 int userId; 875 int verifierUid; 876 877 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 878 int _userId, int _verifierUid) { 879 pkg = _pkg; 880 replacing = _replacing; 881 userId = _userId; 882 replacing = _replacing; 883 verifierUid = _verifierUid; 884 } 885 } 886 887 private interface IntentFilterVerifier<T extends IntentFilter> { 888 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 889 T filter, String packageName); 890 void startVerifications(int userId); 891 void receiveVerificationResponse(int verificationId); 892 } 893 894 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 895 private Context mContext; 896 private ComponentName mIntentFilterVerifierComponent; 897 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 898 899 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 900 mContext = context; 901 mIntentFilterVerifierComponent = verifierComponent; 902 } 903 904 private String getDefaultScheme() { 905 return IntentFilter.SCHEME_HTTPS; 906 } 907 908 @Override 909 public void startVerifications(int userId) { 910 // Launch verifications requests 911 int count = mCurrentIntentFilterVerifications.size(); 912 for (int n=0; n<count; n++) { 913 int verificationId = mCurrentIntentFilterVerifications.get(n); 914 final IntentFilterVerificationState ivs = 915 mIntentFilterVerificationStates.get(verificationId); 916 917 String packageName = ivs.getPackageName(); 918 919 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 920 final int filterCount = filters.size(); 921 ArraySet<String> domainsSet = new ArraySet<>(); 922 for (int m=0; m<filterCount; m++) { 923 PackageParser.ActivityIntentInfo filter = filters.get(m); 924 domainsSet.addAll(filter.getHostsList()); 925 } 926 synchronized (mPackages) { 927 if (mSettings.createIntentFilterVerificationIfNeededLPw( 928 packageName, domainsSet) != null) { 929 scheduleWriteSettingsLocked(); 930 } 931 } 932 sendVerificationRequest(userId, verificationId, ivs); 933 } 934 mCurrentIntentFilterVerifications.clear(); 935 } 936 937 private void sendVerificationRequest(int userId, int verificationId, 938 IntentFilterVerificationState ivs) { 939 940 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 941 verificationIntent.putExtra( 942 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 943 verificationId); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 946 getDefaultScheme()); 947 verificationIntent.putExtra( 948 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 949 ivs.getHostsString()); 950 verificationIntent.putExtra( 951 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 952 ivs.getPackageName()); 953 verificationIntent.setComponent(mIntentFilterVerifierComponent); 954 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 955 956 UserHandle user = new UserHandle(userId); 957 mContext.sendBroadcastAsUser(verificationIntent, user); 958 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 959 "Sending IntentFilter verification broadcast"); 960 } 961 962 public void receiveVerificationResponse(int verificationId) { 963 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 964 965 final boolean verified = ivs.isVerified(); 966 967 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 968 final int count = filters.size(); 969 if (DEBUG_DOMAIN_VERIFICATION) { 970 Slog.i(TAG, "Received verification response " + verificationId 971 + " for " + count + " filters, verified=" + verified); 972 } 973 for (int n=0; n<count; n++) { 974 PackageParser.ActivityIntentInfo filter = filters.get(n); 975 filter.setVerified(verified); 976 977 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 978 + " verified with result:" + verified + " and hosts:" 979 + ivs.getHostsString()); 980 } 981 982 mIntentFilterVerificationStates.remove(verificationId); 983 984 final String packageName = ivs.getPackageName(); 985 IntentFilterVerificationInfo ivi = null; 986 987 synchronized (mPackages) { 988 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 989 } 990 if (ivi == null) { 991 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 992 + verificationId + " packageName:" + packageName); 993 return; 994 } 995 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 996 "Updating IntentFilterVerificationInfo for package " + packageName 997 +" verificationId:" + verificationId); 998 999 synchronized (mPackages) { 1000 if (verified) { 1001 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1002 } else { 1003 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1004 } 1005 scheduleWriteSettingsLocked(); 1006 1007 final int userId = ivs.getUserId(); 1008 if (userId != UserHandle.USER_ALL) { 1009 final int userStatus = 1010 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1011 1012 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1013 boolean needUpdate = false; 1014 1015 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1016 // already been set by the User thru the Disambiguation dialog 1017 switch (userStatus) { 1018 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1019 if (verified) { 1020 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1021 } else { 1022 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1023 } 1024 needUpdate = true; 1025 break; 1026 1027 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1028 if (verified) { 1029 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1030 needUpdate = true; 1031 } 1032 break; 1033 1034 default: 1035 // Nothing to do 1036 } 1037 1038 if (needUpdate) { 1039 mSettings.updateIntentFilterVerificationStatusLPw( 1040 packageName, updatedStatus, userId); 1041 scheduleWritePackageRestrictionsLocked(userId); 1042 } 1043 } 1044 } 1045 } 1046 1047 @Override 1048 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1049 ActivityIntentInfo filter, String packageName) { 1050 if (!hasValidDomains(filter)) { 1051 return false; 1052 } 1053 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1054 if (ivs == null) { 1055 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1056 packageName); 1057 } 1058 if (DEBUG_DOMAIN_VERIFICATION) { 1059 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1060 } 1061 ivs.addFilter(filter); 1062 return true; 1063 } 1064 1065 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1066 int userId, int verificationId, String packageName) { 1067 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1068 verifierUid, userId, packageName); 1069 ivs.setPendingState(); 1070 synchronized (mPackages) { 1071 mIntentFilterVerificationStates.append(verificationId, ivs); 1072 mCurrentIntentFilterVerifications.add(verificationId); 1073 } 1074 return ivs; 1075 } 1076 } 1077 1078 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1079 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1080 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1081 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1082 } 1083 1084 // Set of pending broadcasts for aggregating enable/disable of components. 1085 static class PendingPackageBroadcasts { 1086 // for each user id, a map of <package name -> components within that package> 1087 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1088 1089 public PendingPackageBroadcasts() { 1090 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1091 } 1092 1093 public ArrayList<String> get(int userId, String packageName) { 1094 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1095 return packages.get(packageName); 1096 } 1097 1098 public void put(int userId, String packageName, ArrayList<String> components) { 1099 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1100 packages.put(packageName, components); 1101 } 1102 1103 public void remove(int userId, String packageName) { 1104 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1105 if (packages != null) { 1106 packages.remove(packageName); 1107 } 1108 } 1109 1110 public void remove(int userId) { 1111 mUidMap.remove(userId); 1112 } 1113 1114 public int userIdCount() { 1115 return mUidMap.size(); 1116 } 1117 1118 public int userIdAt(int n) { 1119 return mUidMap.keyAt(n); 1120 } 1121 1122 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1123 return mUidMap.get(userId); 1124 } 1125 1126 public int size() { 1127 // total number of pending broadcast entries across all userIds 1128 int num = 0; 1129 for (int i = 0; i< mUidMap.size(); i++) { 1130 num += mUidMap.valueAt(i).size(); 1131 } 1132 return num; 1133 } 1134 1135 public void clear() { 1136 mUidMap.clear(); 1137 } 1138 1139 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1140 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1141 if (map == null) { 1142 map = new ArrayMap<String, ArrayList<String>>(); 1143 mUidMap.put(userId, map); 1144 } 1145 return map; 1146 } 1147 } 1148 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1149 1150 // Service Connection to remote media container service to copy 1151 // package uri's from external media onto secure containers 1152 // or internal storage. 1153 private IMediaContainerService mContainerService = null; 1154 1155 static final int SEND_PENDING_BROADCAST = 1; 1156 static final int MCS_BOUND = 3; 1157 static final int END_COPY = 4; 1158 static final int INIT_COPY = 5; 1159 static final int MCS_UNBIND = 6; 1160 static final int START_CLEANING_PACKAGE = 7; 1161 static final int FIND_INSTALL_LOC = 8; 1162 static final int POST_INSTALL = 9; 1163 static final int MCS_RECONNECT = 10; 1164 static final int MCS_GIVE_UP = 11; 1165 static final int UPDATED_MEDIA_STATUS = 12; 1166 static final int WRITE_SETTINGS = 13; 1167 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1168 static final int PACKAGE_VERIFIED = 15; 1169 static final int CHECK_PENDING_VERIFICATION = 16; 1170 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1171 static final int INTENT_FILTER_VERIFIED = 18; 1172 static final int WRITE_PACKAGE_LIST = 19; 1173 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1174 1175 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1176 1177 // Delay time in millisecs 1178 static final int BROADCAST_DELAY = 10 * 1000; 1179 1180 static UserManagerService sUserManager; 1181 1182 // Stores a list of users whose package restrictions file needs to be updated 1183 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1184 1185 final private DefaultContainerConnection mDefContainerConn = 1186 new DefaultContainerConnection(); 1187 class DefaultContainerConnection implements ServiceConnection { 1188 public void onServiceConnected(ComponentName name, IBinder service) { 1189 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1190 final IMediaContainerService imcs = IMediaContainerService.Stub 1191 .asInterface(Binder.allowBlocking(service)); 1192 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1193 } 1194 1195 public void onServiceDisconnected(ComponentName name) { 1196 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1197 } 1198 } 1199 1200 // Recordkeeping of restore-after-install operations that are currently in flight 1201 // between the Package Manager and the Backup Manager 1202 static class PostInstallData { 1203 public InstallArgs args; 1204 public PackageInstalledInfo res; 1205 1206 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1207 args = _a; 1208 res = _r; 1209 } 1210 } 1211 1212 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1213 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1214 1215 // XML tags for backup/restore of various bits of state 1216 private static final String TAG_PREFERRED_BACKUP = "pa"; 1217 private static final String TAG_DEFAULT_APPS = "da"; 1218 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1219 1220 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1221 private static final String TAG_ALL_GRANTS = "rt-grants"; 1222 private static final String TAG_GRANT = "grant"; 1223 private static final String ATTR_PACKAGE_NAME = "pkg"; 1224 1225 private static final String TAG_PERMISSION = "perm"; 1226 private static final String ATTR_PERMISSION_NAME = "name"; 1227 private static final String ATTR_IS_GRANTED = "g"; 1228 private static final String ATTR_USER_SET = "set"; 1229 private static final String ATTR_USER_FIXED = "fixed"; 1230 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1231 1232 // System/policy permission grants are not backed up 1233 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1234 FLAG_PERMISSION_POLICY_FIXED 1235 | FLAG_PERMISSION_SYSTEM_FIXED 1236 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1237 1238 // And we back up these user-adjusted states 1239 private static final int USER_RUNTIME_GRANT_MASK = 1240 FLAG_PERMISSION_USER_SET 1241 | FLAG_PERMISSION_USER_FIXED 1242 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1243 1244 final @Nullable String mRequiredVerifierPackage; 1245 final @NonNull String mRequiredInstallerPackage; 1246 final @NonNull String mRequiredUninstallerPackage; 1247 final @Nullable String mSetupWizardPackage; 1248 final @Nullable String mStorageManagerPackage; 1249 final @NonNull String mServicesSystemSharedLibraryPackageName; 1250 final @NonNull String mSharedSystemSharedLibraryPackageName; 1251 1252 final boolean mPermissionReviewRequired; 1253 1254 private final PackageUsage mPackageUsage = new PackageUsage(); 1255 private final CompilerStats mCompilerStats = new CompilerStats(); 1256 1257 class PackageHandler extends Handler { 1258 private boolean mBound = false; 1259 final ArrayList<HandlerParams> mPendingInstalls = 1260 new ArrayList<HandlerParams>(); 1261 1262 private boolean connectToService() { 1263 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1264 " DefaultContainerService"); 1265 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1266 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1267 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1268 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1269 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1270 mBound = true; 1271 return true; 1272 } 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1274 return false; 1275 } 1276 1277 private void disconnectService() { 1278 mContainerService = null; 1279 mBound = false; 1280 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1281 mContext.unbindService(mDefContainerConn); 1282 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1283 } 1284 1285 PackageHandler(Looper looper) { 1286 super(looper); 1287 } 1288 1289 public void handleMessage(Message msg) { 1290 try { 1291 doHandleMessage(msg); 1292 } finally { 1293 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1294 } 1295 } 1296 1297 void doHandleMessage(Message msg) { 1298 switch (msg.what) { 1299 case INIT_COPY: { 1300 HandlerParams params = (HandlerParams) msg.obj; 1301 int idx = mPendingInstalls.size(); 1302 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1303 // If a bind was already initiated we dont really 1304 // need to do anything. The pending install 1305 // will be processed later on. 1306 if (!mBound) { 1307 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1308 System.identityHashCode(mHandler)); 1309 // If this is the only one pending we might 1310 // have to bind to the service again. 1311 if (!connectToService()) { 1312 Slog.e(TAG, "Failed to bind to media container service"); 1313 params.serviceError(); 1314 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1315 System.identityHashCode(mHandler)); 1316 if (params.traceMethod != null) { 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1318 params.traceCookie); 1319 } 1320 return; 1321 } else { 1322 // Once we bind to the service, the first 1323 // pending request will be processed. 1324 mPendingInstalls.add(idx, params); 1325 } 1326 } else { 1327 mPendingInstalls.add(idx, params); 1328 // Already bound to the service. Just make 1329 // sure we trigger off processing the first request. 1330 if (idx == 0) { 1331 mHandler.sendEmptyMessage(MCS_BOUND); 1332 } 1333 } 1334 break; 1335 } 1336 case MCS_BOUND: { 1337 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1338 if (msg.obj != null) { 1339 mContainerService = (IMediaContainerService) msg.obj; 1340 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1341 System.identityHashCode(mHandler)); 1342 } 1343 if (mContainerService == null) { 1344 if (!mBound) { 1345 // Something seriously wrong since we are not bound and we are not 1346 // waiting for connection. Bail out. 1347 Slog.e(TAG, "Cannot bind to media container service"); 1348 for (HandlerParams params : mPendingInstalls) { 1349 // Indicate service bind error 1350 params.serviceError(); 1351 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1352 System.identityHashCode(params)); 1353 if (params.traceMethod != null) { 1354 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1355 params.traceMethod, params.traceCookie); 1356 } 1357 return; 1358 } 1359 mPendingInstalls.clear(); 1360 } else { 1361 Slog.w(TAG, "Waiting to connect to media container service"); 1362 } 1363 } else if (mPendingInstalls.size() > 0) { 1364 HandlerParams params = mPendingInstalls.get(0); 1365 if (params != null) { 1366 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1367 System.identityHashCode(params)); 1368 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1369 if (params.startCopy()) { 1370 // We are done... look for more work or to 1371 // go idle. 1372 if (DEBUG_SD_INSTALL) Log.i(TAG, 1373 "Checking for more work or unbind..."); 1374 // Delete pending install 1375 if (mPendingInstalls.size() > 0) { 1376 mPendingInstalls.remove(0); 1377 } 1378 if (mPendingInstalls.size() == 0) { 1379 if (mBound) { 1380 if (DEBUG_SD_INSTALL) Log.i(TAG, 1381 "Posting delayed MCS_UNBIND"); 1382 removeMessages(MCS_UNBIND); 1383 Message ubmsg = obtainMessage(MCS_UNBIND); 1384 // Unbind after a little delay, to avoid 1385 // continual thrashing. 1386 sendMessageDelayed(ubmsg, 10000); 1387 } 1388 } else { 1389 // There are more pending requests in queue. 1390 // Just post MCS_BOUND message to trigger processing 1391 // of next pending install. 1392 if (DEBUG_SD_INSTALL) Log.i(TAG, 1393 "Posting MCS_BOUND for next work"); 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1398 } 1399 } else { 1400 // Should never happen ideally. 1401 Slog.w(TAG, "Empty queue"); 1402 } 1403 break; 1404 } 1405 case MCS_RECONNECT: { 1406 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1407 if (mPendingInstalls.size() > 0) { 1408 if (mBound) { 1409 disconnectService(); 1410 } 1411 if (!connectToService()) { 1412 Slog.e(TAG, "Failed to bind to media container service"); 1413 for (HandlerParams params : mPendingInstalls) { 1414 // Indicate service bind error 1415 params.serviceError(); 1416 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1417 System.identityHashCode(params)); 1418 } 1419 mPendingInstalls.clear(); 1420 } 1421 } 1422 break; 1423 } 1424 case MCS_UNBIND: { 1425 // If there is no actual work left, then time to unbind. 1426 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1427 1428 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1429 if (mBound) { 1430 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1431 1432 disconnectService(); 1433 } 1434 } else if (mPendingInstalls.size() > 0) { 1435 // There are more pending requests in queue. 1436 // Just post MCS_BOUND message to trigger processing 1437 // of next pending install. 1438 mHandler.sendEmptyMessage(MCS_BOUND); 1439 } 1440 1441 break; 1442 } 1443 case MCS_GIVE_UP: { 1444 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1445 HandlerParams params = mPendingInstalls.remove(0); 1446 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1447 System.identityHashCode(params)); 1448 break; 1449 } 1450 case SEND_PENDING_BROADCAST: { 1451 String packages[]; 1452 ArrayList<String> components[]; 1453 int size = 0; 1454 int uids[]; 1455 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1456 synchronized (mPackages) { 1457 if (mPendingBroadcasts == null) { 1458 return; 1459 } 1460 size = mPendingBroadcasts.size(); 1461 if (size <= 0) { 1462 // Nothing to be done. Just return 1463 return; 1464 } 1465 packages = new String[size]; 1466 components = new ArrayList[size]; 1467 uids = new int[size]; 1468 int i = 0; // filling out the above arrays 1469 1470 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1471 int packageUserId = mPendingBroadcasts.userIdAt(n); 1472 Iterator<Map.Entry<String, ArrayList<String>>> it 1473 = mPendingBroadcasts.packagesForUserId(packageUserId) 1474 .entrySet().iterator(); 1475 while (it.hasNext() && i < size) { 1476 Map.Entry<String, ArrayList<String>> ent = it.next(); 1477 packages[i] = ent.getKey(); 1478 components[i] = ent.getValue(); 1479 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1480 uids[i] = (ps != null) 1481 ? UserHandle.getUid(packageUserId, ps.appId) 1482 : -1; 1483 i++; 1484 } 1485 } 1486 size = i; 1487 mPendingBroadcasts.clear(); 1488 } 1489 // Send broadcasts 1490 for (int i = 0; i < size; i++) { 1491 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1492 } 1493 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1494 break; 1495 } 1496 case START_CLEANING_PACKAGE: { 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1498 final String packageName = (String)msg.obj; 1499 final int userId = msg.arg1; 1500 final boolean andCode = msg.arg2 != 0; 1501 synchronized (mPackages) { 1502 if (userId == UserHandle.USER_ALL) { 1503 int[] users = sUserManager.getUserIds(); 1504 for (int user : users) { 1505 mSettings.addPackageToCleanLPw( 1506 new PackageCleanItem(user, packageName, andCode)); 1507 } 1508 } else { 1509 mSettings.addPackageToCleanLPw( 1510 new PackageCleanItem(userId, packageName, andCode)); 1511 } 1512 } 1513 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1514 startCleaningPackages(); 1515 } break; 1516 case POST_INSTALL: { 1517 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1518 1519 PostInstallData data = mRunningInstalls.get(msg.arg1); 1520 final boolean didRestore = (msg.arg2 != 0); 1521 mRunningInstalls.delete(msg.arg1); 1522 1523 if (data != null) { 1524 InstallArgs args = data.args; 1525 PackageInstalledInfo parentRes = data.res; 1526 1527 final boolean grantPermissions = (args.installFlags 1528 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1529 final boolean killApp = (args.installFlags 1530 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1531 final String[] grantedPermissions = args.installGrantPermissions; 1532 1533 // Handle the parent package 1534 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1535 grantedPermissions, didRestore, args.installerPackageName, 1536 args.observer); 1537 1538 // Handle the child packages 1539 final int childCount = (parentRes.addedChildPackages != null) 1540 ? parentRes.addedChildPackages.size() : 0; 1541 for (int i = 0; i < childCount; i++) { 1542 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1543 handlePackagePostInstall(childRes, grantPermissions, killApp, 1544 grantedPermissions, false, args.installerPackageName, 1545 args.observer); 1546 } 1547 1548 // Log tracing if needed 1549 if (args.traceMethod != null) { 1550 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1551 args.traceCookie); 1552 } 1553 } else { 1554 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1555 } 1556 1557 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1558 } break; 1559 case UPDATED_MEDIA_STATUS: { 1560 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1561 boolean reportStatus = msg.arg1 == 1; 1562 boolean doGc = msg.arg2 == 1; 1563 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1564 if (doGc) { 1565 // Force a gc to clear up stale containers. 1566 Runtime.getRuntime().gc(); 1567 } 1568 if (msg.obj != null) { 1569 @SuppressWarnings("unchecked") 1570 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1571 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1572 // Unload containers 1573 unloadAllContainers(args); 1574 } 1575 if (reportStatus) { 1576 try { 1577 if (DEBUG_SD_INSTALL) Log.i(TAG, 1578 "Invoking StorageManagerService call back"); 1579 PackageHelper.getStorageManager().finishMediaUpdate(); 1580 } catch (RemoteException e) { 1581 Log.e(TAG, "StorageManagerService not running?"); 1582 } 1583 } 1584 } break; 1585 case WRITE_SETTINGS: { 1586 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1587 synchronized (mPackages) { 1588 removeMessages(WRITE_SETTINGS); 1589 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1590 mSettings.writeLPr(); 1591 mDirtyUsers.clear(); 1592 } 1593 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1594 } break; 1595 case WRITE_PACKAGE_RESTRICTIONS: { 1596 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1597 synchronized (mPackages) { 1598 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1599 for (int userId : mDirtyUsers) { 1600 mSettings.writePackageRestrictionsLPr(userId); 1601 } 1602 mDirtyUsers.clear(); 1603 } 1604 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1605 } break; 1606 case WRITE_PACKAGE_LIST: { 1607 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1608 synchronized (mPackages) { 1609 removeMessages(WRITE_PACKAGE_LIST); 1610 mSettings.writePackageListLPr(msg.arg1); 1611 } 1612 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1613 } break; 1614 case CHECK_PENDING_VERIFICATION: { 1615 final int verificationId = msg.arg1; 1616 final PackageVerificationState state = mPendingVerification.get(verificationId); 1617 1618 if ((state != null) && !state.timeoutExtended()) { 1619 final InstallArgs args = state.getInstallArgs(); 1620 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1621 1622 Slog.i(TAG, "Verification timed out for " + originUri); 1623 mPendingVerification.remove(verificationId); 1624 1625 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1626 1627 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1628 Slog.i(TAG, "Continuing with installation of " + originUri); 1629 state.setVerifierResponse(Binder.getCallingUid(), 1630 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1631 broadcastPackageVerified(verificationId, originUri, 1632 PackageManager.VERIFICATION_ALLOW, 1633 state.getInstallArgs().getUser()); 1634 try { 1635 ret = args.copyApk(mContainerService, true); 1636 } catch (RemoteException e) { 1637 Slog.e(TAG, "Could not contact the ContainerService"); 1638 } 1639 } else { 1640 broadcastPackageVerified(verificationId, originUri, 1641 PackageManager.VERIFICATION_REJECT, 1642 state.getInstallArgs().getUser()); 1643 } 1644 1645 Trace.asyncTraceEnd( 1646 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1647 1648 processPendingInstall(args, ret); 1649 mHandler.sendEmptyMessage(MCS_UNBIND); 1650 } 1651 break; 1652 } 1653 case PACKAGE_VERIFIED: { 1654 final int verificationId = msg.arg1; 1655 1656 final PackageVerificationState state = mPendingVerification.get(verificationId); 1657 if (state == null) { 1658 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1659 break; 1660 } 1661 1662 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1663 1664 state.setVerifierResponse(response.callerUid, response.code); 1665 1666 if (state.isVerificationComplete()) { 1667 mPendingVerification.remove(verificationId); 1668 1669 final InstallArgs args = state.getInstallArgs(); 1670 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1671 1672 int ret; 1673 if (state.isInstallAllowed()) { 1674 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1675 broadcastPackageVerified(verificationId, originUri, 1676 response.code, state.getInstallArgs().getUser()); 1677 try { 1678 ret = args.copyApk(mContainerService, true); 1679 } catch (RemoteException e) { 1680 Slog.e(TAG, "Could not contact the ContainerService"); 1681 } 1682 } else { 1683 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1684 } 1685 1686 Trace.asyncTraceEnd( 1687 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1688 1689 processPendingInstall(args, ret); 1690 mHandler.sendEmptyMessage(MCS_UNBIND); 1691 } 1692 1693 break; 1694 } 1695 case START_INTENT_FILTER_VERIFICATIONS: { 1696 IFVerificationParams params = (IFVerificationParams) msg.obj; 1697 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1698 params.replacing, params.pkg); 1699 break; 1700 } 1701 case INTENT_FILTER_VERIFIED: { 1702 final int verificationId = msg.arg1; 1703 1704 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1705 verificationId); 1706 if (state == null) { 1707 Slog.w(TAG, "Invalid IntentFilter verification token " 1708 + verificationId + " received"); 1709 break; 1710 } 1711 1712 final int userId = state.getUserId(); 1713 1714 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1715 "Processing IntentFilter verification with token:" 1716 + verificationId + " and userId:" + userId); 1717 1718 final IntentFilterVerificationResponse response = 1719 (IntentFilterVerificationResponse) msg.obj; 1720 1721 state.setVerifierResponse(response.callerUid, response.code); 1722 1723 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1724 "IntentFilter verification with token:" + verificationId 1725 + " and userId:" + userId 1726 + " is settings verifier response with response code:" 1727 + response.code); 1728 1729 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1730 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1731 + response.getFailedDomainsString()); 1732 } 1733 1734 if (state.isVerificationComplete()) { 1735 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1736 } else { 1737 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1738 "IntentFilter verification with token:" + verificationId 1739 + " was not said to be complete"); 1740 } 1741 1742 break; 1743 } 1744 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1745 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1746 mInstantAppResolverConnection, 1747 (InstantAppRequest) msg.obj, 1748 mInstantAppInstallerActivity, 1749 mHandler); 1750 } 1751 } 1752 } 1753 } 1754 1755 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1756 boolean killApp, String[] grantedPermissions, 1757 boolean launchedForRestore, String installerPackage, 1758 IPackageInstallObserver2 installObserver) { 1759 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1760 // Send the removed broadcasts 1761 if (res.removedInfo != null) { 1762 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1763 } 1764 1765 // Now that we successfully installed the package, grant runtime 1766 // permissions if requested before broadcasting the install. Also 1767 // for legacy apps in permission review mode we clear the permission 1768 // review flag which is used to emulate runtime permissions for 1769 // legacy apps. 1770 if (grantPermissions) { 1771 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1772 } 1773 1774 final boolean update = res.removedInfo != null 1775 && res.removedInfo.removedPackage != null; 1776 1777 // If this is the first time we have child packages for a disabled privileged 1778 // app that had no children, we grant requested runtime permissions to the new 1779 // children if the parent on the system image had them already granted. 1780 if (res.pkg.parentPackage != null) { 1781 synchronized (mPackages) { 1782 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1783 } 1784 } 1785 1786 synchronized (mPackages) { 1787 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1788 } 1789 1790 final String packageName = res.pkg.applicationInfo.packageName; 1791 1792 // Determine the set of users who are adding this package for 1793 // the first time vs. those who are seeing an update. 1794 int[] firstUsers = EMPTY_INT_ARRAY; 1795 int[] updateUsers = EMPTY_INT_ARRAY; 1796 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1797 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1798 for (int newUser : res.newUsers) { 1799 if (ps.getInstantApp(newUser)) { 1800 continue; 1801 } 1802 if (allNewUsers) { 1803 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1804 continue; 1805 } 1806 boolean isNew = true; 1807 for (int origUser : res.origUsers) { 1808 if (origUser == newUser) { 1809 isNew = false; 1810 break; 1811 } 1812 } 1813 if (isNew) { 1814 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1815 } else { 1816 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1817 } 1818 } 1819 1820 // Send installed broadcasts if the package is not a static shared lib. 1821 if (res.pkg.staticSharedLibName == null) { 1822 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1823 1824 // Send added for users that see the package for the first time 1825 // sendPackageAddedForNewUsers also deals with system apps 1826 int appId = UserHandle.getAppId(res.uid); 1827 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1828 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1829 1830 // Send added for users that don't see the package for the first time 1831 Bundle extras = new Bundle(1); 1832 extras.putInt(Intent.EXTRA_UID, res.uid); 1833 if (update) { 1834 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1835 } 1836 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1837 extras, 0 /*flags*/, null /*targetPackage*/, 1838 null /*finishedReceiver*/, updateUsers); 1839 1840 // Send replaced for users that don't see the package for the first time 1841 if (update) { 1842 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1843 packageName, extras, 0 /*flags*/, 1844 null /*targetPackage*/, null /*finishedReceiver*/, 1845 updateUsers); 1846 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1847 null /*package*/, null /*extras*/, 0 /*flags*/, 1848 packageName /*targetPackage*/, 1849 null /*finishedReceiver*/, updateUsers); 1850 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1851 // First-install and we did a restore, so we're responsible for the 1852 // first-launch broadcast. 1853 if (DEBUG_BACKUP) { 1854 Slog.i(TAG, "Post-restore of " + packageName 1855 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1856 } 1857 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1858 } 1859 1860 // Send broadcast package appeared if forward locked/external for all users 1861 // treat asec-hosted packages like removable media on upgrade 1862 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1863 if (DEBUG_INSTALL) { 1864 Slog.i(TAG, "upgrading pkg " + res.pkg 1865 + " is ASEC-hosted -> AVAILABLE"); 1866 } 1867 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1868 ArrayList<String> pkgList = new ArrayList<>(1); 1869 pkgList.add(packageName); 1870 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1871 } 1872 } 1873 1874 // Work that needs to happen on first install within each user 1875 if (firstUsers != null && firstUsers.length > 0) { 1876 synchronized (mPackages) { 1877 for (int userId : firstUsers) { 1878 // If this app is a browser and it's newly-installed for some 1879 // users, clear any default-browser state in those users. The 1880 // app's nature doesn't depend on the user, so we can just check 1881 // its browser nature in any user and generalize. 1882 if (packageIsBrowser(packageName, userId)) { 1883 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1884 } 1885 1886 // We may also need to apply pending (restored) runtime 1887 // permission grants within these users. 1888 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1889 } 1890 } 1891 } 1892 1893 // Log current value of "unknown sources" setting 1894 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1895 getUnknownSourcesSettings()); 1896 1897 // Force a gc to clear up things 1898 Runtime.getRuntime().gc(); 1899 1900 // Remove the replaced package's older resources safely now 1901 // We delete after a gc for applications on sdcard. 1902 if (res.removedInfo != null && res.removedInfo.args != null) { 1903 synchronized (mInstallLock) { 1904 res.removedInfo.args.doPostDeleteLI(true); 1905 } 1906 } 1907 1908 // Notify DexManager that the package was installed for new users. 1909 // The updated users should already be indexed and the package code paths 1910 // should not change. 1911 // Don't notify the manager for ephemeral apps as they are not expected to 1912 // survive long enough to benefit of background optimizations. 1913 for (int userId : firstUsers) { 1914 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1915 mDexManager.notifyPackageInstalled(info, userId); 1916 } 1917 } 1918 1919 // If someone is watching installs - notify them 1920 if (installObserver != null) { 1921 try { 1922 Bundle extras = extrasForInstallResult(res); 1923 installObserver.onPackageInstalled(res.name, res.returnCode, 1924 res.returnMsg, extras); 1925 } catch (RemoteException e) { 1926 Slog.i(TAG, "Observer no longer exists."); 1927 } 1928 } 1929 } 1930 1931 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1932 PackageParser.Package pkg) { 1933 if (pkg.parentPackage == null) { 1934 return; 1935 } 1936 if (pkg.requestedPermissions == null) { 1937 return; 1938 } 1939 final PackageSetting disabledSysParentPs = mSettings 1940 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1941 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1942 || !disabledSysParentPs.isPrivileged() 1943 || (disabledSysParentPs.childPackageNames != null 1944 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1945 return; 1946 } 1947 final int[] allUserIds = sUserManager.getUserIds(); 1948 final int permCount = pkg.requestedPermissions.size(); 1949 for (int i = 0; i < permCount; i++) { 1950 String permission = pkg.requestedPermissions.get(i); 1951 BasePermission bp = mSettings.mPermissions.get(permission); 1952 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1953 continue; 1954 } 1955 for (int userId : allUserIds) { 1956 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1957 permission, userId)) { 1958 grantRuntimePermission(pkg.packageName, permission, userId); 1959 } 1960 } 1961 } 1962 } 1963 1964 private StorageEventListener mStorageListener = new StorageEventListener() { 1965 @Override 1966 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1967 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1968 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1969 final String volumeUuid = vol.getFsUuid(); 1970 1971 // Clean up any users or apps that were removed or recreated 1972 // while this volume was missing 1973 sUserManager.reconcileUsers(volumeUuid); 1974 reconcileApps(volumeUuid); 1975 1976 // Clean up any install sessions that expired or were 1977 // cancelled while this volume was missing 1978 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1979 1980 loadPrivatePackages(vol); 1981 1982 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1983 unloadPrivatePackages(vol); 1984 } 1985 } 1986 1987 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1988 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1989 updateExternalMediaStatus(true, false); 1990 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1991 updateExternalMediaStatus(false, false); 1992 } 1993 } 1994 } 1995 1996 @Override 1997 public void onVolumeForgotten(String fsUuid) { 1998 if (TextUtils.isEmpty(fsUuid)) { 1999 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2000 return; 2001 } 2002 2003 // Remove any apps installed on the forgotten volume 2004 synchronized (mPackages) { 2005 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2006 for (PackageSetting ps : packages) { 2007 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2008 deletePackageVersioned(new VersionedPackage(ps.name, 2009 PackageManager.VERSION_CODE_HIGHEST), 2010 new LegacyPackageDeleteObserver(null).getBinder(), 2011 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2012 // Try very hard to release any references to this package 2013 // so we don't risk the system server being killed due to 2014 // open FDs 2015 AttributeCache.instance().removePackage(ps.name); 2016 } 2017 2018 mSettings.onVolumeForgotten(fsUuid); 2019 mSettings.writeLPr(); 2020 } 2021 } 2022 }; 2023 2024 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2025 String[] grantedPermissions) { 2026 for (int userId : userIds) { 2027 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2028 } 2029 } 2030 2031 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2032 String[] grantedPermissions) { 2033 SettingBase sb = (SettingBase) pkg.mExtras; 2034 if (sb == null) { 2035 return; 2036 } 2037 2038 PermissionsState permissionsState = sb.getPermissionsState(); 2039 2040 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2041 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2042 2043 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2044 >= Build.VERSION_CODES.M; 2045 2046 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2047 2048 for (String permission : pkg.requestedPermissions) { 2049 final BasePermission bp; 2050 synchronized (mPackages) { 2051 bp = mSettings.mPermissions.get(permission); 2052 } 2053 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2054 && (!instantApp || bp.isInstant()) 2055 && (grantedPermissions == null 2056 || ArrayUtils.contains(grantedPermissions, permission))) { 2057 final int flags = permissionsState.getPermissionFlags(permission, userId); 2058 if (supportsRuntimePermissions) { 2059 // Installer cannot change immutable permissions. 2060 if ((flags & immutableFlags) == 0) { 2061 grantRuntimePermission(pkg.packageName, permission, userId); 2062 } 2063 } else if (mPermissionReviewRequired) { 2064 // In permission review mode we clear the review flag when we 2065 // are asked to install the app with all permissions granted. 2066 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2067 updatePermissionFlags(permission, pkg.packageName, 2068 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2069 } 2070 } 2071 } 2072 } 2073 } 2074 2075 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2076 Bundle extras = null; 2077 switch (res.returnCode) { 2078 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2079 extras = new Bundle(); 2080 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2081 res.origPermission); 2082 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2083 res.origPackage); 2084 break; 2085 } 2086 case PackageManager.INSTALL_SUCCEEDED: { 2087 extras = new Bundle(); 2088 extras.putBoolean(Intent.EXTRA_REPLACING, 2089 res.removedInfo != null && res.removedInfo.removedPackage != null); 2090 break; 2091 } 2092 } 2093 return extras; 2094 } 2095 2096 void scheduleWriteSettingsLocked() { 2097 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2098 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2099 } 2100 } 2101 2102 void scheduleWritePackageListLocked(int userId) { 2103 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2104 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2105 msg.arg1 = userId; 2106 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2107 } 2108 } 2109 2110 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2111 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2112 scheduleWritePackageRestrictionsLocked(userId); 2113 } 2114 2115 void scheduleWritePackageRestrictionsLocked(int userId) { 2116 final int[] userIds = (userId == UserHandle.USER_ALL) 2117 ? sUserManager.getUserIds() : new int[]{userId}; 2118 for (int nextUserId : userIds) { 2119 if (!sUserManager.exists(nextUserId)) return; 2120 mDirtyUsers.add(nextUserId); 2121 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2122 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2123 } 2124 } 2125 } 2126 2127 public static PackageManagerService main(Context context, Installer installer, 2128 boolean factoryTest, boolean onlyCore) { 2129 // Self-check for initial settings. 2130 PackageManagerServiceCompilerMapping.checkProperties(); 2131 2132 PackageManagerService m = new PackageManagerService(context, installer, 2133 factoryTest, onlyCore); 2134 m.enableSystemUserPackages(); 2135 ServiceManager.addService("package", m); 2136 return m; 2137 } 2138 2139 private void enableSystemUserPackages() { 2140 if (!UserManager.isSplitSystemUser()) { 2141 return; 2142 } 2143 // For system user, enable apps based on the following conditions: 2144 // - app is whitelisted or belong to one of these groups: 2145 // -- system app which has no launcher icons 2146 // -- system app which has INTERACT_ACROSS_USERS permission 2147 // -- system IME app 2148 // - app is not in the blacklist 2149 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2150 Set<String> enableApps = new ArraySet<>(); 2151 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2152 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2153 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2154 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2155 enableApps.addAll(wlApps); 2156 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2157 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2158 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2159 enableApps.removeAll(blApps); 2160 Log.i(TAG, "Applications installed for system user: " + enableApps); 2161 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2162 UserHandle.SYSTEM); 2163 final int allAppsSize = allAps.size(); 2164 synchronized (mPackages) { 2165 for (int i = 0; i < allAppsSize; i++) { 2166 String pName = allAps.get(i); 2167 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2168 // Should not happen, but we shouldn't be failing if it does 2169 if (pkgSetting == null) { 2170 continue; 2171 } 2172 boolean install = enableApps.contains(pName); 2173 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2174 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2175 + " for system user"); 2176 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2177 } 2178 } 2179 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2180 } 2181 } 2182 2183 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2184 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2185 Context.DISPLAY_SERVICE); 2186 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2187 } 2188 2189 /** 2190 * Requests that files preopted on a secondary system partition be copied to the data partition 2191 * if possible. Note that the actual copying of the files is accomplished by init for security 2192 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2193 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2194 */ 2195 private static void requestCopyPreoptedFiles() { 2196 final int WAIT_TIME_MS = 100; 2197 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2198 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2199 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2200 // We will wait for up to 100 seconds. 2201 final long timeStart = SystemClock.uptimeMillis(); 2202 final long timeEnd = timeStart + 100 * 1000; 2203 long timeNow = timeStart; 2204 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2205 try { 2206 Thread.sleep(WAIT_TIME_MS); 2207 } catch (InterruptedException e) { 2208 // Do nothing 2209 } 2210 timeNow = SystemClock.uptimeMillis(); 2211 if (timeNow > timeEnd) { 2212 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2213 Slog.wtf(TAG, "cppreopt did not finish!"); 2214 break; 2215 } 2216 } 2217 2218 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2219 } 2220 } 2221 2222 public PackageManagerService(Context context, Installer installer, 2223 boolean factoryTest, boolean onlyCore) { 2224 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2225 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2226 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2227 SystemClock.uptimeMillis()); 2228 2229 if (mSdkVersion <= 0) { 2230 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2231 } 2232 2233 mContext = context; 2234 2235 mPermissionReviewRequired = context.getResources().getBoolean( 2236 R.bool.config_permissionReviewRequired); 2237 2238 mFactoryTest = factoryTest; 2239 mOnlyCore = onlyCore; 2240 mMetrics = new DisplayMetrics(); 2241 mSettings = new Settings(mPackages); 2242 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2245 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2246 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2247 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2248 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2249 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2250 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2251 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2252 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2253 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2254 2255 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2256 if (separateProcesses != null && separateProcesses.length() > 0) { 2257 if ("*".equals(separateProcesses)) { 2258 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2259 mSeparateProcesses = null; 2260 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2261 } else { 2262 mDefParseFlags = 0; 2263 mSeparateProcesses = separateProcesses.split(","); 2264 Slog.w(TAG, "Running with debug.separate_processes: " 2265 + separateProcesses); 2266 } 2267 } else { 2268 mDefParseFlags = 0; 2269 mSeparateProcesses = null; 2270 } 2271 2272 mInstaller = installer; 2273 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2274 "*dexopt*"); 2275 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2276 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2277 2278 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2279 FgThread.get().getLooper()); 2280 2281 getDefaultDisplayMetrics(context, mMetrics); 2282 2283 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2284 SystemConfig systemConfig = SystemConfig.getInstance(); 2285 mGlobalGids = systemConfig.getGlobalGids(); 2286 mSystemPermissions = systemConfig.getSystemPermissions(); 2287 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2288 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2289 2290 mProtectedPackages = new ProtectedPackages(mContext); 2291 2292 synchronized (mInstallLock) { 2293 // writer 2294 synchronized (mPackages) { 2295 mHandlerThread = new ServiceThread(TAG, 2296 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2297 mHandlerThread.start(); 2298 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2299 mProcessLoggingHandler = new ProcessLoggingHandler(); 2300 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2301 2302 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2303 mInstantAppRegistry = new InstantAppRegistry(this); 2304 2305 File dataDir = Environment.getDataDirectory(); 2306 mAppInstallDir = new File(dataDir, "app"); 2307 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2308 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2309 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2310 sUserManager = new UserManagerService(context, this, 2311 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2312 2313 // Propagate permission configuration in to package manager. 2314 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2315 = systemConfig.getPermissions(); 2316 for (int i=0; i<permConfig.size(); i++) { 2317 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2318 BasePermission bp = mSettings.mPermissions.get(perm.name); 2319 if (bp == null) { 2320 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2321 mSettings.mPermissions.put(perm.name, bp); 2322 } 2323 if (perm.gids != null) { 2324 bp.setGids(perm.gids, perm.perUser); 2325 } 2326 } 2327 2328 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2329 final int builtInLibCount = libConfig.size(); 2330 for (int i = 0; i < builtInLibCount; i++) { 2331 String name = libConfig.keyAt(i); 2332 String path = libConfig.valueAt(i); 2333 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2334 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2335 } 2336 2337 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2338 2339 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2340 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2341 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2342 2343 // Clean up orphaned packages for which the code path doesn't exist 2344 // and they are an update to a system app - caused by bug/32321269 2345 final int packageSettingCount = mSettings.mPackages.size(); 2346 for (int i = packageSettingCount - 1; i >= 0; i--) { 2347 PackageSetting ps = mSettings.mPackages.valueAt(i); 2348 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2349 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2350 mSettings.mPackages.removeAt(i); 2351 mSettings.enableSystemPackageLPw(ps.name); 2352 } 2353 } 2354 2355 if (mFirstBoot) { 2356 requestCopyPreoptedFiles(); 2357 } 2358 2359 String customResolverActivity = Resources.getSystem().getString( 2360 R.string.config_customResolverActivity); 2361 if (TextUtils.isEmpty(customResolverActivity)) { 2362 customResolverActivity = null; 2363 } else { 2364 mCustomResolverComponentName = ComponentName.unflattenFromString( 2365 customResolverActivity); 2366 } 2367 2368 long startTime = SystemClock.uptimeMillis(); 2369 2370 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2371 startTime); 2372 2373 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2374 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2375 2376 if (bootClassPath == null) { 2377 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2378 } 2379 2380 if (systemServerClassPath == null) { 2381 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2382 } 2383 2384 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2385 2386 final VersionInfo ver = mSettings.getInternalVersion(); 2387 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2388 if (mIsUpgrade) { 2389 logCriticalInfo(Log.INFO, 2390 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2391 } 2392 2393 // when upgrading from pre-M, promote system app permissions from install to runtime 2394 mPromoteSystemApps = 2395 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2396 2397 // When upgrading from pre-N, we need to handle package extraction like first boot, 2398 // as there is no profiling data available. 2399 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2400 2401 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2402 2403 // save off the names of pre-existing system packages prior to scanning; we don't 2404 // want to automatically grant runtime permissions for new system apps 2405 if (mPromoteSystemApps) { 2406 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2407 while (pkgSettingIter.hasNext()) { 2408 PackageSetting ps = pkgSettingIter.next(); 2409 if (isSystemApp(ps)) { 2410 mExistingSystemPackages.add(ps.name); 2411 } 2412 } 2413 } 2414 2415 mCacheDir = preparePackageParserCache(mIsUpgrade); 2416 2417 // Set flag to monitor and not change apk file paths when 2418 // scanning install directories. 2419 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2420 2421 if (mIsUpgrade || mFirstBoot) { 2422 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2423 } 2424 2425 // Collect vendor overlay packages. (Do this before scanning any apps.) 2426 // For security and version matching reason, only consider 2427 // overlay packages if they reside in the right directory. 2428 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2429 | PackageParser.PARSE_IS_SYSTEM 2430 | PackageParser.PARSE_IS_SYSTEM_DIR 2431 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2432 2433 // Find base frameworks (resource packages without code). 2434 scanDirTracedLI(frameworkDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR 2437 | PackageParser.PARSE_IS_PRIVILEGED, 2438 scanFlags | SCAN_NO_DEX, 0); 2439 2440 // Collected privileged system packages. 2441 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2442 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR 2445 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2446 2447 // Collect ordinary system packages. 2448 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2449 scanDirTracedLI(systemAppDir, mDefParseFlags 2450 | PackageParser.PARSE_IS_SYSTEM 2451 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2452 2453 // Collect all vendor packages. 2454 File vendorAppDir = new File("/vendor/app"); 2455 try { 2456 vendorAppDir = vendorAppDir.getCanonicalFile(); 2457 } catch (IOException e) { 2458 // failed to look up canonical path, continue with original one 2459 } 2460 scanDirTracedLI(vendorAppDir, mDefParseFlags 2461 | PackageParser.PARSE_IS_SYSTEM 2462 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2463 2464 // Collect all OEM packages. 2465 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2466 scanDirTracedLI(oemAppDir, mDefParseFlags 2467 | PackageParser.PARSE_IS_SYSTEM 2468 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2469 2470 // Prune any system packages that no longer exist. 2471 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2472 if (!mOnlyCore) { 2473 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2474 while (psit.hasNext()) { 2475 PackageSetting ps = psit.next(); 2476 2477 /* 2478 * If this is not a system app, it can't be a 2479 * disable system app. 2480 */ 2481 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2482 continue; 2483 } 2484 2485 /* 2486 * If the package is scanned, it's not erased. 2487 */ 2488 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2489 if (scannedPkg != null) { 2490 /* 2491 * If the system app is both scanned and in the 2492 * disabled packages list, then it must have been 2493 * added via OTA. Remove it from the currently 2494 * scanned package so the previously user-installed 2495 * application can be scanned. 2496 */ 2497 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2498 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2499 + ps.name + "; removing system app. Last known codePath=" 2500 + ps.codePathString + ", installStatus=" + ps.installStatus 2501 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2502 + scannedPkg.mVersionCode); 2503 removePackageLI(scannedPkg, true); 2504 mExpectingBetter.put(ps.name, ps.codePath); 2505 } 2506 2507 continue; 2508 } 2509 2510 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2511 psit.remove(); 2512 logCriticalInfo(Log.WARN, "System package " + ps.name 2513 + " no longer exists; it's data will be wiped"); 2514 // Actual deletion of code and data will be handled by later 2515 // reconciliation step 2516 } else { 2517 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2518 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2519 possiblyDeletedUpdatedSystemApps.add(ps.name); 2520 } 2521 } 2522 } 2523 } 2524 2525 //look for any incomplete package installations 2526 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2527 for (int i = 0; i < deletePkgsList.size(); i++) { 2528 // Actual deletion of code and data will be handled by later 2529 // reconciliation step 2530 final String packageName = deletePkgsList.get(i).name; 2531 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2532 synchronized (mPackages) { 2533 mSettings.removePackageLPw(packageName); 2534 } 2535 } 2536 2537 //delete tmp files 2538 deleteTempPackageFiles(); 2539 2540 // Remove any shared userIDs that have no associated packages 2541 mSettings.pruneSharedUsersLPw(); 2542 2543 if (!mOnlyCore) { 2544 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2545 SystemClock.uptimeMillis()); 2546 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2547 2548 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2549 | PackageParser.PARSE_FORWARD_LOCK, 2550 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2551 2552 /** 2553 * Remove disable package settings for any updated system 2554 * apps that were removed via an OTA. If they're not a 2555 * previously-updated app, remove them completely. 2556 * Otherwise, just revoke their system-level permissions. 2557 */ 2558 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2559 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2560 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2561 2562 String msg; 2563 if (deletedPkg == null) { 2564 msg = "Updated system package " + deletedAppName 2565 + " no longer exists; it's data will be wiped"; 2566 // Actual deletion of code and data will be handled by later 2567 // reconciliation step 2568 } else { 2569 msg = "Updated system app + " + deletedAppName 2570 + " no longer present; removing system privileges for " 2571 + deletedAppName; 2572 2573 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2574 2575 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2576 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2577 } 2578 logCriticalInfo(Log.WARN, msg); 2579 } 2580 2581 /** 2582 * Make sure all system apps that we expected to appear on 2583 * the userdata partition actually showed up. If they never 2584 * appeared, crawl back and revive the system version. 2585 */ 2586 for (int i = 0; i < mExpectingBetter.size(); i++) { 2587 final String packageName = mExpectingBetter.keyAt(i); 2588 if (!mPackages.containsKey(packageName)) { 2589 final File scanFile = mExpectingBetter.valueAt(i); 2590 2591 logCriticalInfo(Log.WARN, "Expected better " + packageName 2592 + " but never showed up; reverting to system"); 2593 2594 int reparseFlags = mDefParseFlags; 2595 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2596 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2597 | PackageParser.PARSE_IS_SYSTEM_DIR 2598 | PackageParser.PARSE_IS_PRIVILEGED; 2599 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2600 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2601 | PackageParser.PARSE_IS_SYSTEM_DIR; 2602 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2603 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2604 | PackageParser.PARSE_IS_SYSTEM_DIR; 2605 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2606 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2607 | PackageParser.PARSE_IS_SYSTEM_DIR; 2608 } else { 2609 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2610 continue; 2611 } 2612 2613 mSettings.enableSystemPackageLPw(packageName); 2614 2615 try { 2616 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2617 } catch (PackageManagerException e) { 2618 Slog.e(TAG, "Failed to parse original system package: " 2619 + e.getMessage()); 2620 } 2621 } 2622 } 2623 } 2624 mExpectingBetter.clear(); 2625 2626 // Resolve the storage manager. 2627 mStorageManagerPackage = getStorageManagerPackageName(); 2628 2629 // Resolve protected action filters. Only the setup wizard is allowed to 2630 // have a high priority filter for these actions. 2631 mSetupWizardPackage = getSetupWizardPackageName(); 2632 if (mProtectedFilters.size() > 0) { 2633 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2634 Slog.i(TAG, "No setup wizard;" 2635 + " All protected intents capped to priority 0"); 2636 } 2637 for (ActivityIntentInfo filter : mProtectedFilters) { 2638 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2639 if (DEBUG_FILTERS) { 2640 Slog.i(TAG, "Found setup wizard;" 2641 + " allow priority " + filter.getPriority() + ";" 2642 + " package: " + filter.activity.info.packageName 2643 + " activity: " + filter.activity.className 2644 + " priority: " + filter.getPriority()); 2645 } 2646 // skip setup wizard; allow it to keep the high priority filter 2647 continue; 2648 } 2649 Slog.w(TAG, "Protected action; cap priority to 0;" 2650 + " package: " + filter.activity.info.packageName 2651 + " activity: " + filter.activity.className 2652 + " origPrio: " + filter.getPriority()); 2653 filter.setPriority(0); 2654 } 2655 } 2656 mDeferProtectedFilters = false; 2657 mProtectedFilters.clear(); 2658 2659 // Now that we know all of the shared libraries, update all clients to have 2660 // the correct library paths. 2661 updateAllSharedLibrariesLPw(null); 2662 2663 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2664 // NOTE: We ignore potential failures here during a system scan (like 2665 // the rest of the commands above) because there's precious little we 2666 // can do about it. A settings error is reported, though. 2667 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2668 } 2669 2670 // Now that we know all the packages we are keeping, 2671 // read and update their last usage times. 2672 mPackageUsage.read(mPackages); 2673 mCompilerStats.read(); 2674 2675 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2676 SystemClock.uptimeMillis()); 2677 Slog.i(TAG, "Time to scan packages: " 2678 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2679 + " seconds"); 2680 2681 // If the platform SDK has changed since the last time we booted, 2682 // we need to re-grant app permission to catch any new ones that 2683 // appear. This is really a hack, and means that apps can in some 2684 // cases get permissions that the user didn't initially explicitly 2685 // allow... it would be nice to have some better way to handle 2686 // this situation. 2687 int updateFlags = UPDATE_PERMISSIONS_ALL; 2688 if (ver.sdkVersion != mSdkVersion) { 2689 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2690 + mSdkVersion + "; regranting permissions for internal storage"); 2691 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2692 } 2693 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2694 ver.sdkVersion = mSdkVersion; 2695 2696 // If this is the first boot or an update from pre-M, and it is a normal 2697 // boot, then we need to initialize the default preferred apps across 2698 // all defined users. 2699 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2700 for (UserInfo user : sUserManager.getUsers(true)) { 2701 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2702 applyFactoryDefaultBrowserLPw(user.id); 2703 primeDomainVerificationsLPw(user.id); 2704 } 2705 } 2706 2707 // Prepare storage for system user really early during boot, 2708 // since core system apps like SettingsProvider and SystemUI 2709 // can't wait for user to start 2710 final int storageFlags; 2711 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2712 storageFlags = StorageManager.FLAG_STORAGE_DE; 2713 } else { 2714 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2715 } 2716 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2717 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2718 true /* onlyCoreApps */); 2719 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2720 if (deferPackages == null || deferPackages.isEmpty()) { 2721 return; 2722 } 2723 int count = 0; 2724 for (String pkgName : deferPackages) { 2725 PackageParser.Package pkg = null; 2726 synchronized (mPackages) { 2727 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2728 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2729 pkg = ps.pkg; 2730 } 2731 } 2732 if (pkg != null) { 2733 synchronized (mInstallLock) { 2734 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2735 true /* maybeMigrateAppData */); 2736 } 2737 count++; 2738 } 2739 } 2740 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2741 }, "prepareAppData"); 2742 2743 // If this is first boot after an OTA, and a normal boot, then 2744 // we need to clear code cache directories. 2745 // Note that we do *not* clear the application profiles. These remain valid 2746 // across OTAs and are used to drive profile verification (post OTA) and 2747 // profile compilation (without waiting to collect a fresh set of profiles). 2748 if (mIsUpgrade && !onlyCore) { 2749 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2750 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2751 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2752 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2753 // No apps are running this early, so no need to freeze 2754 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2755 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2756 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2757 } 2758 } 2759 ver.fingerprint = Build.FINGERPRINT; 2760 } 2761 2762 checkDefaultBrowser(); 2763 2764 // clear only after permissions and other defaults have been updated 2765 mExistingSystemPackages.clear(); 2766 mPromoteSystemApps = false; 2767 2768 // All the changes are done during package scanning. 2769 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2770 2771 // can downgrade to reader 2772 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2773 mSettings.writeLPr(); 2774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2775 2776 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2777 SystemClock.uptimeMillis()); 2778 2779 if (!mOnlyCore) { 2780 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2781 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2782 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2783 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2784 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2785 mIntentFilterVerifierComponent); 2786 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2787 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2788 SharedLibraryInfo.VERSION_UNDEFINED); 2789 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2790 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2791 SharedLibraryInfo.VERSION_UNDEFINED); 2792 } else { 2793 mRequiredVerifierPackage = null; 2794 mRequiredInstallerPackage = null; 2795 mRequiredUninstallerPackage = null; 2796 mIntentFilterVerifierComponent = null; 2797 mIntentFilterVerifier = null; 2798 mServicesSystemSharedLibraryPackageName = null; 2799 mSharedSystemSharedLibraryPackageName = null; 2800 } 2801 2802 mInstallerService = new PackageInstallerService(context, this); 2803 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2804 if (ephemeralResolverComponent != null) { 2805 if (DEBUG_EPHEMERAL) { 2806 Slog.d(TAG, "Set ephemeral resolver: " + ephemeralResolverComponent); 2807 } 2808 mInstantAppResolverConnection = 2809 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2810 } else { 2811 mInstantAppResolverConnection = null; 2812 } 2813 updateInstantAppInstallerLocked(); 2814 mInstantAppResolverSettingsComponent = getEphemeralResolverSettingsLPr(); 2815 2816 // Read and update the usage of dex files. 2817 // Do this at the end of PM init so that all the packages have their 2818 // data directory reconciled. 2819 // At this point we know the code paths of the packages, so we can validate 2820 // the disk file and build the internal cache. 2821 // The usage file is expected to be small so loading and verifying it 2822 // should take a fairly small time compare to the other activities (e.g. package 2823 // scanning). 2824 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2825 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2826 for (int userId : currentUserIds) { 2827 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2828 } 2829 mDexManager.load(userPackages); 2830 } // synchronized (mPackages) 2831 } // synchronized (mInstallLock) 2832 2833 // Now after opening every single application zip, make sure they 2834 // are all flushed. Not really needed, but keeps things nice and 2835 // tidy. 2836 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2837 Runtime.getRuntime().gc(); 2838 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2839 2840 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2841 FallbackCategoryProvider.loadFallbacks(); 2842 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2843 2844 // The initial scanning above does many calls into installd while 2845 // holding the mPackages lock, but we're mostly interested in yelling 2846 // once we have a booted system. 2847 mInstaller.setWarnIfHeld(mPackages); 2848 2849 // Expose private service for system components to use. 2850 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2851 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2852 } 2853 2854 private void updateInstantAppInstallerLocked() { 2855 final ComponentName oldInstantAppInstallerComponent = mInstantAppInstallerComponent; 2856 final ActivityInfo newInstantAppInstaller = getEphemeralInstallerLPr(); 2857 ComponentName newInstantAppInstallerComponent = newInstantAppInstaller == null 2858 ? null : newInstantAppInstaller.getComponentName(); 2859 2860 if (newInstantAppInstallerComponent != null 2861 && !newInstantAppInstallerComponent.equals(oldInstantAppInstallerComponent)) { 2862 if (DEBUG_EPHEMERAL) { 2863 Slog.d(TAG, "Set ephemeral installer: " + newInstantAppInstallerComponent); 2864 } 2865 setUpInstantAppInstallerActivityLP(newInstantAppInstaller); 2866 } else if (DEBUG_EPHEMERAL && newInstantAppInstallerComponent == null) { 2867 Slog.d(TAG, "Unset ephemeral installer; none available"); 2868 } 2869 mInstantAppInstallerComponent = newInstantAppInstallerComponent; 2870 } 2871 2872 private static File preparePackageParserCache(boolean isUpgrade) { 2873 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2874 return null; 2875 } 2876 2877 // Disable package parsing on eng builds to allow for faster incremental development. 2878 if ("eng".equals(Build.TYPE)) { 2879 return null; 2880 } 2881 2882 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2883 Slog.i(TAG, "Disabling package parser cache due to system property."); 2884 return null; 2885 } 2886 2887 // The base directory for the package parser cache lives under /data/system/. 2888 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2889 "package_cache"); 2890 if (cacheBaseDir == null) { 2891 return null; 2892 } 2893 2894 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2895 // This also serves to "GC" unused entries when the package cache version changes (which 2896 // can only happen during upgrades). 2897 if (isUpgrade) { 2898 FileUtils.deleteContents(cacheBaseDir); 2899 } 2900 2901 2902 // Return the versioned package cache directory. This is something like 2903 // "/data/system/package_cache/1" 2904 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2905 2906 // The following is a workaround to aid development on non-numbered userdebug 2907 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2908 // the system partition is newer. 2909 // 2910 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2911 // that starts with "eng." to signify that this is an engineering build and not 2912 // destined for release. 2913 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2914 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2915 2916 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2917 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2918 // in general and should not be used for production changes. In this specific case, 2919 // we know that they will work. 2920 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2921 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2922 FileUtils.deleteContents(cacheBaseDir); 2923 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2924 } 2925 } 2926 2927 return cacheDir; 2928 } 2929 2930 @Override 2931 public boolean isFirstBoot() { 2932 return mFirstBoot; 2933 } 2934 2935 @Override 2936 public boolean isOnlyCoreApps() { 2937 return mOnlyCore; 2938 } 2939 2940 @Override 2941 public boolean isUpgrade() { 2942 return mIsUpgrade; 2943 } 2944 2945 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2946 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2947 2948 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2949 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2950 UserHandle.USER_SYSTEM); 2951 if (matches.size() == 1) { 2952 return matches.get(0).getComponentInfo().packageName; 2953 } else if (matches.size() == 0) { 2954 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2955 return null; 2956 } 2957 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2958 } 2959 2960 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2961 synchronized (mPackages) { 2962 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2963 if (libraryEntry == null) { 2964 throw new IllegalStateException("Missing required shared library:" + name); 2965 } 2966 return libraryEntry.apk; 2967 } 2968 } 2969 2970 private @NonNull String getRequiredInstallerLPr() { 2971 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2972 intent.addCategory(Intent.CATEGORY_DEFAULT); 2973 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2974 2975 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2976 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2977 UserHandle.USER_SYSTEM); 2978 if (matches.size() == 1) { 2979 ResolveInfo resolveInfo = matches.get(0); 2980 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2981 throw new RuntimeException("The installer must be a privileged app"); 2982 } 2983 return matches.get(0).getComponentInfo().packageName; 2984 } else { 2985 throw new RuntimeException("There must be exactly one installer; found " + matches); 2986 } 2987 } 2988 2989 private @NonNull String getRequiredUninstallerLPr() { 2990 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2991 intent.addCategory(Intent.CATEGORY_DEFAULT); 2992 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2993 2994 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2995 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2996 UserHandle.USER_SYSTEM); 2997 if (resolveInfo == null || 2998 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2999 throw new RuntimeException("There must be exactly one uninstaller; found " 3000 + resolveInfo); 3001 } 3002 return resolveInfo.getComponentInfo().packageName; 3003 } 3004 3005 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3006 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3007 3008 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3009 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3010 UserHandle.USER_SYSTEM); 3011 ResolveInfo best = null; 3012 final int N = matches.size(); 3013 for (int i = 0; i < N; i++) { 3014 final ResolveInfo cur = matches.get(i); 3015 final String packageName = cur.getComponentInfo().packageName; 3016 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3017 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3018 continue; 3019 } 3020 3021 if (best == null || cur.priority > best.priority) { 3022 best = cur; 3023 } 3024 } 3025 3026 if (best != null) { 3027 return best.getComponentInfo().getComponentName(); 3028 } else { 3029 throw new RuntimeException("There must be at least one intent filter verifier"); 3030 } 3031 } 3032 3033 private @Nullable ComponentName getEphemeralResolverLPr() { 3034 final String[] packageArray = 3035 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3036 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3037 if (DEBUG_EPHEMERAL) { 3038 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3039 } 3040 return null; 3041 } 3042 3043 final int callingUid = Binder.getCallingUid(); 3044 final int resolveFlags = 3045 MATCH_DIRECT_BOOT_AWARE 3046 | MATCH_DIRECT_BOOT_UNAWARE 3047 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3048 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3049 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3050 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3051 3052 final int N = resolvers.size(); 3053 if (N == 0) { 3054 if (DEBUG_EPHEMERAL) { 3055 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3056 } 3057 return null; 3058 } 3059 3060 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3061 for (int i = 0; i < N; i++) { 3062 final ResolveInfo info = resolvers.get(i); 3063 3064 if (info.serviceInfo == null) { 3065 continue; 3066 } 3067 3068 final String packageName = info.serviceInfo.packageName; 3069 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3070 if (DEBUG_EPHEMERAL) { 3071 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3072 + " pkg: " + packageName + ", info:" + info); 3073 } 3074 continue; 3075 } 3076 3077 if (DEBUG_EPHEMERAL) { 3078 Slog.v(TAG, "Ephemeral resolver found;" 3079 + " pkg: " + packageName + ", info:" + info); 3080 } 3081 return new ComponentName(packageName, info.serviceInfo.name); 3082 } 3083 if (DEBUG_EPHEMERAL) { 3084 Slog.v(TAG, "Ephemeral resolver NOT found"); 3085 } 3086 return null; 3087 } 3088 3089 private @Nullable ActivityInfo getEphemeralInstallerLPr() { 3090 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3091 intent.addCategory(Intent.CATEGORY_DEFAULT); 3092 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3093 3094 final int resolveFlags = 3095 MATCH_DIRECT_BOOT_AWARE 3096 | MATCH_DIRECT_BOOT_UNAWARE 3097 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3098 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3099 resolveFlags, UserHandle.USER_SYSTEM); 3100 Iterator<ResolveInfo> iter = matches.iterator(); 3101 while (iter.hasNext()) { 3102 final ResolveInfo rInfo = iter.next(); 3103 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3104 if (ps != null) { 3105 final PermissionsState permissionsState = ps.getPermissionsState(); 3106 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3107 continue; 3108 } 3109 } 3110 iter.remove(); 3111 } 3112 if (matches.size() == 0) { 3113 return null; 3114 } else if (matches.size() == 1) { 3115 return (ActivityInfo) matches.get(0).getComponentInfo(); 3116 } else { 3117 throw new RuntimeException( 3118 "There must be at most one ephemeral installer; found " + matches); 3119 } 3120 } 3121 3122 private @Nullable ComponentName getEphemeralResolverSettingsLPr() { 3123 final Intent intent = new Intent(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3124 intent.addCategory(Intent.CATEGORY_DEFAULT); 3125 final int resolveFlags = 3126 MATCH_DIRECT_BOOT_AWARE 3127 | MATCH_DIRECT_BOOT_UNAWARE 3128 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3129 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 3130 resolveFlags, UserHandle.USER_SYSTEM); 3131 Iterator<ResolveInfo> iter = matches.iterator(); 3132 while (iter.hasNext()) { 3133 final ResolveInfo rInfo = iter.next(); 3134 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3135 if (ps != null) { 3136 final PermissionsState permissionsState = ps.getPermissionsState(); 3137 if (permissionsState.hasPermission(Manifest.permission.ACCESS_INSTANT_APPS, 0)) { 3138 continue; 3139 } 3140 } 3141 iter.remove(); 3142 } 3143 if (matches.size() == 0) { 3144 return null; 3145 } else if (matches.size() == 1) { 3146 return matches.get(0).getComponentInfo().getComponentName(); 3147 } else { 3148 throw new RuntimeException( 3149 "There must be at most one ephemeral resolver settings; found " + matches); 3150 } 3151 } 3152 3153 private void primeDomainVerificationsLPw(int userId) { 3154 if (DEBUG_DOMAIN_VERIFICATION) { 3155 Slog.d(TAG, "Priming domain verifications in user " + userId); 3156 } 3157 3158 SystemConfig systemConfig = SystemConfig.getInstance(); 3159 ArraySet<String> packages = systemConfig.getLinkedApps(); 3160 3161 for (String packageName : packages) { 3162 PackageParser.Package pkg = mPackages.get(packageName); 3163 if (pkg != null) { 3164 if (!pkg.isSystemApp()) { 3165 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3166 continue; 3167 } 3168 3169 ArraySet<String> domains = null; 3170 for (PackageParser.Activity a : pkg.activities) { 3171 for (ActivityIntentInfo filter : a.intents) { 3172 if (hasValidDomains(filter)) { 3173 if (domains == null) { 3174 domains = new ArraySet<String>(); 3175 } 3176 domains.addAll(filter.getHostsList()); 3177 } 3178 } 3179 } 3180 3181 if (domains != null && domains.size() > 0) { 3182 if (DEBUG_DOMAIN_VERIFICATION) { 3183 Slog.v(TAG, " + " + packageName); 3184 } 3185 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3186 // state w.r.t. the formal app-linkage "no verification attempted" state; 3187 // and then 'always' in the per-user state actually used for intent resolution. 3188 final IntentFilterVerificationInfo ivi; 3189 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3190 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3191 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3192 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3193 } else { 3194 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3195 + "' does not handle web links"); 3196 } 3197 } else { 3198 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3199 } 3200 } 3201 3202 scheduleWritePackageRestrictionsLocked(userId); 3203 scheduleWriteSettingsLocked(); 3204 } 3205 3206 private void applyFactoryDefaultBrowserLPw(int userId) { 3207 // The default browser app's package name is stored in a string resource, 3208 // with a product-specific overlay used for vendor customization. 3209 String browserPkg = mContext.getResources().getString( 3210 com.android.internal.R.string.default_browser); 3211 if (!TextUtils.isEmpty(browserPkg)) { 3212 // non-empty string => required to be a known package 3213 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3214 if (ps == null) { 3215 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3216 browserPkg = null; 3217 } else { 3218 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3219 } 3220 } 3221 3222 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3223 // default. If there's more than one, just leave everything alone. 3224 if (browserPkg == null) { 3225 calculateDefaultBrowserLPw(userId); 3226 } 3227 } 3228 3229 private void calculateDefaultBrowserLPw(int userId) { 3230 List<String> allBrowsers = resolveAllBrowserApps(userId); 3231 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3232 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3233 } 3234 3235 private List<String> resolveAllBrowserApps(int userId) { 3236 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3237 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3238 PackageManager.MATCH_ALL, userId); 3239 3240 final int count = list.size(); 3241 List<String> result = new ArrayList<String>(count); 3242 for (int i=0; i<count; i++) { 3243 ResolveInfo info = list.get(i); 3244 if (info.activityInfo == null 3245 || !info.handleAllWebDataURI 3246 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3247 || result.contains(info.activityInfo.packageName)) { 3248 continue; 3249 } 3250 result.add(info.activityInfo.packageName); 3251 } 3252 3253 return result; 3254 } 3255 3256 private boolean packageIsBrowser(String packageName, int userId) { 3257 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3258 PackageManager.MATCH_ALL, userId); 3259 final int N = list.size(); 3260 for (int i = 0; i < N; i++) { 3261 ResolveInfo info = list.get(i); 3262 if (packageName.equals(info.activityInfo.packageName)) { 3263 return true; 3264 } 3265 } 3266 return false; 3267 } 3268 3269 private void checkDefaultBrowser() { 3270 final int myUserId = UserHandle.myUserId(); 3271 final String packageName = getDefaultBrowserPackageName(myUserId); 3272 if (packageName != null) { 3273 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3274 if (info == null) { 3275 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3276 synchronized (mPackages) { 3277 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3278 } 3279 } 3280 } 3281 } 3282 3283 @Override 3284 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3285 throws RemoteException { 3286 try { 3287 return super.onTransact(code, data, reply, flags); 3288 } catch (RuntimeException e) { 3289 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3290 Slog.wtf(TAG, "Package Manager Crash", e); 3291 } 3292 throw e; 3293 } 3294 } 3295 3296 static int[] appendInts(int[] cur, int[] add) { 3297 if (add == null) return cur; 3298 if (cur == null) return add; 3299 final int N = add.length; 3300 for (int i=0; i<N; i++) { 3301 cur = appendInt(cur, add[i]); 3302 } 3303 return cur; 3304 } 3305 3306 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3307 if (!sUserManager.exists(userId)) return null; 3308 if (ps == null) { 3309 return null; 3310 } 3311 final PackageParser.Package p = ps.pkg; 3312 if (p == null) { 3313 return null; 3314 } 3315 // Filter out ephemeral app metadata: 3316 // * The system/shell/root can see metadata for any app 3317 // * An installed app can see metadata for 1) other installed apps 3318 // and 2) ephemeral apps that have explicitly interacted with it 3319 // * Ephemeral apps can only see their own data and exposed installed apps 3320 // * Holding a signature permission allows seeing instant apps 3321 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3322 if (callingAppId != Process.SYSTEM_UID 3323 && callingAppId != Process.SHELL_UID 3324 && callingAppId != Process.ROOT_UID 3325 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3326 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3327 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3328 if (instantAppPackageName != null) { 3329 // ephemeral apps can only get information on themselves or 3330 // installed apps that are exposed. 3331 if (!instantAppPackageName.equals(p.packageName) 3332 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3333 return null; 3334 } 3335 } else { 3336 if (ps.getInstantApp(userId)) { 3337 // only get access to the ephemeral app if we've been granted access 3338 if (!mInstantAppRegistry.isInstantAccessGranted( 3339 userId, callingAppId, ps.appId)) { 3340 return null; 3341 } 3342 } 3343 } 3344 } 3345 3346 final PermissionsState permissionsState = ps.getPermissionsState(); 3347 3348 // Compute GIDs only if requested 3349 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3350 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3351 // Compute granted permissions only if package has requested permissions 3352 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3353 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3354 final PackageUserState state = ps.readUserState(userId); 3355 3356 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3357 && ps.isSystem()) { 3358 flags |= MATCH_ANY_USER; 3359 } 3360 3361 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3362 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3363 3364 if (packageInfo == null) { 3365 return null; 3366 } 3367 3368 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3369 3370 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3371 resolveExternalPackageNameLPr(p); 3372 3373 return packageInfo; 3374 } 3375 3376 @Override 3377 public void checkPackageStartable(String packageName, int userId) { 3378 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3379 3380 synchronized (mPackages) { 3381 final PackageSetting ps = mSettings.mPackages.get(packageName); 3382 if (ps == null) { 3383 throw new SecurityException("Package " + packageName + " was not found!"); 3384 } 3385 3386 if (!ps.getInstalled(userId)) { 3387 throw new SecurityException( 3388 "Package " + packageName + " was not installed for user " + userId + "!"); 3389 } 3390 3391 if (mSafeMode && !ps.isSystem()) { 3392 throw new SecurityException("Package " + packageName + " not a system app!"); 3393 } 3394 3395 if (mFrozenPackages.contains(packageName)) { 3396 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3397 } 3398 3399 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3400 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3401 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3402 } 3403 } 3404 } 3405 3406 @Override 3407 public boolean isPackageAvailable(String packageName, int userId) { 3408 if (!sUserManager.exists(userId)) return false; 3409 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3410 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3411 synchronized (mPackages) { 3412 PackageParser.Package p = mPackages.get(packageName); 3413 if (p != null) { 3414 final PackageSetting ps = (PackageSetting) p.mExtras; 3415 if (ps != null) { 3416 final PackageUserState state = ps.readUserState(userId); 3417 if (state != null) { 3418 return PackageParser.isAvailable(state); 3419 } 3420 } 3421 } 3422 } 3423 return false; 3424 } 3425 3426 @Override 3427 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3428 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3429 flags, userId); 3430 } 3431 3432 @Override 3433 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3434 int flags, int userId) { 3435 return getPackageInfoInternal(versionedPackage.getPackageName(), 3436 // TODO: We will change version code to long, so in the new API it is long 3437 (int) versionedPackage.getVersionCode(), flags, userId); 3438 } 3439 3440 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3441 int flags, int userId) { 3442 if (!sUserManager.exists(userId)) return null; 3443 flags = updateFlagsForPackage(flags, userId, packageName); 3444 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3445 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3446 3447 // reader 3448 synchronized (mPackages) { 3449 // Normalize package name to handle renamed packages and static libs 3450 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3451 3452 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3453 if (matchFactoryOnly) { 3454 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3455 if (ps != null) { 3456 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3457 return null; 3458 } 3459 return generatePackageInfo(ps, flags, userId); 3460 } 3461 } 3462 3463 PackageParser.Package p = mPackages.get(packageName); 3464 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3465 return null; 3466 } 3467 if (DEBUG_PACKAGE_INFO) 3468 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3469 if (p != null) { 3470 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3471 Binder.getCallingUid(), userId)) { 3472 return null; 3473 } 3474 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3475 } 3476 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3477 final PackageSetting ps = mSettings.mPackages.get(packageName); 3478 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3479 return null; 3480 } 3481 return generatePackageInfo(ps, flags, userId); 3482 } 3483 } 3484 return null; 3485 } 3486 3487 3488 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3489 // System/shell/root get to see all static libs 3490 final int appId = UserHandle.getAppId(uid); 3491 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3492 || appId == Process.ROOT_UID) { 3493 return false; 3494 } 3495 3496 // No package means no static lib as it is always on internal storage 3497 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3498 return false; 3499 } 3500 3501 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3502 ps.pkg.staticSharedLibVersion); 3503 if (libEntry == null) { 3504 return false; 3505 } 3506 3507 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3508 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3509 if (uidPackageNames == null) { 3510 return true; 3511 } 3512 3513 for (String uidPackageName : uidPackageNames) { 3514 if (ps.name.equals(uidPackageName)) { 3515 return false; 3516 } 3517 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3518 if (uidPs != null) { 3519 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3520 libEntry.info.getName()); 3521 if (index < 0) { 3522 continue; 3523 } 3524 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3525 return false; 3526 } 3527 } 3528 } 3529 return true; 3530 } 3531 3532 @Override 3533 public String[] currentToCanonicalPackageNames(String[] names) { 3534 String[] out = new String[names.length]; 3535 // reader 3536 synchronized (mPackages) { 3537 for (int i=names.length-1; i>=0; i--) { 3538 PackageSetting ps = mSettings.mPackages.get(names[i]); 3539 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3540 } 3541 } 3542 return out; 3543 } 3544 3545 @Override 3546 public String[] canonicalToCurrentPackageNames(String[] names) { 3547 String[] out = new String[names.length]; 3548 // reader 3549 synchronized (mPackages) { 3550 for (int i=names.length-1; i>=0; i--) { 3551 String cur = mSettings.getRenamedPackageLPr(names[i]); 3552 out[i] = cur != null ? cur : names[i]; 3553 } 3554 } 3555 return out; 3556 } 3557 3558 @Override 3559 public int getPackageUid(String packageName, int flags, int userId) { 3560 if (!sUserManager.exists(userId)) return -1; 3561 flags = updateFlagsForPackage(flags, userId, packageName); 3562 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3563 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3564 3565 // reader 3566 synchronized (mPackages) { 3567 final PackageParser.Package p = mPackages.get(packageName); 3568 if (p != null && p.isMatch(flags)) { 3569 return UserHandle.getUid(userId, p.applicationInfo.uid); 3570 } 3571 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3572 final PackageSetting ps = mSettings.mPackages.get(packageName); 3573 if (ps != null && ps.isMatch(flags)) { 3574 return UserHandle.getUid(userId, ps.appId); 3575 } 3576 } 3577 } 3578 3579 return -1; 3580 } 3581 3582 @Override 3583 public int[] getPackageGids(String packageName, int flags, int userId) { 3584 if (!sUserManager.exists(userId)) return null; 3585 flags = updateFlagsForPackage(flags, userId, packageName); 3586 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3587 false /* requireFullPermission */, false /* checkShell */, 3588 "getPackageGids"); 3589 3590 // reader 3591 synchronized (mPackages) { 3592 final PackageParser.Package p = mPackages.get(packageName); 3593 if (p != null && p.isMatch(flags)) { 3594 PackageSetting ps = (PackageSetting) p.mExtras; 3595 // TODO: Shouldn't this be checking for package installed state for userId and 3596 // return null? 3597 return ps.getPermissionsState().computeGids(userId); 3598 } 3599 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3600 final PackageSetting ps = mSettings.mPackages.get(packageName); 3601 if (ps != null && ps.isMatch(flags)) { 3602 return ps.getPermissionsState().computeGids(userId); 3603 } 3604 } 3605 } 3606 3607 return null; 3608 } 3609 3610 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3611 if (bp.perm != null) { 3612 return PackageParser.generatePermissionInfo(bp.perm, flags); 3613 } 3614 PermissionInfo pi = new PermissionInfo(); 3615 pi.name = bp.name; 3616 pi.packageName = bp.sourcePackage; 3617 pi.nonLocalizedLabel = bp.name; 3618 pi.protectionLevel = bp.protectionLevel; 3619 return pi; 3620 } 3621 3622 @Override 3623 public PermissionInfo getPermissionInfo(String name, int flags) { 3624 // reader 3625 synchronized (mPackages) { 3626 final BasePermission p = mSettings.mPermissions.get(name); 3627 if (p != null) { 3628 return generatePermissionInfo(p, flags); 3629 } 3630 return null; 3631 } 3632 } 3633 3634 @Override 3635 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3636 int flags) { 3637 // reader 3638 synchronized (mPackages) { 3639 if (group != null && !mPermissionGroups.containsKey(group)) { 3640 // This is thrown as NameNotFoundException 3641 return null; 3642 } 3643 3644 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3645 for (BasePermission p : mSettings.mPermissions.values()) { 3646 if (group == null) { 3647 if (p.perm == null || p.perm.info.group == null) { 3648 out.add(generatePermissionInfo(p, flags)); 3649 } 3650 } else { 3651 if (p.perm != null && group.equals(p.perm.info.group)) { 3652 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3653 } 3654 } 3655 } 3656 return new ParceledListSlice<>(out); 3657 } 3658 } 3659 3660 @Override 3661 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3662 // reader 3663 synchronized (mPackages) { 3664 return PackageParser.generatePermissionGroupInfo( 3665 mPermissionGroups.get(name), flags); 3666 } 3667 } 3668 3669 @Override 3670 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3671 // reader 3672 synchronized (mPackages) { 3673 final int N = mPermissionGroups.size(); 3674 ArrayList<PermissionGroupInfo> out 3675 = new ArrayList<PermissionGroupInfo>(N); 3676 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3677 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3678 } 3679 return new ParceledListSlice<>(out); 3680 } 3681 } 3682 3683 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3684 int uid, int userId) { 3685 if (!sUserManager.exists(userId)) return null; 3686 PackageSetting ps = mSettings.mPackages.get(packageName); 3687 if (ps != null) { 3688 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3689 return null; 3690 } 3691 if (ps.pkg == null) { 3692 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3693 if (pInfo != null) { 3694 return pInfo.applicationInfo; 3695 } 3696 return null; 3697 } 3698 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3699 ps.readUserState(userId), userId); 3700 if (ai != null) { 3701 rebaseEnabledOverlays(ai, userId); 3702 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3703 } 3704 return ai; 3705 } 3706 return null; 3707 } 3708 3709 @Override 3710 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3711 if (!sUserManager.exists(userId)) return null; 3712 flags = updateFlagsForApplication(flags, userId, packageName); 3713 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3714 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3715 3716 // writer 3717 synchronized (mPackages) { 3718 // Normalize package name to handle renamed packages and static libs 3719 packageName = resolveInternalPackageNameLPr(packageName, 3720 PackageManager.VERSION_CODE_HIGHEST); 3721 3722 PackageParser.Package p = mPackages.get(packageName); 3723 if (DEBUG_PACKAGE_INFO) Log.v( 3724 TAG, "getApplicationInfo " + packageName 3725 + ": " + p); 3726 if (p != null) { 3727 PackageSetting ps = mSettings.mPackages.get(packageName); 3728 if (ps == null) return null; 3729 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3730 return null; 3731 } 3732 // Note: isEnabledLP() does not apply here - always return info 3733 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3734 p, flags, ps.readUserState(userId), userId); 3735 if (ai != null) { 3736 rebaseEnabledOverlays(ai, userId); 3737 ai.packageName = resolveExternalPackageNameLPr(p); 3738 } 3739 return ai; 3740 } 3741 if ("android".equals(packageName)||"system".equals(packageName)) { 3742 return mAndroidApplication; 3743 } 3744 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3745 // Already generates the external package name 3746 return generateApplicationInfoFromSettingsLPw(packageName, 3747 Binder.getCallingUid(), flags, userId); 3748 } 3749 } 3750 return null; 3751 } 3752 3753 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3754 List<String> paths = new ArrayList<>(); 3755 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3756 mEnabledOverlayPaths.get(userId); 3757 if (userSpecificOverlays != null) { 3758 if (!"android".equals(ai.packageName)) { 3759 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3760 if (frameworkOverlays != null) { 3761 paths.addAll(frameworkOverlays); 3762 } 3763 } 3764 3765 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3766 if (appOverlays != null) { 3767 paths.addAll(appOverlays); 3768 } 3769 } 3770 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3771 } 3772 3773 private String normalizePackageNameLPr(String packageName) { 3774 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3775 return normalizedPackageName != null ? normalizedPackageName : packageName; 3776 } 3777 3778 @Override 3779 public void deletePreloadsFileCache() { 3780 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3781 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3782 } 3783 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3784 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3785 FileUtils.deleteContents(dir); 3786 } 3787 3788 @Override 3789 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3790 final IPackageDataObserver observer) { 3791 mContext.enforceCallingOrSelfPermission( 3792 android.Manifest.permission.CLEAR_APP_CACHE, null); 3793 mHandler.post(() -> { 3794 boolean success = false; 3795 try { 3796 freeStorage(volumeUuid, freeStorageSize, 0); 3797 success = true; 3798 } catch (IOException e) { 3799 Slog.w(TAG, e); 3800 } 3801 if (observer != null) { 3802 try { 3803 observer.onRemoveCompleted(null, success); 3804 } catch (RemoteException e) { 3805 Slog.w(TAG, e); 3806 } 3807 } 3808 }); 3809 } 3810 3811 @Override 3812 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3813 final IntentSender pi) { 3814 mContext.enforceCallingOrSelfPermission( 3815 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3816 mHandler.post(() -> { 3817 boolean success = false; 3818 try { 3819 freeStorage(volumeUuid, freeStorageSize, 0); 3820 success = true; 3821 } catch (IOException e) { 3822 Slog.w(TAG, e); 3823 } 3824 if (pi != null) { 3825 try { 3826 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3827 } catch (SendIntentException e) { 3828 Slog.w(TAG, e); 3829 } 3830 } 3831 }); 3832 } 3833 3834 /** 3835 * Blocking call to clear various types of cached data across the system 3836 * until the requested bytes are available. 3837 */ 3838 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3839 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3840 final File file = storage.findPathForUuid(volumeUuid); 3841 if (file.getUsableSpace() >= bytes) return; 3842 3843 if (ENABLE_FREE_CACHE_V2) { 3844 final boolean aggressive = (storageFlags 3845 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3846 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3847 volumeUuid); 3848 3849 // 1. Pre-flight to determine if we have any chance to succeed 3850 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3851 if (internalVolume && (aggressive || SystemProperties 3852 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3853 deletePreloadsFileCache(); 3854 if (file.getUsableSpace() >= bytes) return; 3855 } 3856 3857 // 3. Consider parsed APK data (aggressive only) 3858 if (internalVolume && aggressive) { 3859 FileUtils.deleteContents(mCacheDir); 3860 if (file.getUsableSpace() >= bytes) return; 3861 } 3862 3863 // 4. Consider cached app data (above quotas) 3864 try { 3865 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3866 } catch (InstallerException ignored) { 3867 } 3868 if (file.getUsableSpace() >= bytes) return; 3869 3870 // 5. Consider shared libraries with refcount=0 and age>2h 3871 // 6. Consider dexopt output (aggressive only) 3872 // 7. Consider ephemeral apps not used in last week 3873 3874 // 8. Consider cached app data (below quotas) 3875 try { 3876 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3877 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3878 } catch (InstallerException ignored) { 3879 } 3880 if (file.getUsableSpace() >= bytes) return; 3881 3882 // 9. Consider DropBox entries 3883 // 10. Consider ephemeral cookies 3884 3885 } else { 3886 try { 3887 mInstaller.freeCache(volumeUuid, bytes, 0); 3888 } catch (InstallerException ignored) { 3889 } 3890 if (file.getUsableSpace() >= bytes) return; 3891 } 3892 3893 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3894 } 3895 3896 /** 3897 * Update given flags based on encryption status of current user. 3898 */ 3899 private int updateFlags(int flags, int userId) { 3900 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3901 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3902 // Caller expressed an explicit opinion about what encryption 3903 // aware/unaware components they want to see, so fall through and 3904 // give them what they want 3905 } else { 3906 // Caller expressed no opinion, so match based on user state 3907 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3908 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3909 } else { 3910 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3911 } 3912 } 3913 return flags; 3914 } 3915 3916 private UserManagerInternal getUserManagerInternal() { 3917 if (mUserManagerInternal == null) { 3918 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3919 } 3920 return mUserManagerInternal; 3921 } 3922 3923 private DeviceIdleController.LocalService getDeviceIdleController() { 3924 if (mDeviceIdleController == null) { 3925 mDeviceIdleController = 3926 LocalServices.getService(DeviceIdleController.LocalService.class); 3927 } 3928 return mDeviceIdleController; 3929 } 3930 3931 /** 3932 * Update given flags when being used to request {@link PackageInfo}. 3933 */ 3934 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3935 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3936 boolean triaged = true; 3937 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3938 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3939 // Caller is asking for component details, so they'd better be 3940 // asking for specific encryption matching behavior, or be triaged 3941 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3942 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3943 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3944 triaged = false; 3945 } 3946 } 3947 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3948 | PackageManager.MATCH_SYSTEM_ONLY 3949 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3950 triaged = false; 3951 } 3952 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3953 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3954 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3955 + Debug.getCallers(5)); 3956 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3957 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3958 // If the caller wants all packages and has a restricted profile associated with it, 3959 // then match all users. This is to make sure that launchers that need to access work 3960 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3961 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3962 flags |= PackageManager.MATCH_ANY_USER; 3963 } 3964 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3965 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3966 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3967 } 3968 return updateFlags(flags, userId); 3969 } 3970 3971 /** 3972 * Update given flags when being used to request {@link ApplicationInfo}. 3973 */ 3974 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3975 return updateFlagsForPackage(flags, userId, cookie); 3976 } 3977 3978 /** 3979 * Update given flags when being used to request {@link ComponentInfo}. 3980 */ 3981 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3982 if (cookie instanceof Intent) { 3983 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3984 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3985 } 3986 } 3987 3988 boolean triaged = true; 3989 // Caller is asking for component details, so they'd better be 3990 // asking for specific encryption matching behavior, or be triaged 3991 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3992 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3993 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3994 triaged = false; 3995 } 3996 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3997 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3998 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3999 } 4000 4001 return updateFlags(flags, userId); 4002 } 4003 4004 /** 4005 * Update given intent when being used to request {@link ResolveInfo}. 4006 */ 4007 private Intent updateIntentForResolve(Intent intent) { 4008 if (intent.getSelector() != null) { 4009 intent = intent.getSelector(); 4010 } 4011 if (DEBUG_PREFERRED) { 4012 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4013 } 4014 return intent; 4015 } 4016 4017 /** 4018 * Update given flags when being used to request {@link ResolveInfo}. 4019 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4020 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4021 * flag set. However, this flag is only honoured in three circumstances: 4022 * <ul> 4023 * <li>when called from a system process</li> 4024 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4025 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4026 * action and a {@code android.intent.category.BROWSABLE} category</li> 4027 * </ul> 4028 */ 4029 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4030 boolean includeInstantApps) { 4031 // Safe mode means we shouldn't match any third-party components 4032 if (mSafeMode) { 4033 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4034 } 4035 if (getInstantAppPackageName(callingUid) != null) { 4036 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4037 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4038 flags |= PackageManager.MATCH_INSTANT; 4039 } else { 4040 // Otherwise, prevent leaking ephemeral components 4041 final boolean isSpecialProcess = 4042 callingUid == Process.SYSTEM_UID 4043 || callingUid == Process.SHELL_UID 4044 || callingUid == 0; 4045 final boolean allowMatchInstant = 4046 (includeInstantApps 4047 && Intent.ACTION_VIEW.equals(intent.getAction()) 4048 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4049 && hasWebURI(intent)) 4050 || isSpecialProcess 4051 || mContext.checkCallingOrSelfPermission( 4052 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4053 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4054 if (!allowMatchInstant) { 4055 flags &= ~PackageManager.MATCH_INSTANT; 4056 } 4057 } 4058 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4059 } 4060 4061 @Override 4062 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4063 if (!sUserManager.exists(userId)) return null; 4064 flags = updateFlagsForComponent(flags, userId, component); 4065 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4066 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4067 synchronized (mPackages) { 4068 PackageParser.Activity a = mActivities.mActivities.get(component); 4069 4070 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4071 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4072 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4073 if (ps == null) return null; 4074 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4075 userId); 4076 } 4077 if (mResolveComponentName.equals(component)) { 4078 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4079 new PackageUserState(), userId); 4080 } 4081 } 4082 return null; 4083 } 4084 4085 @Override 4086 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4087 String resolvedType) { 4088 synchronized (mPackages) { 4089 if (component.equals(mResolveComponentName)) { 4090 // The resolver supports EVERYTHING! 4091 return true; 4092 } 4093 PackageParser.Activity a = mActivities.mActivities.get(component); 4094 if (a == null) { 4095 return false; 4096 } 4097 for (int i=0; i<a.intents.size(); i++) { 4098 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4099 intent.getData(), intent.getCategories(), TAG) >= 0) { 4100 return true; 4101 } 4102 } 4103 return false; 4104 } 4105 } 4106 4107 @Override 4108 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4109 if (!sUserManager.exists(userId)) return null; 4110 flags = updateFlagsForComponent(flags, userId, component); 4111 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4112 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4113 synchronized (mPackages) { 4114 PackageParser.Activity a = mReceivers.mActivities.get(component); 4115 if (DEBUG_PACKAGE_INFO) Log.v( 4116 TAG, "getReceiverInfo " + component + ": " + a); 4117 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4118 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4119 if (ps == null) return null; 4120 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4121 ps.readUserState(userId), userId); 4122 if (ri != null) { 4123 rebaseEnabledOverlays(ri.applicationInfo, userId); 4124 } 4125 return ri; 4126 } 4127 } 4128 return null; 4129 } 4130 4131 @Override 4132 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4133 if (!sUserManager.exists(userId)) return null; 4134 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4135 4136 flags = updateFlagsForPackage(flags, userId, null); 4137 4138 final boolean canSeeStaticLibraries = 4139 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4140 == PERMISSION_GRANTED 4141 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4142 == PERMISSION_GRANTED 4143 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4144 == PERMISSION_GRANTED 4145 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4146 == PERMISSION_GRANTED; 4147 4148 synchronized (mPackages) { 4149 List<SharedLibraryInfo> result = null; 4150 4151 final int libCount = mSharedLibraries.size(); 4152 for (int i = 0; i < libCount; i++) { 4153 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4154 if (versionedLib == null) { 4155 continue; 4156 } 4157 4158 final int versionCount = versionedLib.size(); 4159 for (int j = 0; j < versionCount; j++) { 4160 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4161 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4162 break; 4163 } 4164 final long identity = Binder.clearCallingIdentity(); 4165 try { 4166 // TODO: We will change version code to long, so in the new API it is long 4167 PackageInfo packageInfo = getPackageInfoVersioned( 4168 libInfo.getDeclaringPackage(), flags, userId); 4169 if (packageInfo == null) { 4170 continue; 4171 } 4172 } finally { 4173 Binder.restoreCallingIdentity(identity); 4174 } 4175 4176 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4177 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4178 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4179 4180 if (result == null) { 4181 result = new ArrayList<>(); 4182 } 4183 result.add(resLibInfo); 4184 } 4185 } 4186 4187 return result != null ? new ParceledListSlice<>(result) : null; 4188 } 4189 } 4190 4191 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4192 SharedLibraryInfo libInfo, int flags, int userId) { 4193 List<VersionedPackage> versionedPackages = null; 4194 final int packageCount = mSettings.mPackages.size(); 4195 for (int i = 0; i < packageCount; i++) { 4196 PackageSetting ps = mSettings.mPackages.valueAt(i); 4197 4198 if (ps == null) { 4199 continue; 4200 } 4201 4202 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4203 continue; 4204 } 4205 4206 final String libName = libInfo.getName(); 4207 if (libInfo.isStatic()) { 4208 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4209 if (libIdx < 0) { 4210 continue; 4211 } 4212 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4213 continue; 4214 } 4215 if (versionedPackages == null) { 4216 versionedPackages = new ArrayList<>(); 4217 } 4218 // If the dependent is a static shared lib, use the public package name 4219 String dependentPackageName = ps.name; 4220 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4221 dependentPackageName = ps.pkg.manifestPackageName; 4222 } 4223 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4224 } else if (ps.pkg != null) { 4225 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4226 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4227 if (versionedPackages == null) { 4228 versionedPackages = new ArrayList<>(); 4229 } 4230 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4231 } 4232 } 4233 } 4234 4235 return versionedPackages; 4236 } 4237 4238 @Override 4239 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4240 if (!sUserManager.exists(userId)) return null; 4241 flags = updateFlagsForComponent(flags, userId, component); 4242 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4243 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4244 synchronized (mPackages) { 4245 PackageParser.Service s = mServices.mServices.get(component); 4246 if (DEBUG_PACKAGE_INFO) Log.v( 4247 TAG, "getServiceInfo " + component + ": " + s); 4248 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4249 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4250 if (ps == null) return null; 4251 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4252 ps.readUserState(userId), userId); 4253 if (si != null) { 4254 rebaseEnabledOverlays(si.applicationInfo, userId); 4255 } 4256 return si; 4257 } 4258 } 4259 return null; 4260 } 4261 4262 @Override 4263 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4264 if (!sUserManager.exists(userId)) return null; 4265 flags = updateFlagsForComponent(flags, userId, component); 4266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4267 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4268 synchronized (mPackages) { 4269 PackageParser.Provider p = mProviders.mProviders.get(component); 4270 if (DEBUG_PACKAGE_INFO) Log.v( 4271 TAG, "getProviderInfo " + component + ": " + p); 4272 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4273 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4274 if (ps == null) return null; 4275 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4276 ps.readUserState(userId), userId); 4277 if (pi != null) { 4278 rebaseEnabledOverlays(pi.applicationInfo, userId); 4279 } 4280 return pi; 4281 } 4282 } 4283 return null; 4284 } 4285 4286 @Override 4287 public String[] getSystemSharedLibraryNames() { 4288 synchronized (mPackages) { 4289 Set<String> libs = null; 4290 final int libCount = mSharedLibraries.size(); 4291 for (int i = 0; i < libCount; i++) { 4292 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4293 if (versionedLib == null) { 4294 continue; 4295 } 4296 final int versionCount = versionedLib.size(); 4297 for (int j = 0; j < versionCount; j++) { 4298 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4299 if (!libEntry.info.isStatic()) { 4300 if (libs == null) { 4301 libs = new ArraySet<>(); 4302 } 4303 libs.add(libEntry.info.getName()); 4304 break; 4305 } 4306 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4307 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4308 UserHandle.getUserId(Binder.getCallingUid()))) { 4309 if (libs == null) { 4310 libs = new ArraySet<>(); 4311 } 4312 libs.add(libEntry.info.getName()); 4313 break; 4314 } 4315 } 4316 } 4317 4318 if (libs != null) { 4319 String[] libsArray = new String[libs.size()]; 4320 libs.toArray(libsArray); 4321 return libsArray; 4322 } 4323 4324 return null; 4325 } 4326 } 4327 4328 @Override 4329 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4330 synchronized (mPackages) { 4331 return mServicesSystemSharedLibraryPackageName; 4332 } 4333 } 4334 4335 @Override 4336 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4337 synchronized (mPackages) { 4338 return mSharedSystemSharedLibraryPackageName; 4339 } 4340 } 4341 4342 private void updateSequenceNumberLP(String packageName, int[] userList) { 4343 for (int i = userList.length - 1; i >= 0; --i) { 4344 final int userId = userList[i]; 4345 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4346 if (changedPackages == null) { 4347 changedPackages = new SparseArray<>(); 4348 mChangedPackages.put(userId, changedPackages); 4349 } 4350 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4351 if (sequenceNumbers == null) { 4352 sequenceNumbers = new HashMap<>(); 4353 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4354 } 4355 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4356 if (sequenceNumber != null) { 4357 changedPackages.remove(sequenceNumber); 4358 } 4359 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4360 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4361 } 4362 mChangedPackagesSequenceNumber++; 4363 } 4364 4365 @Override 4366 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4367 synchronized (mPackages) { 4368 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4369 return null; 4370 } 4371 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4372 if (changedPackages == null) { 4373 return null; 4374 } 4375 final List<String> packageNames = 4376 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4377 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4378 final String packageName = changedPackages.get(i); 4379 if (packageName != null) { 4380 packageNames.add(packageName); 4381 } 4382 } 4383 return packageNames.isEmpty() 4384 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4385 } 4386 } 4387 4388 @Override 4389 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4390 ArrayList<FeatureInfo> res; 4391 synchronized (mAvailableFeatures) { 4392 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4393 res.addAll(mAvailableFeatures.values()); 4394 } 4395 final FeatureInfo fi = new FeatureInfo(); 4396 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4397 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4398 res.add(fi); 4399 4400 return new ParceledListSlice<>(res); 4401 } 4402 4403 @Override 4404 public boolean hasSystemFeature(String name, int version) { 4405 synchronized (mAvailableFeatures) { 4406 final FeatureInfo feat = mAvailableFeatures.get(name); 4407 if (feat == null) { 4408 return false; 4409 } else { 4410 return feat.version >= version; 4411 } 4412 } 4413 } 4414 4415 @Override 4416 public int checkPermission(String permName, String pkgName, int userId) { 4417 if (!sUserManager.exists(userId)) { 4418 return PackageManager.PERMISSION_DENIED; 4419 } 4420 4421 synchronized (mPackages) { 4422 final PackageParser.Package p = mPackages.get(pkgName); 4423 if (p != null && p.mExtras != null) { 4424 final PackageSetting ps = (PackageSetting) p.mExtras; 4425 final PermissionsState permissionsState = ps.getPermissionsState(); 4426 if (permissionsState.hasPermission(permName, userId)) { 4427 return PackageManager.PERMISSION_GRANTED; 4428 } 4429 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4430 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4431 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4432 return PackageManager.PERMISSION_GRANTED; 4433 } 4434 } 4435 } 4436 4437 return PackageManager.PERMISSION_DENIED; 4438 } 4439 4440 @Override 4441 public int checkUidPermission(String permName, int uid) { 4442 final int userId = UserHandle.getUserId(uid); 4443 4444 if (!sUserManager.exists(userId)) { 4445 return PackageManager.PERMISSION_DENIED; 4446 } 4447 4448 synchronized (mPackages) { 4449 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4450 if (obj != null) { 4451 final SettingBase ps = (SettingBase) obj; 4452 final PermissionsState permissionsState = ps.getPermissionsState(); 4453 if (permissionsState.hasPermission(permName, userId)) { 4454 return PackageManager.PERMISSION_GRANTED; 4455 } 4456 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4457 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4458 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4459 return PackageManager.PERMISSION_GRANTED; 4460 } 4461 } else { 4462 ArraySet<String> perms = mSystemPermissions.get(uid); 4463 if (perms != null) { 4464 if (perms.contains(permName)) { 4465 return PackageManager.PERMISSION_GRANTED; 4466 } 4467 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4468 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4469 return PackageManager.PERMISSION_GRANTED; 4470 } 4471 } 4472 } 4473 } 4474 4475 return PackageManager.PERMISSION_DENIED; 4476 } 4477 4478 @Override 4479 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4480 if (UserHandle.getCallingUserId() != userId) { 4481 mContext.enforceCallingPermission( 4482 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4483 "isPermissionRevokedByPolicy for user " + userId); 4484 } 4485 4486 if (checkPermission(permission, packageName, userId) 4487 == PackageManager.PERMISSION_GRANTED) { 4488 return false; 4489 } 4490 4491 final long identity = Binder.clearCallingIdentity(); 4492 try { 4493 final int flags = getPermissionFlags(permission, packageName, userId); 4494 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4495 } finally { 4496 Binder.restoreCallingIdentity(identity); 4497 } 4498 } 4499 4500 @Override 4501 public String getPermissionControllerPackageName() { 4502 synchronized (mPackages) { 4503 return mRequiredInstallerPackage; 4504 } 4505 } 4506 4507 /** 4508 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4509 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4510 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4511 * @param message the message to log on security exception 4512 */ 4513 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4514 boolean checkShell, String message) { 4515 if (userId < 0) { 4516 throw new IllegalArgumentException("Invalid userId " + userId); 4517 } 4518 if (checkShell) { 4519 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4520 } 4521 if (userId == UserHandle.getUserId(callingUid)) return; 4522 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4523 if (requireFullPermission) { 4524 mContext.enforceCallingOrSelfPermission( 4525 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4526 } else { 4527 try { 4528 mContext.enforceCallingOrSelfPermission( 4529 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4530 } catch (SecurityException se) { 4531 mContext.enforceCallingOrSelfPermission( 4532 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4533 } 4534 } 4535 } 4536 } 4537 4538 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4539 if (callingUid == Process.SHELL_UID) { 4540 if (userHandle >= 0 4541 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4542 throw new SecurityException("Shell does not have permission to access user " 4543 + userHandle); 4544 } else if (userHandle < 0) { 4545 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4546 + Debug.getCallers(3)); 4547 } 4548 } 4549 } 4550 4551 private BasePermission findPermissionTreeLP(String permName) { 4552 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4553 if (permName.startsWith(bp.name) && 4554 permName.length() > bp.name.length() && 4555 permName.charAt(bp.name.length()) == '.') { 4556 return bp; 4557 } 4558 } 4559 return null; 4560 } 4561 4562 private BasePermission checkPermissionTreeLP(String permName) { 4563 if (permName != null) { 4564 BasePermission bp = findPermissionTreeLP(permName); 4565 if (bp != null) { 4566 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4567 return bp; 4568 } 4569 throw new SecurityException("Calling uid " 4570 + Binder.getCallingUid() 4571 + " is not allowed to add to permission tree " 4572 + bp.name + " owned by uid " + bp.uid); 4573 } 4574 } 4575 throw new SecurityException("No permission tree found for " + permName); 4576 } 4577 4578 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4579 if (s1 == null) { 4580 return s2 == null; 4581 } 4582 if (s2 == null) { 4583 return false; 4584 } 4585 if (s1.getClass() != s2.getClass()) { 4586 return false; 4587 } 4588 return s1.equals(s2); 4589 } 4590 4591 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4592 if (pi1.icon != pi2.icon) return false; 4593 if (pi1.logo != pi2.logo) return false; 4594 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4595 if (!compareStrings(pi1.name, pi2.name)) return false; 4596 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4597 // We'll take care of setting this one. 4598 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4599 // These are not currently stored in settings. 4600 //if (!compareStrings(pi1.group, pi2.group)) return false; 4601 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4602 //if (pi1.labelRes != pi2.labelRes) return false; 4603 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4604 return true; 4605 } 4606 4607 int permissionInfoFootprint(PermissionInfo info) { 4608 int size = info.name.length(); 4609 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4610 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4611 return size; 4612 } 4613 4614 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4615 int size = 0; 4616 for (BasePermission perm : mSettings.mPermissions.values()) { 4617 if (perm.uid == tree.uid) { 4618 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4619 } 4620 } 4621 return size; 4622 } 4623 4624 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4625 // We calculate the max size of permissions defined by this uid and throw 4626 // if that plus the size of 'info' would exceed our stated maximum. 4627 if (tree.uid != Process.SYSTEM_UID) { 4628 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4629 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4630 throw new SecurityException("Permission tree size cap exceeded"); 4631 } 4632 } 4633 } 4634 4635 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4636 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4637 throw new SecurityException("Label must be specified in permission"); 4638 } 4639 BasePermission tree = checkPermissionTreeLP(info.name); 4640 BasePermission bp = mSettings.mPermissions.get(info.name); 4641 boolean added = bp == null; 4642 boolean changed = true; 4643 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4644 if (added) { 4645 enforcePermissionCapLocked(info, tree); 4646 bp = new BasePermission(info.name, tree.sourcePackage, 4647 BasePermission.TYPE_DYNAMIC); 4648 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4649 throw new SecurityException( 4650 "Not allowed to modify non-dynamic permission " 4651 + info.name); 4652 } else { 4653 if (bp.protectionLevel == fixedLevel 4654 && bp.perm.owner.equals(tree.perm.owner) 4655 && bp.uid == tree.uid 4656 && comparePermissionInfos(bp.perm.info, info)) { 4657 changed = false; 4658 } 4659 } 4660 bp.protectionLevel = fixedLevel; 4661 info = new PermissionInfo(info); 4662 info.protectionLevel = fixedLevel; 4663 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4664 bp.perm.info.packageName = tree.perm.info.packageName; 4665 bp.uid = tree.uid; 4666 if (added) { 4667 mSettings.mPermissions.put(info.name, bp); 4668 } 4669 if (changed) { 4670 if (!async) { 4671 mSettings.writeLPr(); 4672 } else { 4673 scheduleWriteSettingsLocked(); 4674 } 4675 } 4676 return added; 4677 } 4678 4679 @Override 4680 public boolean addPermission(PermissionInfo info) { 4681 synchronized (mPackages) { 4682 return addPermissionLocked(info, false); 4683 } 4684 } 4685 4686 @Override 4687 public boolean addPermissionAsync(PermissionInfo info) { 4688 synchronized (mPackages) { 4689 return addPermissionLocked(info, true); 4690 } 4691 } 4692 4693 @Override 4694 public void removePermission(String name) { 4695 synchronized (mPackages) { 4696 checkPermissionTreeLP(name); 4697 BasePermission bp = mSettings.mPermissions.get(name); 4698 if (bp != null) { 4699 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4700 throw new SecurityException( 4701 "Not allowed to modify non-dynamic permission " 4702 + name); 4703 } 4704 mSettings.mPermissions.remove(name); 4705 mSettings.writeLPr(); 4706 } 4707 } 4708 } 4709 4710 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4711 BasePermission bp) { 4712 int index = pkg.requestedPermissions.indexOf(bp.name); 4713 if (index == -1) { 4714 throw new SecurityException("Package " + pkg.packageName 4715 + " has not requested permission " + bp.name); 4716 } 4717 if (!bp.isRuntime() && !bp.isDevelopment()) { 4718 throw new SecurityException("Permission " + bp.name 4719 + " is not a changeable permission type"); 4720 } 4721 } 4722 4723 @Override 4724 public void grantRuntimePermission(String packageName, String name, final int userId) { 4725 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4726 } 4727 4728 private void grantRuntimePermission(String packageName, String name, final int userId, 4729 boolean overridePolicy) { 4730 if (!sUserManager.exists(userId)) { 4731 Log.e(TAG, "No such user:" + userId); 4732 return; 4733 } 4734 4735 mContext.enforceCallingOrSelfPermission( 4736 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4737 "grantRuntimePermission"); 4738 4739 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4740 true /* requireFullPermission */, true /* checkShell */, 4741 "grantRuntimePermission"); 4742 4743 final int uid; 4744 final SettingBase sb; 4745 4746 synchronized (mPackages) { 4747 final PackageParser.Package pkg = mPackages.get(packageName); 4748 if (pkg == null) { 4749 throw new IllegalArgumentException("Unknown package: " + packageName); 4750 } 4751 4752 final BasePermission bp = mSettings.mPermissions.get(name); 4753 if (bp == null) { 4754 throw new IllegalArgumentException("Unknown permission: " + name); 4755 } 4756 4757 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4758 4759 // If a permission review is required for legacy apps we represent 4760 // their permissions as always granted runtime ones since we need 4761 // to keep the review required permission flag per user while an 4762 // install permission's state is shared across all users. 4763 if (mPermissionReviewRequired 4764 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4765 && bp.isRuntime()) { 4766 return; 4767 } 4768 4769 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4770 sb = (SettingBase) pkg.mExtras; 4771 if (sb == null) { 4772 throw new IllegalArgumentException("Unknown package: " + packageName); 4773 } 4774 4775 final PermissionsState permissionsState = sb.getPermissionsState(); 4776 4777 final int flags = permissionsState.getPermissionFlags(name, userId); 4778 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4779 throw new SecurityException("Cannot grant system fixed permission " 4780 + name + " for package " + packageName); 4781 } 4782 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4783 throw new SecurityException("Cannot grant policy fixed permission " 4784 + name + " for package " + packageName); 4785 } 4786 4787 if (bp.isDevelopment()) { 4788 // Development permissions must be handled specially, since they are not 4789 // normal runtime permissions. For now they apply to all users. 4790 if (permissionsState.grantInstallPermission(bp) != 4791 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4792 scheduleWriteSettingsLocked(); 4793 } 4794 return; 4795 } 4796 4797 final PackageSetting ps = mSettings.mPackages.get(packageName); 4798 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4799 throw new SecurityException("Cannot grant non-ephemeral permission" 4800 + name + " for package " + packageName); 4801 } 4802 4803 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4804 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4805 return; 4806 } 4807 4808 final int result = permissionsState.grantRuntimePermission(bp, userId); 4809 switch (result) { 4810 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4811 return; 4812 } 4813 4814 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4815 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4816 mHandler.post(new Runnable() { 4817 @Override 4818 public void run() { 4819 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4820 } 4821 }); 4822 } 4823 break; 4824 } 4825 4826 if (bp.isRuntime()) { 4827 logPermissionGranted(mContext, name, packageName); 4828 } 4829 4830 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4831 4832 // Not critical if that is lost - app has to request again. 4833 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4834 } 4835 4836 // Only need to do this if user is initialized. Otherwise it's a new user 4837 // and there are no processes running as the user yet and there's no need 4838 // to make an expensive call to remount processes for the changed permissions. 4839 if (READ_EXTERNAL_STORAGE.equals(name) 4840 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4841 final long token = Binder.clearCallingIdentity(); 4842 try { 4843 if (sUserManager.isInitialized(userId)) { 4844 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4845 StorageManagerInternal.class); 4846 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4847 } 4848 } finally { 4849 Binder.restoreCallingIdentity(token); 4850 } 4851 } 4852 } 4853 4854 @Override 4855 public void revokeRuntimePermission(String packageName, String name, int userId) { 4856 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4857 } 4858 4859 private void revokeRuntimePermission(String packageName, String name, int userId, 4860 boolean overridePolicy) { 4861 if (!sUserManager.exists(userId)) { 4862 Log.e(TAG, "No such user:" + userId); 4863 return; 4864 } 4865 4866 mContext.enforceCallingOrSelfPermission( 4867 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4868 "revokeRuntimePermission"); 4869 4870 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4871 true /* requireFullPermission */, true /* checkShell */, 4872 "revokeRuntimePermission"); 4873 4874 final int appId; 4875 4876 synchronized (mPackages) { 4877 final PackageParser.Package pkg = mPackages.get(packageName); 4878 if (pkg == null) { 4879 throw new IllegalArgumentException("Unknown package: " + packageName); 4880 } 4881 4882 final BasePermission bp = mSettings.mPermissions.get(name); 4883 if (bp == null) { 4884 throw new IllegalArgumentException("Unknown permission: " + name); 4885 } 4886 4887 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4888 4889 // If a permission review is required for legacy apps we represent 4890 // their permissions as always granted runtime ones since we need 4891 // to keep the review required permission flag per user while an 4892 // install permission's state is shared across all users. 4893 if (mPermissionReviewRequired 4894 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4895 && bp.isRuntime()) { 4896 return; 4897 } 4898 4899 SettingBase sb = (SettingBase) pkg.mExtras; 4900 if (sb == null) { 4901 throw new IllegalArgumentException("Unknown package: " + packageName); 4902 } 4903 4904 final PermissionsState permissionsState = sb.getPermissionsState(); 4905 4906 final int flags = permissionsState.getPermissionFlags(name, userId); 4907 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4908 throw new SecurityException("Cannot revoke system fixed permission " 4909 + name + " for package " + packageName); 4910 } 4911 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4912 throw new SecurityException("Cannot revoke policy fixed permission " 4913 + name + " for package " + packageName); 4914 } 4915 4916 if (bp.isDevelopment()) { 4917 // Development permissions must be handled specially, since they are not 4918 // normal runtime permissions. For now they apply to all users. 4919 if (permissionsState.revokeInstallPermission(bp) != 4920 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4921 scheduleWriteSettingsLocked(); 4922 } 4923 return; 4924 } 4925 4926 if (permissionsState.revokeRuntimePermission(bp, userId) == 4927 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4928 return; 4929 } 4930 4931 if (bp.isRuntime()) { 4932 logPermissionRevoked(mContext, name, packageName); 4933 } 4934 4935 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4936 4937 // Critical, after this call app should never have the permission. 4938 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4939 4940 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4941 } 4942 4943 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4944 } 4945 4946 /** 4947 * Get the first event id for the permission. 4948 * 4949 * <p>There are four events for each permission: <ul> 4950 * <li>Request permission: first id + 0</li> 4951 * <li>Grant permission: first id + 1</li> 4952 * <li>Request for permission denied: first id + 2</li> 4953 * <li>Revoke permission: first id + 3</li> 4954 * </ul></p> 4955 * 4956 * @param name name of the permission 4957 * 4958 * @return The first event id for the permission 4959 */ 4960 private static int getBaseEventId(@NonNull String name) { 4961 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4962 4963 if (eventIdIndex == -1) { 4964 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4965 || "user".equals(Build.TYPE)) { 4966 Log.i(TAG, "Unknown permission " + name); 4967 4968 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4969 } else { 4970 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4971 // 4972 // Also update 4973 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4974 // - metrics_constants.proto 4975 throw new IllegalStateException("Unknown permission " + name); 4976 } 4977 } 4978 4979 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4980 } 4981 4982 /** 4983 * Log that a permission was revoked. 4984 * 4985 * @param context Context of the caller 4986 * @param name name of the permission 4987 * @param packageName package permission if for 4988 */ 4989 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4990 @NonNull String packageName) { 4991 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4992 } 4993 4994 /** 4995 * Log that a permission request was granted. 4996 * 4997 * @param context Context of the caller 4998 * @param name name of the permission 4999 * @param packageName package permission if for 5000 */ 5001 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5002 @NonNull String packageName) { 5003 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5004 } 5005 5006 @Override 5007 public void resetRuntimePermissions() { 5008 mContext.enforceCallingOrSelfPermission( 5009 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5010 "revokeRuntimePermission"); 5011 5012 int callingUid = Binder.getCallingUid(); 5013 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5014 mContext.enforceCallingOrSelfPermission( 5015 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5016 "resetRuntimePermissions"); 5017 } 5018 5019 synchronized (mPackages) { 5020 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5021 for (int userId : UserManagerService.getInstance().getUserIds()) { 5022 final int packageCount = mPackages.size(); 5023 for (int i = 0; i < packageCount; i++) { 5024 PackageParser.Package pkg = mPackages.valueAt(i); 5025 if (!(pkg.mExtras instanceof PackageSetting)) { 5026 continue; 5027 } 5028 PackageSetting ps = (PackageSetting) pkg.mExtras; 5029 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5030 } 5031 } 5032 } 5033 } 5034 5035 @Override 5036 public int getPermissionFlags(String name, String packageName, int userId) { 5037 if (!sUserManager.exists(userId)) { 5038 return 0; 5039 } 5040 5041 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5042 5043 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5044 true /* requireFullPermission */, false /* checkShell */, 5045 "getPermissionFlags"); 5046 5047 synchronized (mPackages) { 5048 final PackageParser.Package pkg = mPackages.get(packageName); 5049 if (pkg == null) { 5050 return 0; 5051 } 5052 5053 final BasePermission bp = mSettings.mPermissions.get(name); 5054 if (bp == null) { 5055 return 0; 5056 } 5057 5058 SettingBase sb = (SettingBase) pkg.mExtras; 5059 if (sb == null) { 5060 return 0; 5061 } 5062 5063 PermissionsState permissionsState = sb.getPermissionsState(); 5064 return permissionsState.getPermissionFlags(name, userId); 5065 } 5066 } 5067 5068 @Override 5069 public void updatePermissionFlags(String name, String packageName, int flagMask, 5070 int flagValues, int userId) { 5071 if (!sUserManager.exists(userId)) { 5072 return; 5073 } 5074 5075 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5076 5077 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5078 true /* requireFullPermission */, true /* checkShell */, 5079 "updatePermissionFlags"); 5080 5081 // Only the system can change these flags and nothing else. 5082 if (getCallingUid() != Process.SYSTEM_UID) { 5083 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5084 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5085 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5086 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5087 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5088 } 5089 5090 synchronized (mPackages) { 5091 final PackageParser.Package pkg = mPackages.get(packageName); 5092 if (pkg == null) { 5093 throw new IllegalArgumentException("Unknown package: " + packageName); 5094 } 5095 5096 final BasePermission bp = mSettings.mPermissions.get(name); 5097 if (bp == null) { 5098 throw new IllegalArgumentException("Unknown permission: " + name); 5099 } 5100 5101 SettingBase sb = (SettingBase) pkg.mExtras; 5102 if (sb == null) { 5103 throw new IllegalArgumentException("Unknown package: " + packageName); 5104 } 5105 5106 PermissionsState permissionsState = sb.getPermissionsState(); 5107 5108 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5109 5110 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5111 // Install and runtime permissions are stored in different places, 5112 // so figure out what permission changed and persist the change. 5113 if (permissionsState.getInstallPermissionState(name) != null) { 5114 scheduleWriteSettingsLocked(); 5115 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5116 || hadState) { 5117 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5118 } 5119 } 5120 } 5121 } 5122 5123 /** 5124 * Update the permission flags for all packages and runtime permissions of a user in order 5125 * to allow device or profile owner to remove POLICY_FIXED. 5126 */ 5127 @Override 5128 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5129 if (!sUserManager.exists(userId)) { 5130 return; 5131 } 5132 5133 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5134 5135 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5136 true /* requireFullPermission */, true /* checkShell */, 5137 "updatePermissionFlagsForAllApps"); 5138 5139 // Only the system can change system fixed flags. 5140 if (getCallingUid() != Process.SYSTEM_UID) { 5141 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5142 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5143 } 5144 5145 synchronized (mPackages) { 5146 boolean changed = false; 5147 final int packageCount = mPackages.size(); 5148 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5149 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5150 SettingBase sb = (SettingBase) pkg.mExtras; 5151 if (sb == null) { 5152 continue; 5153 } 5154 PermissionsState permissionsState = sb.getPermissionsState(); 5155 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5156 userId, flagMask, flagValues); 5157 } 5158 if (changed) { 5159 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5160 } 5161 } 5162 } 5163 5164 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5165 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5166 != PackageManager.PERMISSION_GRANTED 5167 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5168 != PackageManager.PERMISSION_GRANTED) { 5169 throw new SecurityException(message + " requires " 5170 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5171 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5172 } 5173 } 5174 5175 @Override 5176 public boolean shouldShowRequestPermissionRationale(String permissionName, 5177 String packageName, int userId) { 5178 if (UserHandle.getCallingUserId() != userId) { 5179 mContext.enforceCallingPermission( 5180 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5181 "canShowRequestPermissionRationale for user " + userId); 5182 } 5183 5184 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5185 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5186 return false; 5187 } 5188 5189 if (checkPermission(permissionName, packageName, userId) 5190 == PackageManager.PERMISSION_GRANTED) { 5191 return false; 5192 } 5193 5194 final int flags; 5195 5196 final long identity = Binder.clearCallingIdentity(); 5197 try { 5198 flags = getPermissionFlags(permissionName, 5199 packageName, userId); 5200 } finally { 5201 Binder.restoreCallingIdentity(identity); 5202 } 5203 5204 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5205 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5206 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5207 5208 if ((flags & fixedFlags) != 0) { 5209 return false; 5210 } 5211 5212 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5213 } 5214 5215 @Override 5216 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5217 mContext.enforceCallingOrSelfPermission( 5218 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5219 "addOnPermissionsChangeListener"); 5220 5221 synchronized (mPackages) { 5222 mOnPermissionChangeListeners.addListenerLocked(listener); 5223 } 5224 } 5225 5226 @Override 5227 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5228 synchronized (mPackages) { 5229 mOnPermissionChangeListeners.removeListenerLocked(listener); 5230 } 5231 } 5232 5233 @Override 5234 public boolean isProtectedBroadcast(String actionName) { 5235 synchronized (mPackages) { 5236 if (mProtectedBroadcasts.contains(actionName)) { 5237 return true; 5238 } else if (actionName != null) { 5239 // TODO: remove these terrible hacks 5240 if (actionName.startsWith("android.net.netmon.lingerExpired") 5241 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5242 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5243 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5244 return true; 5245 } 5246 } 5247 } 5248 return false; 5249 } 5250 5251 @Override 5252 public int checkSignatures(String pkg1, String pkg2) { 5253 synchronized (mPackages) { 5254 final PackageParser.Package p1 = mPackages.get(pkg1); 5255 final PackageParser.Package p2 = mPackages.get(pkg2); 5256 if (p1 == null || p1.mExtras == null 5257 || p2 == null || p2.mExtras == null) { 5258 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5259 } 5260 return compareSignatures(p1.mSignatures, p2.mSignatures); 5261 } 5262 } 5263 5264 @Override 5265 public int checkUidSignatures(int uid1, int uid2) { 5266 // Map to base uids. 5267 uid1 = UserHandle.getAppId(uid1); 5268 uid2 = UserHandle.getAppId(uid2); 5269 // reader 5270 synchronized (mPackages) { 5271 Signature[] s1; 5272 Signature[] s2; 5273 Object obj = mSettings.getUserIdLPr(uid1); 5274 if (obj != null) { 5275 if (obj instanceof SharedUserSetting) { 5276 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5277 } else if (obj instanceof PackageSetting) { 5278 s1 = ((PackageSetting)obj).signatures.mSignatures; 5279 } else { 5280 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5281 } 5282 } else { 5283 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5284 } 5285 obj = mSettings.getUserIdLPr(uid2); 5286 if (obj != null) { 5287 if (obj instanceof SharedUserSetting) { 5288 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5289 } else if (obj instanceof PackageSetting) { 5290 s2 = ((PackageSetting)obj).signatures.mSignatures; 5291 } else { 5292 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5293 } 5294 } else { 5295 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5296 } 5297 return compareSignatures(s1, s2); 5298 } 5299 } 5300 5301 /** 5302 * This method should typically only be used when granting or revoking 5303 * permissions, since the app may immediately restart after this call. 5304 * <p> 5305 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5306 * guard your work against the app being relaunched. 5307 */ 5308 private void killUid(int appId, int userId, String reason) { 5309 final long identity = Binder.clearCallingIdentity(); 5310 try { 5311 IActivityManager am = ActivityManager.getService(); 5312 if (am != null) { 5313 try { 5314 am.killUid(appId, userId, reason); 5315 } catch (RemoteException e) { 5316 /* ignore - same process */ 5317 } 5318 } 5319 } finally { 5320 Binder.restoreCallingIdentity(identity); 5321 } 5322 } 5323 5324 /** 5325 * Compares two sets of signatures. Returns: 5326 * <br /> 5327 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5328 * <br /> 5329 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5330 * <br /> 5331 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5332 * <br /> 5333 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5334 * <br /> 5335 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5336 */ 5337 static int compareSignatures(Signature[] s1, Signature[] s2) { 5338 if (s1 == null) { 5339 return s2 == null 5340 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5341 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5342 } 5343 5344 if (s2 == null) { 5345 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5346 } 5347 5348 if (s1.length != s2.length) { 5349 return PackageManager.SIGNATURE_NO_MATCH; 5350 } 5351 5352 // Since both signature sets are of size 1, we can compare without HashSets. 5353 if (s1.length == 1) { 5354 return s1[0].equals(s2[0]) ? 5355 PackageManager.SIGNATURE_MATCH : 5356 PackageManager.SIGNATURE_NO_MATCH; 5357 } 5358 5359 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5360 for (Signature sig : s1) { 5361 set1.add(sig); 5362 } 5363 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5364 for (Signature sig : s2) { 5365 set2.add(sig); 5366 } 5367 // Make sure s2 contains all signatures in s1. 5368 if (set1.equals(set2)) { 5369 return PackageManager.SIGNATURE_MATCH; 5370 } 5371 return PackageManager.SIGNATURE_NO_MATCH; 5372 } 5373 5374 /** 5375 * If the database version for this type of package (internal storage or 5376 * external storage) is less than the version where package signatures 5377 * were updated, return true. 5378 */ 5379 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5380 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5381 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5382 } 5383 5384 /** 5385 * Used for backward compatibility to make sure any packages with 5386 * certificate chains get upgraded to the new style. {@code existingSigs} 5387 * will be in the old format (since they were stored on disk from before the 5388 * system upgrade) and {@code scannedSigs} will be in the newer format. 5389 */ 5390 private int compareSignaturesCompat(PackageSignatures existingSigs, 5391 PackageParser.Package scannedPkg) { 5392 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5393 return PackageManager.SIGNATURE_NO_MATCH; 5394 } 5395 5396 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5397 for (Signature sig : existingSigs.mSignatures) { 5398 existingSet.add(sig); 5399 } 5400 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5401 for (Signature sig : scannedPkg.mSignatures) { 5402 try { 5403 Signature[] chainSignatures = sig.getChainSignatures(); 5404 for (Signature chainSig : chainSignatures) { 5405 scannedCompatSet.add(chainSig); 5406 } 5407 } catch (CertificateEncodingException e) { 5408 scannedCompatSet.add(sig); 5409 } 5410 } 5411 /* 5412 * Make sure the expanded scanned set contains all signatures in the 5413 * existing one. 5414 */ 5415 if (scannedCompatSet.equals(existingSet)) { 5416 // Migrate the old signatures to the new scheme. 5417 existingSigs.assignSignatures(scannedPkg.mSignatures); 5418 // The new KeySets will be re-added later in the scanning process. 5419 synchronized (mPackages) { 5420 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5421 } 5422 return PackageManager.SIGNATURE_MATCH; 5423 } 5424 return PackageManager.SIGNATURE_NO_MATCH; 5425 } 5426 5427 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5428 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5429 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5430 } 5431 5432 private int compareSignaturesRecover(PackageSignatures existingSigs, 5433 PackageParser.Package scannedPkg) { 5434 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5435 return PackageManager.SIGNATURE_NO_MATCH; 5436 } 5437 5438 String msg = null; 5439 try { 5440 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5441 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5442 + scannedPkg.packageName); 5443 return PackageManager.SIGNATURE_MATCH; 5444 } 5445 } catch (CertificateException e) { 5446 msg = e.getMessage(); 5447 } 5448 5449 logCriticalInfo(Log.INFO, 5450 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5451 return PackageManager.SIGNATURE_NO_MATCH; 5452 } 5453 5454 @Override 5455 public List<String> getAllPackages() { 5456 synchronized (mPackages) { 5457 return new ArrayList<String>(mPackages.keySet()); 5458 } 5459 } 5460 5461 @Override 5462 public String[] getPackagesForUid(int uid) { 5463 final int userId = UserHandle.getUserId(uid); 5464 uid = UserHandle.getAppId(uid); 5465 // reader 5466 synchronized (mPackages) { 5467 Object obj = mSettings.getUserIdLPr(uid); 5468 if (obj instanceof SharedUserSetting) { 5469 final SharedUserSetting sus = (SharedUserSetting) obj; 5470 final int N = sus.packages.size(); 5471 String[] res = new String[N]; 5472 final Iterator<PackageSetting> it = sus.packages.iterator(); 5473 int i = 0; 5474 while (it.hasNext()) { 5475 PackageSetting ps = it.next(); 5476 if (ps.getInstalled(userId)) { 5477 res[i++] = ps.name; 5478 } else { 5479 res = ArrayUtils.removeElement(String.class, res, res[i]); 5480 } 5481 } 5482 return res; 5483 } else if (obj instanceof PackageSetting) { 5484 final PackageSetting ps = (PackageSetting) obj; 5485 if (ps.getInstalled(userId)) { 5486 return new String[]{ps.name}; 5487 } 5488 } 5489 } 5490 return null; 5491 } 5492 5493 @Override 5494 public String getNameForUid(int uid) { 5495 // reader 5496 synchronized (mPackages) { 5497 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5498 if (obj instanceof SharedUserSetting) { 5499 final SharedUserSetting sus = (SharedUserSetting) obj; 5500 return sus.name + ":" + sus.userId; 5501 } else if (obj instanceof PackageSetting) { 5502 final PackageSetting ps = (PackageSetting) obj; 5503 return ps.name; 5504 } 5505 } 5506 return null; 5507 } 5508 5509 @Override 5510 public int getUidForSharedUser(String sharedUserName) { 5511 if(sharedUserName == null) { 5512 return -1; 5513 } 5514 // reader 5515 synchronized (mPackages) { 5516 SharedUserSetting suid; 5517 try { 5518 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5519 if (suid != null) { 5520 return suid.userId; 5521 } 5522 } catch (PackageManagerException ignore) { 5523 // can't happen, but, still need to catch it 5524 } 5525 return -1; 5526 } 5527 } 5528 5529 @Override 5530 public int getFlagsForUid(int uid) { 5531 synchronized (mPackages) { 5532 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5533 if (obj instanceof SharedUserSetting) { 5534 final SharedUserSetting sus = (SharedUserSetting) obj; 5535 return sus.pkgFlags; 5536 } else if (obj instanceof PackageSetting) { 5537 final PackageSetting ps = (PackageSetting) obj; 5538 return ps.pkgFlags; 5539 } 5540 } 5541 return 0; 5542 } 5543 5544 @Override 5545 public int getPrivateFlagsForUid(int uid) { 5546 synchronized (mPackages) { 5547 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5548 if (obj instanceof SharedUserSetting) { 5549 final SharedUserSetting sus = (SharedUserSetting) obj; 5550 return sus.pkgPrivateFlags; 5551 } else if (obj instanceof PackageSetting) { 5552 final PackageSetting ps = (PackageSetting) obj; 5553 return ps.pkgPrivateFlags; 5554 } 5555 } 5556 return 0; 5557 } 5558 5559 @Override 5560 public boolean isUidPrivileged(int uid) { 5561 uid = UserHandle.getAppId(uid); 5562 // reader 5563 synchronized (mPackages) { 5564 Object obj = mSettings.getUserIdLPr(uid); 5565 if (obj instanceof SharedUserSetting) { 5566 final SharedUserSetting sus = (SharedUserSetting) obj; 5567 final Iterator<PackageSetting> it = sus.packages.iterator(); 5568 while (it.hasNext()) { 5569 if (it.next().isPrivileged()) { 5570 return true; 5571 } 5572 } 5573 } else if (obj instanceof PackageSetting) { 5574 final PackageSetting ps = (PackageSetting) obj; 5575 return ps.isPrivileged(); 5576 } 5577 } 5578 return false; 5579 } 5580 5581 @Override 5582 public String[] getAppOpPermissionPackages(String permissionName) { 5583 synchronized (mPackages) { 5584 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5585 if (pkgs == null) { 5586 return null; 5587 } 5588 return pkgs.toArray(new String[pkgs.size()]); 5589 } 5590 } 5591 5592 @Override 5593 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5594 int flags, int userId) { 5595 return resolveIntentInternal( 5596 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5597 } 5598 5599 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5600 int flags, int userId, boolean includeInstantApps) { 5601 try { 5602 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5603 5604 if (!sUserManager.exists(userId)) return null; 5605 final int callingUid = Binder.getCallingUid(); 5606 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 5607 enforceCrossUserPermission(callingUid, userId, 5608 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5609 5610 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5611 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5612 flags, userId, includeInstantApps); 5613 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5614 5615 final ResolveInfo bestChoice = 5616 chooseBestActivity(intent, resolvedType, flags, query, userId); 5617 return bestChoice; 5618 } finally { 5619 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5620 } 5621 } 5622 5623 @Override 5624 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5625 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5626 throw new SecurityException( 5627 "findPersistentPreferredActivity can only be run by the system"); 5628 } 5629 if (!sUserManager.exists(userId)) { 5630 return null; 5631 } 5632 final int callingUid = Binder.getCallingUid(); 5633 intent = updateIntentForResolve(intent); 5634 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5635 final int flags = updateFlagsForResolve( 5636 0, userId, intent, callingUid, false /*includeInstantApps*/); 5637 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5638 userId); 5639 synchronized (mPackages) { 5640 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5641 userId); 5642 } 5643 } 5644 5645 @Override 5646 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5647 IntentFilter filter, int match, ComponentName activity) { 5648 final int userId = UserHandle.getCallingUserId(); 5649 if (DEBUG_PREFERRED) { 5650 Log.v(TAG, "setLastChosenActivity intent=" + intent 5651 + " resolvedType=" + resolvedType 5652 + " flags=" + flags 5653 + " filter=" + filter 5654 + " match=" + match 5655 + " activity=" + activity); 5656 filter.dump(new PrintStreamPrinter(System.out), " "); 5657 } 5658 intent.setComponent(null); 5659 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5660 userId); 5661 // Find any earlier preferred or last chosen entries and nuke them 5662 findPreferredActivity(intent, resolvedType, 5663 flags, query, 0, false, true, false, userId); 5664 // Add the new activity as the last chosen for this filter 5665 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5666 "Setting last chosen"); 5667 } 5668 5669 @Override 5670 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5671 final int userId = UserHandle.getCallingUserId(); 5672 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5673 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5674 userId); 5675 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5676 false, false, false, userId); 5677 } 5678 5679 /** 5680 * Returns whether or not instant apps have been disabled remotely. 5681 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5682 * held. Otherwise we run the risk of deadlock. 5683 */ 5684 private boolean isEphemeralDisabled() { 5685 // ephemeral apps have been disabled across the board 5686 if (DISABLE_EPHEMERAL_APPS) { 5687 return true; 5688 } 5689 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5690 if (!mSystemReady) { 5691 return true; 5692 } 5693 // we can't get a content resolver until the system is ready; these checks must happen last 5694 final ContentResolver resolver = mContext.getContentResolver(); 5695 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5696 return true; 5697 } 5698 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5699 } 5700 5701 private boolean isEphemeralAllowed( 5702 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5703 boolean skipPackageCheck) { 5704 final int callingUser = UserHandle.getCallingUserId(); 5705 if (callingUser != UserHandle.USER_SYSTEM) { 5706 return false; 5707 } 5708 if (mInstantAppResolverConnection == null) { 5709 return false; 5710 } 5711 if (mInstantAppInstallerComponent == null) { 5712 return false; 5713 } 5714 if (intent.getComponent() != null) { 5715 return false; 5716 } 5717 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5718 return false; 5719 } 5720 if (!skipPackageCheck && intent.getPackage() != null) { 5721 return false; 5722 } 5723 final boolean isWebUri = hasWebURI(intent); 5724 if (!isWebUri || intent.getData().getHost() == null) { 5725 return false; 5726 } 5727 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5728 // Or if there's already an ephemeral app installed that handles the action 5729 synchronized (mPackages) { 5730 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5731 for (int n = 0; n < count; n++) { 5732 ResolveInfo info = resolvedActivities.get(n); 5733 String packageName = info.activityInfo.packageName; 5734 PackageSetting ps = mSettings.mPackages.get(packageName); 5735 if (ps != null) { 5736 // Try to get the status from User settings first 5737 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5738 int status = (int) (packedStatus >> 32); 5739 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5740 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5741 if (DEBUG_EPHEMERAL) { 5742 Slog.v(TAG, "DENY ephemeral apps;" 5743 + " pkg: " + packageName + ", status: " + status); 5744 } 5745 return false; 5746 } 5747 if (ps.getInstantApp(userId)) { 5748 if (DEBUG_EPHEMERAL) { 5749 Slog.v(TAG, "DENY instant app installed;" 5750 + " pkg: " + packageName); 5751 } 5752 return false; 5753 } 5754 } 5755 } 5756 } 5757 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5758 return true; 5759 } 5760 5761 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5762 Intent origIntent, String resolvedType, String callingPackage, 5763 int userId) { 5764 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5765 new InstantAppRequest(responseObj, origIntent, resolvedType, 5766 callingPackage, userId)); 5767 mHandler.sendMessage(msg); 5768 } 5769 5770 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5771 int flags, List<ResolveInfo> query, int userId) { 5772 if (query != null) { 5773 final int N = query.size(); 5774 if (N == 1) { 5775 return query.get(0); 5776 } else if (N > 1) { 5777 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5778 // If there is more than one activity with the same priority, 5779 // then let the user decide between them. 5780 ResolveInfo r0 = query.get(0); 5781 ResolveInfo r1 = query.get(1); 5782 if (DEBUG_INTENT_MATCHING || debug) { 5783 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5784 + r1.activityInfo.name + "=" + r1.priority); 5785 } 5786 // If the first activity has a higher priority, or a different 5787 // default, then it is always desirable to pick it. 5788 if (r0.priority != r1.priority 5789 || r0.preferredOrder != r1.preferredOrder 5790 || r0.isDefault != r1.isDefault) { 5791 return query.get(0); 5792 } 5793 // If we have saved a preference for a preferred activity for 5794 // this Intent, use that. 5795 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5796 flags, query, r0.priority, true, false, debug, userId); 5797 if (ri != null) { 5798 return ri; 5799 } 5800 // If we have an ephemeral app, use it 5801 for (int i = 0; i < N; i++) { 5802 ri = query.get(i); 5803 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5804 return ri; 5805 } 5806 } 5807 ri = new ResolveInfo(mResolveInfo); 5808 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5809 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5810 // If all of the options come from the same package, show the application's 5811 // label and icon instead of the generic resolver's. 5812 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5813 // and then throw away the ResolveInfo itself, meaning that the caller loses 5814 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5815 // a fallback for this case; we only set the target package's resources on 5816 // the ResolveInfo, not the ActivityInfo. 5817 final String intentPackage = intent.getPackage(); 5818 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5819 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5820 ri.resolvePackageName = intentPackage; 5821 if (userNeedsBadging(userId)) { 5822 ri.noResourceId = true; 5823 } else { 5824 ri.icon = appi.icon; 5825 } 5826 ri.iconResourceId = appi.icon; 5827 ri.labelRes = appi.labelRes; 5828 } 5829 ri.activityInfo.applicationInfo = new ApplicationInfo( 5830 ri.activityInfo.applicationInfo); 5831 if (userId != 0) { 5832 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5833 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5834 } 5835 // Make sure that the resolver is displayable in car mode 5836 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5837 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5838 return ri; 5839 } 5840 } 5841 return null; 5842 } 5843 5844 /** 5845 * Return true if the given list is not empty and all of its contents have 5846 * an activityInfo with the given package name. 5847 */ 5848 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5849 if (ArrayUtils.isEmpty(list)) { 5850 return false; 5851 } 5852 for (int i = 0, N = list.size(); i < N; i++) { 5853 final ResolveInfo ri = list.get(i); 5854 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5855 if (ai == null || !packageName.equals(ai.packageName)) { 5856 return false; 5857 } 5858 } 5859 return true; 5860 } 5861 5862 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5863 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5864 final int N = query.size(); 5865 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5866 .get(userId); 5867 // Get the list of persistent preferred activities that handle the intent 5868 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5869 List<PersistentPreferredActivity> pprefs = ppir != null 5870 ? ppir.queryIntent(intent, resolvedType, 5871 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5872 userId) 5873 : null; 5874 if (pprefs != null && pprefs.size() > 0) { 5875 final int M = pprefs.size(); 5876 for (int i=0; i<M; i++) { 5877 final PersistentPreferredActivity ppa = pprefs.get(i); 5878 if (DEBUG_PREFERRED || debug) { 5879 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5880 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5881 + "\n component=" + ppa.mComponent); 5882 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5883 } 5884 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5885 flags | MATCH_DISABLED_COMPONENTS, userId); 5886 if (DEBUG_PREFERRED || debug) { 5887 Slog.v(TAG, "Found persistent preferred activity:"); 5888 if (ai != null) { 5889 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5890 } else { 5891 Slog.v(TAG, " null"); 5892 } 5893 } 5894 if (ai == null) { 5895 // This previously registered persistent preferred activity 5896 // component is no longer known. Ignore it and do NOT remove it. 5897 continue; 5898 } 5899 for (int j=0; j<N; j++) { 5900 final ResolveInfo ri = query.get(j); 5901 if (!ri.activityInfo.applicationInfo.packageName 5902 .equals(ai.applicationInfo.packageName)) { 5903 continue; 5904 } 5905 if (!ri.activityInfo.name.equals(ai.name)) { 5906 continue; 5907 } 5908 // Found a persistent preference that can handle the intent. 5909 if (DEBUG_PREFERRED || debug) { 5910 Slog.v(TAG, "Returning persistent preferred activity: " + 5911 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5912 } 5913 return ri; 5914 } 5915 } 5916 } 5917 return null; 5918 } 5919 5920 // TODO: handle preferred activities missing while user has amnesia 5921 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5922 List<ResolveInfo> query, int priority, boolean always, 5923 boolean removeMatches, boolean debug, int userId) { 5924 if (!sUserManager.exists(userId)) return null; 5925 final int callingUid = Binder.getCallingUid(); 5926 flags = updateFlagsForResolve( 5927 flags, userId, intent, callingUid, false /*includeInstantApps*/); 5928 intent = updateIntentForResolve(intent); 5929 // writer 5930 synchronized (mPackages) { 5931 // Try to find a matching persistent preferred activity. 5932 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5933 debug, userId); 5934 5935 // If a persistent preferred activity matched, use it. 5936 if (pri != null) { 5937 return pri; 5938 } 5939 5940 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5941 // Get the list of preferred activities that handle the intent 5942 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5943 List<PreferredActivity> prefs = pir != null 5944 ? pir.queryIntent(intent, resolvedType, 5945 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5946 userId) 5947 : null; 5948 if (prefs != null && prefs.size() > 0) { 5949 boolean changed = false; 5950 try { 5951 // First figure out how good the original match set is. 5952 // We will only allow preferred activities that came 5953 // from the same match quality. 5954 int match = 0; 5955 5956 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5957 5958 final int N = query.size(); 5959 for (int j=0; j<N; j++) { 5960 final ResolveInfo ri = query.get(j); 5961 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5962 + ": 0x" + Integer.toHexString(match)); 5963 if (ri.match > match) { 5964 match = ri.match; 5965 } 5966 } 5967 5968 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5969 + Integer.toHexString(match)); 5970 5971 match &= IntentFilter.MATCH_CATEGORY_MASK; 5972 final int M = prefs.size(); 5973 for (int i=0; i<M; i++) { 5974 final PreferredActivity pa = prefs.get(i); 5975 if (DEBUG_PREFERRED || debug) { 5976 Slog.v(TAG, "Checking PreferredActivity ds=" 5977 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5978 + "\n component=" + pa.mPref.mComponent); 5979 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5980 } 5981 if (pa.mPref.mMatch != match) { 5982 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5983 + Integer.toHexString(pa.mPref.mMatch)); 5984 continue; 5985 } 5986 // If it's not an "always" type preferred activity and that's what we're 5987 // looking for, skip it. 5988 if (always && !pa.mPref.mAlways) { 5989 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5990 continue; 5991 } 5992 final ActivityInfo ai = getActivityInfo( 5993 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5994 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5995 userId); 5996 if (DEBUG_PREFERRED || debug) { 5997 Slog.v(TAG, "Found preferred activity:"); 5998 if (ai != null) { 5999 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6000 } else { 6001 Slog.v(TAG, " null"); 6002 } 6003 } 6004 if (ai == null) { 6005 // This previously registered preferred activity 6006 // component is no longer known. Most likely an update 6007 // to the app was installed and in the new version this 6008 // component no longer exists. Clean it up by removing 6009 // it from the preferred activities list, and skip it. 6010 Slog.w(TAG, "Removing dangling preferred activity: " 6011 + pa.mPref.mComponent); 6012 pir.removeFilter(pa); 6013 changed = true; 6014 continue; 6015 } 6016 for (int j=0; j<N; j++) { 6017 final ResolveInfo ri = query.get(j); 6018 if (!ri.activityInfo.applicationInfo.packageName 6019 .equals(ai.applicationInfo.packageName)) { 6020 continue; 6021 } 6022 if (!ri.activityInfo.name.equals(ai.name)) { 6023 continue; 6024 } 6025 6026 if (removeMatches) { 6027 pir.removeFilter(pa); 6028 changed = true; 6029 if (DEBUG_PREFERRED) { 6030 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6031 } 6032 break; 6033 } 6034 6035 // Okay we found a previously set preferred or last chosen app. 6036 // If the result set is different from when this 6037 // was created, we need to clear it and re-ask the 6038 // user their preference, if we're looking for an "always" type entry. 6039 if (always && !pa.mPref.sameSet(query)) { 6040 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6041 + intent + " type " + resolvedType); 6042 if (DEBUG_PREFERRED) { 6043 Slog.v(TAG, "Removing preferred activity since set changed " 6044 + pa.mPref.mComponent); 6045 } 6046 pir.removeFilter(pa); 6047 // Re-add the filter as a "last chosen" entry (!always) 6048 PreferredActivity lastChosen = new PreferredActivity( 6049 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6050 pir.addFilter(lastChosen); 6051 changed = true; 6052 return null; 6053 } 6054 6055 // Yay! Either the set matched or we're looking for the last chosen 6056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6057 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6058 return ri; 6059 } 6060 } 6061 } finally { 6062 if (changed) { 6063 if (DEBUG_PREFERRED) { 6064 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6065 } 6066 scheduleWritePackageRestrictionsLocked(userId); 6067 } 6068 } 6069 } 6070 } 6071 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6072 return null; 6073 } 6074 6075 /* 6076 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6077 */ 6078 @Override 6079 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6080 int targetUserId) { 6081 mContext.enforceCallingOrSelfPermission( 6082 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6083 List<CrossProfileIntentFilter> matches = 6084 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6085 if (matches != null) { 6086 int size = matches.size(); 6087 for (int i = 0; i < size; i++) { 6088 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6089 } 6090 } 6091 if (hasWebURI(intent)) { 6092 // cross-profile app linking works only towards the parent. 6093 final int callingUid = Binder.getCallingUid(); 6094 final UserInfo parent = getProfileParent(sourceUserId); 6095 synchronized(mPackages) { 6096 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6097 false /*includeInstantApps*/); 6098 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6099 intent, resolvedType, flags, sourceUserId, parent.id); 6100 return xpDomainInfo != null; 6101 } 6102 } 6103 return false; 6104 } 6105 6106 private UserInfo getProfileParent(int userId) { 6107 final long identity = Binder.clearCallingIdentity(); 6108 try { 6109 return sUserManager.getProfileParent(userId); 6110 } finally { 6111 Binder.restoreCallingIdentity(identity); 6112 } 6113 } 6114 6115 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6116 String resolvedType, int userId) { 6117 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6118 if (resolver != null) { 6119 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6120 } 6121 return null; 6122 } 6123 6124 @Override 6125 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6126 String resolvedType, int flags, int userId) { 6127 try { 6128 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6129 6130 return new ParceledListSlice<>( 6131 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6132 } finally { 6133 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6134 } 6135 } 6136 6137 /** 6138 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6139 * instant, returns {@code null}. 6140 */ 6141 private String getInstantAppPackageName(int callingUid) { 6142 // If the caller is an isolated app use the owner's uid for the lookup. 6143 if (Process.isIsolated(callingUid)) { 6144 callingUid = mIsolatedOwners.get(callingUid); 6145 } 6146 final int appId = UserHandle.getAppId(callingUid); 6147 synchronized (mPackages) { 6148 final Object obj = mSettings.getUserIdLPr(appId); 6149 if (obj instanceof PackageSetting) { 6150 final PackageSetting ps = (PackageSetting) obj; 6151 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6152 return isInstantApp ? ps.pkg.packageName : null; 6153 } 6154 } 6155 return null; 6156 } 6157 6158 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6159 String resolvedType, int flags, int userId) { 6160 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6161 } 6162 6163 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6164 String resolvedType, int flags, int userId, boolean includeInstantApps) { 6165 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6166 final int callingUid = Binder.getCallingUid(); 6167 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6168 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 6169 enforceCrossUserPermission(callingUid, userId, 6170 false /* requireFullPermission */, false /* checkShell */, 6171 "query intent activities"); 6172 ComponentName comp = intent.getComponent(); 6173 if (comp == null) { 6174 if (intent.getSelector() != null) { 6175 intent = intent.getSelector(); 6176 comp = intent.getComponent(); 6177 } 6178 } 6179 6180 if (comp != null) { 6181 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6182 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6183 if (ai != null) { 6184 // When specifying an explicit component, we prevent the activity from being 6185 // used when either 1) the calling package is normal and the activity is within 6186 // an ephemeral application or 2) the calling package is ephemeral and the 6187 // activity is not visible to ephemeral applications. 6188 final boolean matchInstantApp = 6189 (flags & PackageManager.MATCH_INSTANT) != 0; 6190 final boolean matchVisibleToInstantAppOnly = 6191 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6192 final boolean isCallerInstantApp = 6193 instantAppPkgName != null; 6194 final boolean isTargetSameInstantApp = 6195 comp.getPackageName().equals(instantAppPkgName); 6196 final boolean isTargetInstantApp = 6197 (ai.applicationInfo.privateFlags 6198 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6199 final boolean isTargetHiddenFromInstantApp = 6200 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6201 final boolean blockResolution = 6202 !isTargetSameInstantApp 6203 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6204 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6205 && isTargetHiddenFromInstantApp)); 6206 if (!blockResolution) { 6207 final ResolveInfo ri = new ResolveInfo(); 6208 ri.activityInfo = ai; 6209 list.add(ri); 6210 } 6211 } 6212 return applyPostResolutionFilter(list, instantAppPkgName); 6213 } 6214 6215 // reader 6216 boolean sortResult = false; 6217 boolean addEphemeral = false; 6218 List<ResolveInfo> result; 6219 final String pkgName = intent.getPackage(); 6220 final boolean ephemeralDisabled = isEphemeralDisabled(); 6221 synchronized (mPackages) { 6222 if (pkgName == null) { 6223 List<CrossProfileIntentFilter> matchingFilters = 6224 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6225 // Check for results that need to skip the current profile. 6226 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6227 resolvedType, flags, userId); 6228 if (xpResolveInfo != null) { 6229 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6230 xpResult.add(xpResolveInfo); 6231 return applyPostResolutionFilter( 6232 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6233 } 6234 6235 // Check for results in the current profile. 6236 result = filterIfNotSystemUser(mActivities.queryIntent( 6237 intent, resolvedType, flags, userId), userId); 6238 addEphemeral = !ephemeralDisabled 6239 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6240 // Check for cross profile results. 6241 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6242 xpResolveInfo = queryCrossProfileIntents( 6243 matchingFilters, intent, resolvedType, flags, userId, 6244 hasNonNegativePriorityResult); 6245 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6246 boolean isVisibleToUser = filterIfNotSystemUser( 6247 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6248 if (isVisibleToUser) { 6249 result.add(xpResolveInfo); 6250 sortResult = true; 6251 } 6252 } 6253 if (hasWebURI(intent)) { 6254 CrossProfileDomainInfo xpDomainInfo = null; 6255 final UserInfo parent = getProfileParent(userId); 6256 if (parent != null) { 6257 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6258 flags, userId, parent.id); 6259 } 6260 if (xpDomainInfo != null) { 6261 if (xpResolveInfo != null) { 6262 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6263 // in the result. 6264 result.remove(xpResolveInfo); 6265 } 6266 if (result.size() == 0 && !addEphemeral) { 6267 // No result in current profile, but found candidate in parent user. 6268 // And we are not going to add emphemeral app, so we can return the 6269 // result straight away. 6270 result.add(xpDomainInfo.resolveInfo); 6271 return applyPostResolutionFilter(result, instantAppPkgName); 6272 } 6273 } else if (result.size() <= 1 && !addEphemeral) { 6274 // No result in parent user and <= 1 result in current profile, and we 6275 // are not going to add emphemeral app, so we can return the result without 6276 // further processing. 6277 return applyPostResolutionFilter(result, instantAppPkgName); 6278 } 6279 // We have more than one candidate (combining results from current and parent 6280 // profile), so we need filtering and sorting. 6281 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6282 intent, flags, result, xpDomainInfo, userId); 6283 sortResult = true; 6284 } 6285 } else { 6286 final PackageParser.Package pkg = mPackages.get(pkgName); 6287 if (pkg != null) { 6288 return applyPostResolutionFilter(filterIfNotSystemUser( 6289 mActivities.queryIntentForPackage( 6290 intent, resolvedType, flags, pkg.activities, userId), 6291 userId), instantAppPkgName); 6292 } else { 6293 // the caller wants to resolve for a particular package; however, there 6294 // were no installed results, so, try to find an ephemeral result 6295 addEphemeral = !ephemeralDisabled 6296 && isEphemeralAllowed( 6297 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6298 result = new ArrayList<ResolveInfo>(); 6299 } 6300 } 6301 } 6302 if (addEphemeral) { 6303 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6304 final InstantAppRequest requestObject = new InstantAppRequest( 6305 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6306 null /*callingPackage*/, userId); 6307 final AuxiliaryResolveInfo auxiliaryResponse = 6308 InstantAppResolver.doInstantAppResolutionPhaseOne( 6309 mContext, mInstantAppResolverConnection, requestObject); 6310 if (auxiliaryResponse != null) { 6311 if (DEBUG_EPHEMERAL) { 6312 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6313 } 6314 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6315 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6316 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6317 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6318 // make sure this resolver is the default 6319 ephemeralInstaller.isDefault = true; 6320 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6321 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6322 // add a non-generic filter 6323 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6324 ephemeralInstaller.filter.addDataPath( 6325 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6326 ephemeralInstaller.instantAppAvailable = true; 6327 result.add(ephemeralInstaller); 6328 } 6329 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6330 } 6331 if (sortResult) { 6332 Collections.sort(result, mResolvePrioritySorter); 6333 } 6334 return applyPostResolutionFilter(result, instantAppPkgName); 6335 } 6336 6337 private static class CrossProfileDomainInfo { 6338 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6339 ResolveInfo resolveInfo; 6340 /* Best domain verification status of the activities found in the other profile */ 6341 int bestDomainVerificationStatus; 6342 } 6343 6344 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6345 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6346 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6347 sourceUserId)) { 6348 return null; 6349 } 6350 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6351 resolvedType, flags, parentUserId); 6352 6353 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6354 return null; 6355 } 6356 CrossProfileDomainInfo result = null; 6357 int size = resultTargetUser.size(); 6358 for (int i = 0; i < size; i++) { 6359 ResolveInfo riTargetUser = resultTargetUser.get(i); 6360 // Intent filter verification is only for filters that specify a host. So don't return 6361 // those that handle all web uris. 6362 if (riTargetUser.handleAllWebDataURI) { 6363 continue; 6364 } 6365 String packageName = riTargetUser.activityInfo.packageName; 6366 PackageSetting ps = mSettings.mPackages.get(packageName); 6367 if (ps == null) { 6368 continue; 6369 } 6370 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6371 int status = (int)(verificationState >> 32); 6372 if (result == null) { 6373 result = new CrossProfileDomainInfo(); 6374 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6375 sourceUserId, parentUserId); 6376 result.bestDomainVerificationStatus = status; 6377 } else { 6378 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6379 result.bestDomainVerificationStatus); 6380 } 6381 } 6382 // Don't consider matches with status NEVER across profiles. 6383 if (result != null && result.bestDomainVerificationStatus 6384 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6385 return null; 6386 } 6387 return result; 6388 } 6389 6390 /** 6391 * Verification statuses are ordered from the worse to the best, except for 6392 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6393 */ 6394 private int bestDomainVerificationStatus(int status1, int status2) { 6395 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6396 return status2; 6397 } 6398 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6399 return status1; 6400 } 6401 return (int) MathUtils.max(status1, status2); 6402 } 6403 6404 private boolean isUserEnabled(int userId) { 6405 long callingId = Binder.clearCallingIdentity(); 6406 try { 6407 UserInfo userInfo = sUserManager.getUserInfo(userId); 6408 return userInfo != null && userInfo.isEnabled(); 6409 } finally { 6410 Binder.restoreCallingIdentity(callingId); 6411 } 6412 } 6413 6414 /** 6415 * Filter out activities with systemUserOnly flag set, when current user is not System. 6416 * 6417 * @return filtered list 6418 */ 6419 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6420 if (userId == UserHandle.USER_SYSTEM) { 6421 return resolveInfos; 6422 } 6423 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6424 ResolveInfo info = resolveInfos.get(i); 6425 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6426 resolveInfos.remove(i); 6427 } 6428 } 6429 return resolveInfos; 6430 } 6431 6432 /** 6433 * Filters out ephemeral activities. 6434 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6435 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6436 * 6437 * @param resolveInfos The pre-filtered list of resolved activities 6438 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6439 * is performed. 6440 * @return A filtered list of resolved activities. 6441 */ 6442 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6443 String ephemeralPkgName) { 6444 // TODO: When adding on-demand split support for non-instant apps, remove this check 6445 // and always apply post filtering 6446 if (ephemeralPkgName == null) { 6447 return resolveInfos; 6448 } 6449 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6450 final ResolveInfo info = resolveInfos.get(i); 6451 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6452 // allow activities that are defined in the provided package 6453 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6454 if (info.activityInfo.splitName != null 6455 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6456 info.activityInfo.splitName)) { 6457 // requested activity is defined in a split that hasn't been installed yet. 6458 // add the installer to the resolve list 6459 if (DEBUG_EPHEMERAL) { 6460 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6461 } 6462 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6463 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6464 info.activityInfo.packageName, info.activityInfo.splitName, 6465 info.activityInfo.applicationInfo.versionCode); 6466 // make sure this resolver is the default 6467 installerInfo.isDefault = true; 6468 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6469 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6470 // add a non-generic filter 6471 installerInfo.filter = new IntentFilter(); 6472 // load resources from the correct package 6473 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6474 resolveInfos.set(i, installerInfo); 6475 } 6476 continue; 6477 } 6478 // allow activities that have been explicitly exposed to ephemeral apps 6479 if (!isEphemeralApp 6480 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6481 continue; 6482 } 6483 resolveInfos.remove(i); 6484 } 6485 return resolveInfos; 6486 } 6487 6488 /** 6489 * @param resolveInfos list of resolve infos in descending priority order 6490 * @return if the list contains a resolve info with non-negative priority 6491 */ 6492 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6493 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6494 } 6495 6496 private static boolean hasWebURI(Intent intent) { 6497 if (intent.getData() == null) { 6498 return false; 6499 } 6500 final String scheme = intent.getScheme(); 6501 if (TextUtils.isEmpty(scheme)) { 6502 return false; 6503 } 6504 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6505 } 6506 6507 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6508 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6509 int userId) { 6510 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6511 6512 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6513 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6514 candidates.size()); 6515 } 6516 6517 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6518 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6519 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6520 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6521 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6522 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6523 6524 synchronized (mPackages) { 6525 final int count = candidates.size(); 6526 // First, try to use linked apps. Partition the candidates into four lists: 6527 // one for the final results, one for the "do not use ever", one for "undefined status" 6528 // and finally one for "browser app type". 6529 for (int n=0; n<count; n++) { 6530 ResolveInfo info = candidates.get(n); 6531 String packageName = info.activityInfo.packageName; 6532 PackageSetting ps = mSettings.mPackages.get(packageName); 6533 if (ps != null) { 6534 // Add to the special match all list (Browser use case) 6535 if (info.handleAllWebDataURI) { 6536 matchAllList.add(info); 6537 continue; 6538 } 6539 // Try to get the status from User settings first 6540 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6541 int status = (int)(packedStatus >> 32); 6542 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6543 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6544 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6545 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6546 + " : linkgen=" + linkGeneration); 6547 } 6548 // Use link-enabled generation as preferredOrder, i.e. 6549 // prefer newly-enabled over earlier-enabled. 6550 info.preferredOrder = linkGeneration; 6551 alwaysList.add(info); 6552 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6553 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6554 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6555 } 6556 neverList.add(info); 6557 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6558 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6559 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6560 } 6561 alwaysAskList.add(info); 6562 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6563 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6564 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6565 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6566 } 6567 undefinedList.add(info); 6568 } 6569 } 6570 } 6571 6572 // We'll want to include browser possibilities in a few cases 6573 boolean includeBrowser = false; 6574 6575 // First try to add the "always" resolution(s) for the current user, if any 6576 if (alwaysList.size() > 0) { 6577 result.addAll(alwaysList); 6578 } else { 6579 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6580 result.addAll(undefinedList); 6581 // Maybe add one for the other profile. 6582 if (xpDomainInfo != null && ( 6583 xpDomainInfo.bestDomainVerificationStatus 6584 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6585 result.add(xpDomainInfo.resolveInfo); 6586 } 6587 includeBrowser = true; 6588 } 6589 6590 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6591 // If there were 'always' entries their preferred order has been set, so we also 6592 // back that off to make the alternatives equivalent 6593 if (alwaysAskList.size() > 0) { 6594 for (ResolveInfo i : result) { 6595 i.preferredOrder = 0; 6596 } 6597 result.addAll(alwaysAskList); 6598 includeBrowser = true; 6599 } 6600 6601 if (includeBrowser) { 6602 // Also add browsers (all of them or only the default one) 6603 if (DEBUG_DOMAIN_VERIFICATION) { 6604 Slog.v(TAG, " ...including browsers in candidate set"); 6605 } 6606 if ((matchFlags & MATCH_ALL) != 0) { 6607 result.addAll(matchAllList); 6608 } else { 6609 // Browser/generic handling case. If there's a default browser, go straight 6610 // to that (but only if there is no other higher-priority match). 6611 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6612 int maxMatchPrio = 0; 6613 ResolveInfo defaultBrowserMatch = null; 6614 final int numCandidates = matchAllList.size(); 6615 for (int n = 0; n < numCandidates; n++) { 6616 ResolveInfo info = matchAllList.get(n); 6617 // track the highest overall match priority... 6618 if (info.priority > maxMatchPrio) { 6619 maxMatchPrio = info.priority; 6620 } 6621 // ...and the highest-priority default browser match 6622 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6623 if (defaultBrowserMatch == null 6624 || (defaultBrowserMatch.priority < info.priority)) { 6625 if (debug) { 6626 Slog.v(TAG, "Considering default browser match " + info); 6627 } 6628 defaultBrowserMatch = info; 6629 } 6630 } 6631 } 6632 if (defaultBrowserMatch != null 6633 && defaultBrowserMatch.priority >= maxMatchPrio 6634 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6635 { 6636 if (debug) { 6637 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6638 } 6639 result.add(defaultBrowserMatch); 6640 } else { 6641 result.addAll(matchAllList); 6642 } 6643 } 6644 6645 // If there is nothing selected, add all candidates and remove the ones that the user 6646 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6647 if (result.size() == 0) { 6648 result.addAll(candidates); 6649 result.removeAll(neverList); 6650 } 6651 } 6652 } 6653 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6654 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6655 result.size()); 6656 for (ResolveInfo info : result) { 6657 Slog.v(TAG, " + " + info.activityInfo); 6658 } 6659 } 6660 return result; 6661 } 6662 6663 // Returns a packed value as a long: 6664 // 6665 // high 'int'-sized word: link status: undefined/ask/never/always. 6666 // low 'int'-sized word: relative priority among 'always' results. 6667 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6668 long result = ps.getDomainVerificationStatusForUser(userId); 6669 // if none available, get the master status 6670 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6671 if (ps.getIntentFilterVerificationInfo() != null) { 6672 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6673 } 6674 } 6675 return result; 6676 } 6677 6678 private ResolveInfo querySkipCurrentProfileIntents( 6679 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6680 int flags, int sourceUserId) { 6681 if (matchingFilters != null) { 6682 int size = matchingFilters.size(); 6683 for (int i = 0; i < size; i ++) { 6684 CrossProfileIntentFilter filter = matchingFilters.get(i); 6685 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6686 // Checking if there are activities in the target user that can handle the 6687 // intent. 6688 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6689 resolvedType, flags, sourceUserId); 6690 if (resolveInfo != null) { 6691 return resolveInfo; 6692 } 6693 } 6694 } 6695 } 6696 return null; 6697 } 6698 6699 // Return matching ResolveInfo in target user if any. 6700 private ResolveInfo queryCrossProfileIntents( 6701 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6702 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6703 if (matchingFilters != null) { 6704 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6705 // match the same intent. For performance reasons, it is better not to 6706 // run queryIntent twice for the same userId 6707 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6708 int size = matchingFilters.size(); 6709 for (int i = 0; i < size; i++) { 6710 CrossProfileIntentFilter filter = matchingFilters.get(i); 6711 int targetUserId = filter.getTargetUserId(); 6712 boolean skipCurrentProfile = 6713 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6714 boolean skipCurrentProfileIfNoMatchFound = 6715 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6716 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6717 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6718 // Checking if there are activities in the target user that can handle the 6719 // intent. 6720 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6721 resolvedType, flags, sourceUserId); 6722 if (resolveInfo != null) return resolveInfo; 6723 alreadyTriedUserIds.put(targetUserId, true); 6724 } 6725 } 6726 } 6727 return null; 6728 } 6729 6730 /** 6731 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6732 * will forward the intent to the filter's target user. 6733 * Otherwise, returns null. 6734 */ 6735 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6736 String resolvedType, int flags, int sourceUserId) { 6737 int targetUserId = filter.getTargetUserId(); 6738 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6739 resolvedType, flags, targetUserId); 6740 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6741 // If all the matches in the target profile are suspended, return null. 6742 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6743 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6744 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6745 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6746 targetUserId); 6747 } 6748 } 6749 } 6750 return null; 6751 } 6752 6753 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6754 int sourceUserId, int targetUserId) { 6755 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6756 long ident = Binder.clearCallingIdentity(); 6757 boolean targetIsProfile; 6758 try { 6759 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6760 } finally { 6761 Binder.restoreCallingIdentity(ident); 6762 } 6763 String className; 6764 if (targetIsProfile) { 6765 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6766 } else { 6767 className = FORWARD_INTENT_TO_PARENT; 6768 } 6769 ComponentName forwardingActivityComponentName = new ComponentName( 6770 mAndroidApplication.packageName, className); 6771 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6772 sourceUserId); 6773 if (!targetIsProfile) { 6774 forwardingActivityInfo.showUserIcon = targetUserId; 6775 forwardingResolveInfo.noResourceId = true; 6776 } 6777 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6778 forwardingResolveInfo.priority = 0; 6779 forwardingResolveInfo.preferredOrder = 0; 6780 forwardingResolveInfo.match = 0; 6781 forwardingResolveInfo.isDefault = true; 6782 forwardingResolveInfo.filter = filter; 6783 forwardingResolveInfo.targetUserId = targetUserId; 6784 return forwardingResolveInfo; 6785 } 6786 6787 @Override 6788 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6789 Intent[] specifics, String[] specificTypes, Intent intent, 6790 String resolvedType, int flags, int userId) { 6791 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6792 specificTypes, intent, resolvedType, flags, userId)); 6793 } 6794 6795 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6796 Intent[] specifics, String[] specificTypes, Intent intent, 6797 String resolvedType, int flags, int userId) { 6798 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6799 final int callingUid = Binder.getCallingUid(); 6800 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6801 false /*includeInstantApps*/); 6802 enforceCrossUserPermission(callingUid, userId, 6803 false /*requireFullPermission*/, false /*checkShell*/, 6804 "query intent activity options"); 6805 final String resultsAction = intent.getAction(); 6806 6807 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6808 | PackageManager.GET_RESOLVED_FILTER, userId); 6809 6810 if (DEBUG_INTENT_MATCHING) { 6811 Log.v(TAG, "Query " + intent + ": " + results); 6812 } 6813 6814 int specificsPos = 0; 6815 int N; 6816 6817 // todo: note that the algorithm used here is O(N^2). This 6818 // isn't a problem in our current environment, but if we start running 6819 // into situations where we have more than 5 or 10 matches then this 6820 // should probably be changed to something smarter... 6821 6822 // First we go through and resolve each of the specific items 6823 // that were supplied, taking care of removing any corresponding 6824 // duplicate items in the generic resolve list. 6825 if (specifics != null) { 6826 for (int i=0; i<specifics.length; i++) { 6827 final Intent sintent = specifics[i]; 6828 if (sintent == null) { 6829 continue; 6830 } 6831 6832 if (DEBUG_INTENT_MATCHING) { 6833 Log.v(TAG, "Specific #" + i + ": " + sintent); 6834 } 6835 6836 String action = sintent.getAction(); 6837 if (resultsAction != null && resultsAction.equals(action)) { 6838 // If this action was explicitly requested, then don't 6839 // remove things that have it. 6840 action = null; 6841 } 6842 6843 ResolveInfo ri = null; 6844 ActivityInfo ai = null; 6845 6846 ComponentName comp = sintent.getComponent(); 6847 if (comp == null) { 6848 ri = resolveIntent( 6849 sintent, 6850 specificTypes != null ? specificTypes[i] : null, 6851 flags, userId); 6852 if (ri == null) { 6853 continue; 6854 } 6855 if (ri == mResolveInfo) { 6856 // ACK! Must do something better with this. 6857 } 6858 ai = ri.activityInfo; 6859 comp = new ComponentName(ai.applicationInfo.packageName, 6860 ai.name); 6861 } else { 6862 ai = getActivityInfo(comp, flags, userId); 6863 if (ai == null) { 6864 continue; 6865 } 6866 } 6867 6868 // Look for any generic query activities that are duplicates 6869 // of this specific one, and remove them from the results. 6870 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6871 N = results.size(); 6872 int j; 6873 for (j=specificsPos; j<N; j++) { 6874 ResolveInfo sri = results.get(j); 6875 if ((sri.activityInfo.name.equals(comp.getClassName()) 6876 && sri.activityInfo.applicationInfo.packageName.equals( 6877 comp.getPackageName())) 6878 || (action != null && sri.filter.matchAction(action))) { 6879 results.remove(j); 6880 if (DEBUG_INTENT_MATCHING) Log.v( 6881 TAG, "Removing duplicate item from " + j 6882 + " due to specific " + specificsPos); 6883 if (ri == null) { 6884 ri = sri; 6885 } 6886 j--; 6887 N--; 6888 } 6889 } 6890 6891 // Add this specific item to its proper place. 6892 if (ri == null) { 6893 ri = new ResolveInfo(); 6894 ri.activityInfo = ai; 6895 } 6896 results.add(specificsPos, ri); 6897 ri.specificIndex = i; 6898 specificsPos++; 6899 } 6900 } 6901 6902 // Now we go through the remaining generic results and remove any 6903 // duplicate actions that are found here. 6904 N = results.size(); 6905 for (int i=specificsPos; i<N-1; i++) { 6906 final ResolveInfo rii = results.get(i); 6907 if (rii.filter == null) { 6908 continue; 6909 } 6910 6911 // Iterate over all of the actions of this result's intent 6912 // filter... typically this should be just one. 6913 final Iterator<String> it = rii.filter.actionsIterator(); 6914 if (it == null) { 6915 continue; 6916 } 6917 while (it.hasNext()) { 6918 final String action = it.next(); 6919 if (resultsAction != null && resultsAction.equals(action)) { 6920 // If this action was explicitly requested, then don't 6921 // remove things that have it. 6922 continue; 6923 } 6924 for (int j=i+1; j<N; j++) { 6925 final ResolveInfo rij = results.get(j); 6926 if (rij.filter != null && rij.filter.hasAction(action)) { 6927 results.remove(j); 6928 if (DEBUG_INTENT_MATCHING) Log.v( 6929 TAG, "Removing duplicate item from " + j 6930 + " due to action " + action + " at " + i); 6931 j--; 6932 N--; 6933 } 6934 } 6935 } 6936 6937 // If the caller didn't request filter information, drop it now 6938 // so we don't have to marshall/unmarshall it. 6939 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6940 rii.filter = null; 6941 } 6942 } 6943 6944 // Filter out the caller activity if so requested. 6945 if (caller != null) { 6946 N = results.size(); 6947 for (int i=0; i<N; i++) { 6948 ActivityInfo ainfo = results.get(i).activityInfo; 6949 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6950 && caller.getClassName().equals(ainfo.name)) { 6951 results.remove(i); 6952 break; 6953 } 6954 } 6955 } 6956 6957 // If the caller didn't request filter information, 6958 // drop them now so we don't have to 6959 // marshall/unmarshall it. 6960 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6961 N = results.size(); 6962 for (int i=0; i<N; i++) { 6963 results.get(i).filter = null; 6964 } 6965 } 6966 6967 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6968 return results; 6969 } 6970 6971 @Override 6972 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6973 String resolvedType, int flags, int userId) { 6974 return new ParceledListSlice<>( 6975 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6976 } 6977 6978 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6979 String resolvedType, int flags, int userId) { 6980 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6981 final int callingUid = Binder.getCallingUid(); 6982 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6983 false /*includeInstantApps*/); 6984 ComponentName comp = intent.getComponent(); 6985 if (comp == null) { 6986 if (intent.getSelector() != null) { 6987 intent = intent.getSelector(); 6988 comp = intent.getComponent(); 6989 } 6990 } 6991 if (comp != null) { 6992 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6993 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6994 if (ai != null) { 6995 ResolveInfo ri = new ResolveInfo(); 6996 ri.activityInfo = ai; 6997 list.add(ri); 6998 } 6999 return list; 7000 } 7001 7002 // reader 7003 synchronized (mPackages) { 7004 String pkgName = intent.getPackage(); 7005 if (pkgName == null) { 7006 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7007 } 7008 final PackageParser.Package pkg = mPackages.get(pkgName); 7009 if (pkg != null) { 7010 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7011 userId); 7012 } 7013 return Collections.emptyList(); 7014 } 7015 } 7016 7017 @Override 7018 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7019 final int callingUid = Binder.getCallingUid(); 7020 return resolveServiceInternal( 7021 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7022 } 7023 7024 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7025 int userId, int callingUid, boolean includeInstantApps) { 7026 if (!sUserManager.exists(userId)) return null; 7027 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7028 List<ResolveInfo> query = queryIntentServicesInternal( 7029 intent, resolvedType, flags, userId, callingUid, includeInstantApps); 7030 if (query != null) { 7031 if (query.size() >= 1) { 7032 // If there is more than one service with the same priority, 7033 // just arbitrarily pick the first one. 7034 return query.get(0); 7035 } 7036 } 7037 return null; 7038 } 7039 7040 @Override 7041 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7042 String resolvedType, int flags, int userId) { 7043 final int callingUid = Binder.getCallingUid(); 7044 return new ParceledListSlice<>(queryIntentServicesInternal( 7045 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7046 } 7047 7048 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7049 String resolvedType, int flags, int userId, int callingUid, 7050 boolean includeInstantApps) { 7051 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7052 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7053 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7054 ComponentName comp = intent.getComponent(); 7055 if (comp == null) { 7056 if (intent.getSelector() != null) { 7057 intent = intent.getSelector(); 7058 comp = intent.getComponent(); 7059 } 7060 } 7061 if (comp != null) { 7062 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7063 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7064 if (si != null) { 7065 // When specifying an explicit component, we prevent the service from being 7066 // used when either 1) the service is in an instant application and the 7067 // caller is not the same instant application or 2) the calling package is 7068 // ephemeral and the activity is not visible to ephemeral applications. 7069 final boolean matchVisibleToInstantAppOnly = 7070 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7071 final boolean isCallerInstantApp = 7072 instantAppPkgName != null; 7073 final boolean isTargetSameInstantApp = 7074 comp.getPackageName().equals(instantAppPkgName); 7075 final boolean isTargetHiddenFromInstantApp = 7076 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 7077 final boolean blockResolution = 7078 !isTargetSameInstantApp 7079 && ((matchVisibleToInstantAppOnly && isCallerInstantApp 7080 && isTargetHiddenFromInstantApp)); 7081 if (!blockResolution) { 7082 final ResolveInfo ri = new ResolveInfo(); 7083 ri.serviceInfo = si; 7084 list.add(ri); 7085 } 7086 } 7087 return list; 7088 } 7089 7090 // reader 7091 synchronized (mPackages) { 7092 String pkgName = intent.getPackage(); 7093 if (pkgName == null) { 7094 return applyPostServiceResolutionFilter( 7095 mServices.queryIntent(intent, resolvedType, flags, userId), 7096 instantAppPkgName); 7097 } 7098 final PackageParser.Package pkg = mPackages.get(pkgName); 7099 if (pkg != null) { 7100 return applyPostServiceResolutionFilter( 7101 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7102 userId), 7103 instantAppPkgName); 7104 } 7105 return Collections.emptyList(); 7106 } 7107 } 7108 7109 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7110 String instantAppPkgName) { 7111 // TODO: When adding on-demand split support for non-instant apps, remove this check 7112 // and always apply post filtering 7113 if (instantAppPkgName == null) { 7114 return resolveInfos; 7115 } 7116 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7117 final ResolveInfo info = resolveInfos.get(i); 7118 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7119 // allow services that are defined in the provided package 7120 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7121 if (info.serviceInfo.splitName != null 7122 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7123 info.serviceInfo.splitName)) { 7124 // requested service is defined in a split that hasn't been installed yet. 7125 // add the installer to the resolve list 7126 if (DEBUG_EPHEMERAL) { 7127 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7128 } 7129 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7130 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7131 info.serviceInfo.packageName, info.serviceInfo.splitName, 7132 info.serviceInfo.applicationInfo.versionCode); 7133 // make sure this resolver is the default 7134 installerInfo.isDefault = true; 7135 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7136 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7137 // add a non-generic filter 7138 installerInfo.filter = new IntentFilter(); 7139 // load resources from the correct package 7140 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7141 resolveInfos.set(i, installerInfo); 7142 } 7143 continue; 7144 } 7145 // allow services that have been explicitly exposed to ephemeral apps 7146 if (!isEphemeralApp 7147 && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 7148 continue; 7149 } 7150 resolveInfos.remove(i); 7151 } 7152 return resolveInfos; 7153 } 7154 7155 @Override 7156 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7157 String resolvedType, int flags, int userId) { 7158 return new ParceledListSlice<>( 7159 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7160 } 7161 7162 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7163 Intent intent, String resolvedType, int flags, int userId) { 7164 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7165 final int callingUid = Binder.getCallingUid(); 7166 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7167 false /*includeInstantApps*/); 7168 ComponentName comp = intent.getComponent(); 7169 if (comp == null) { 7170 if (intent.getSelector() != null) { 7171 intent = intent.getSelector(); 7172 comp = intent.getComponent(); 7173 } 7174 } 7175 if (comp != null) { 7176 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7177 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7178 if (pi != null) { 7179 final ResolveInfo ri = new ResolveInfo(); 7180 ri.providerInfo = pi; 7181 list.add(ri); 7182 } 7183 return list; 7184 } 7185 7186 // reader 7187 synchronized (mPackages) { 7188 String pkgName = intent.getPackage(); 7189 if (pkgName == null) { 7190 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7191 } 7192 final PackageParser.Package pkg = mPackages.get(pkgName); 7193 if (pkg != null) { 7194 return mProviders.queryIntentForPackage( 7195 intent, resolvedType, flags, pkg.providers, userId); 7196 } 7197 return Collections.emptyList(); 7198 } 7199 } 7200 7201 @Override 7202 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7203 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7204 flags = updateFlagsForPackage(flags, userId, null); 7205 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7206 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7207 true /* requireFullPermission */, false /* checkShell */, 7208 "get installed packages"); 7209 7210 // writer 7211 synchronized (mPackages) { 7212 ArrayList<PackageInfo> list; 7213 if (listUninstalled) { 7214 list = new ArrayList<>(mSettings.mPackages.size()); 7215 for (PackageSetting ps : mSettings.mPackages.values()) { 7216 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7217 continue; 7218 } 7219 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7220 if (pi != null) { 7221 list.add(pi); 7222 } 7223 } 7224 } else { 7225 list = new ArrayList<>(mPackages.size()); 7226 for (PackageParser.Package p : mPackages.values()) { 7227 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7228 Binder.getCallingUid(), userId)) { 7229 continue; 7230 } 7231 final PackageInfo pi = generatePackageInfo((PackageSetting) 7232 p.mExtras, flags, userId); 7233 if (pi != null) { 7234 list.add(pi); 7235 } 7236 } 7237 } 7238 7239 return new ParceledListSlice<>(list); 7240 } 7241 } 7242 7243 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7244 String[] permissions, boolean[] tmp, int flags, int userId) { 7245 int numMatch = 0; 7246 final PermissionsState permissionsState = ps.getPermissionsState(); 7247 for (int i=0; i<permissions.length; i++) { 7248 final String permission = permissions[i]; 7249 if (permissionsState.hasPermission(permission, userId)) { 7250 tmp[i] = true; 7251 numMatch++; 7252 } else { 7253 tmp[i] = false; 7254 } 7255 } 7256 if (numMatch == 0) { 7257 return; 7258 } 7259 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7260 7261 // The above might return null in cases of uninstalled apps or install-state 7262 // skew across users/profiles. 7263 if (pi != null) { 7264 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7265 if (numMatch == permissions.length) { 7266 pi.requestedPermissions = permissions; 7267 } else { 7268 pi.requestedPermissions = new String[numMatch]; 7269 numMatch = 0; 7270 for (int i=0; i<permissions.length; i++) { 7271 if (tmp[i]) { 7272 pi.requestedPermissions[numMatch] = permissions[i]; 7273 numMatch++; 7274 } 7275 } 7276 } 7277 } 7278 list.add(pi); 7279 } 7280 } 7281 7282 @Override 7283 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7284 String[] permissions, int flags, int userId) { 7285 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7286 flags = updateFlagsForPackage(flags, userId, permissions); 7287 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7288 true /* requireFullPermission */, false /* checkShell */, 7289 "get packages holding permissions"); 7290 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7291 7292 // writer 7293 synchronized (mPackages) { 7294 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7295 boolean[] tmpBools = new boolean[permissions.length]; 7296 if (listUninstalled) { 7297 for (PackageSetting ps : mSettings.mPackages.values()) { 7298 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7299 userId); 7300 } 7301 } else { 7302 for (PackageParser.Package pkg : mPackages.values()) { 7303 PackageSetting ps = (PackageSetting)pkg.mExtras; 7304 if (ps != null) { 7305 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7306 userId); 7307 } 7308 } 7309 } 7310 7311 return new ParceledListSlice<PackageInfo>(list); 7312 } 7313 } 7314 7315 @Override 7316 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7317 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7318 flags = updateFlagsForApplication(flags, userId, null); 7319 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7320 7321 // writer 7322 synchronized (mPackages) { 7323 ArrayList<ApplicationInfo> list; 7324 if (listUninstalled) { 7325 list = new ArrayList<>(mSettings.mPackages.size()); 7326 for (PackageSetting ps : mSettings.mPackages.values()) { 7327 ApplicationInfo ai; 7328 int effectiveFlags = flags; 7329 if (ps.isSystem()) { 7330 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7331 } 7332 if (ps.pkg != null) { 7333 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7334 continue; 7335 } 7336 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7337 ps.readUserState(userId), userId); 7338 if (ai != null) { 7339 rebaseEnabledOverlays(ai, userId); 7340 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7341 } 7342 } else { 7343 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7344 // and already converts to externally visible package name 7345 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7346 Binder.getCallingUid(), effectiveFlags, userId); 7347 } 7348 if (ai != null) { 7349 list.add(ai); 7350 } 7351 } 7352 } else { 7353 list = new ArrayList<>(mPackages.size()); 7354 for (PackageParser.Package p : mPackages.values()) { 7355 if (p.mExtras != null) { 7356 PackageSetting ps = (PackageSetting) p.mExtras; 7357 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7358 continue; 7359 } 7360 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7361 ps.readUserState(userId), userId); 7362 if (ai != null) { 7363 rebaseEnabledOverlays(ai, userId); 7364 ai.packageName = resolveExternalPackageNameLPr(p); 7365 list.add(ai); 7366 } 7367 } 7368 } 7369 } 7370 7371 return new ParceledListSlice<>(list); 7372 } 7373 } 7374 7375 @Override 7376 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7377 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7378 return null; 7379 } 7380 7381 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7382 "getEphemeralApplications"); 7383 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7384 true /* requireFullPermission */, false /* checkShell */, 7385 "getEphemeralApplications"); 7386 synchronized (mPackages) { 7387 List<InstantAppInfo> instantApps = mInstantAppRegistry 7388 .getInstantAppsLPr(userId); 7389 if (instantApps != null) { 7390 return new ParceledListSlice<>(instantApps); 7391 } 7392 } 7393 return null; 7394 } 7395 7396 @Override 7397 public boolean isInstantApp(String packageName, int userId) { 7398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7399 true /* requireFullPermission */, false /* checkShell */, 7400 "isInstantApp"); 7401 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7402 return false; 7403 } 7404 int uid = Binder.getCallingUid(); 7405 if (Process.isIsolated(uid)) { 7406 uid = mIsolatedOwners.get(uid); 7407 } 7408 7409 synchronized (mPackages) { 7410 final PackageSetting ps = mSettings.mPackages.get(packageName); 7411 PackageParser.Package pkg = mPackages.get(packageName); 7412 final boolean returnAllowed = 7413 ps != null 7414 && (isCallerSameApp(packageName, uid) 7415 || mContext.checkCallingOrSelfPermission( 7416 android.Manifest.permission.ACCESS_INSTANT_APPS) 7417 == PERMISSION_GRANTED 7418 || mInstantAppRegistry.isInstantAccessGranted( 7419 userId, UserHandle.getAppId(uid), ps.appId)); 7420 if (returnAllowed) { 7421 return ps.getInstantApp(userId); 7422 } 7423 } 7424 return false; 7425 } 7426 7427 @Override 7428 public byte[] getInstantAppCookie(String packageName, int userId) { 7429 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7430 return null; 7431 } 7432 7433 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7434 true /* requireFullPermission */, false /* checkShell */, 7435 "getInstantAppCookie"); 7436 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7437 return null; 7438 } 7439 synchronized (mPackages) { 7440 return mInstantAppRegistry.getInstantAppCookieLPw( 7441 packageName, userId); 7442 } 7443 } 7444 7445 @Override 7446 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7447 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7448 return true; 7449 } 7450 7451 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7452 true /* requireFullPermission */, true /* checkShell */, 7453 "setInstantAppCookie"); 7454 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7455 return false; 7456 } 7457 synchronized (mPackages) { 7458 return mInstantAppRegistry.setInstantAppCookieLPw( 7459 packageName, cookie, userId); 7460 } 7461 } 7462 7463 @Override 7464 public Bitmap getInstantAppIcon(String packageName, int userId) { 7465 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7466 return null; 7467 } 7468 7469 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7470 "getInstantAppIcon"); 7471 7472 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7473 true /* requireFullPermission */, false /* checkShell */, 7474 "getInstantAppIcon"); 7475 7476 synchronized (mPackages) { 7477 return mInstantAppRegistry.getInstantAppIconLPw( 7478 packageName, userId); 7479 } 7480 } 7481 7482 private boolean isCallerSameApp(String packageName, int uid) { 7483 PackageParser.Package pkg = mPackages.get(packageName); 7484 return pkg != null 7485 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7486 } 7487 7488 @Override 7489 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7490 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7491 } 7492 7493 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7494 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7495 7496 // reader 7497 synchronized (mPackages) { 7498 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7499 final int userId = UserHandle.getCallingUserId(); 7500 while (i.hasNext()) { 7501 final PackageParser.Package p = i.next(); 7502 if (p.applicationInfo == null) continue; 7503 7504 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7505 && !p.applicationInfo.isDirectBootAware(); 7506 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7507 && p.applicationInfo.isDirectBootAware(); 7508 7509 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7510 && (!mSafeMode || isSystemApp(p)) 7511 && (matchesUnaware || matchesAware)) { 7512 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7513 if (ps != null) { 7514 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7515 ps.readUserState(userId), userId); 7516 if (ai != null) { 7517 rebaseEnabledOverlays(ai, userId); 7518 finalList.add(ai); 7519 } 7520 } 7521 } 7522 } 7523 } 7524 7525 return finalList; 7526 } 7527 7528 @Override 7529 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7530 if (!sUserManager.exists(userId)) return null; 7531 flags = updateFlagsForComponent(flags, userId, name); 7532 // reader 7533 synchronized (mPackages) { 7534 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7535 PackageSetting ps = provider != null 7536 ? mSettings.mPackages.get(provider.owner.packageName) 7537 : null; 7538 return ps != null 7539 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7540 ? PackageParser.generateProviderInfo(provider, flags, 7541 ps.readUserState(userId), userId) 7542 : null; 7543 } 7544 } 7545 7546 /** 7547 * @deprecated 7548 */ 7549 @Deprecated 7550 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7551 // reader 7552 synchronized (mPackages) { 7553 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7554 .entrySet().iterator(); 7555 final int userId = UserHandle.getCallingUserId(); 7556 while (i.hasNext()) { 7557 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7558 PackageParser.Provider p = entry.getValue(); 7559 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7560 7561 if (ps != null && p.syncable 7562 && (!mSafeMode || (p.info.applicationInfo.flags 7563 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7564 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7565 ps.readUserState(userId), userId); 7566 if (info != null) { 7567 outNames.add(entry.getKey()); 7568 outInfo.add(info); 7569 } 7570 } 7571 } 7572 } 7573 } 7574 7575 @Override 7576 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7577 int uid, int flags, String metaDataKey) { 7578 final int userId = processName != null ? UserHandle.getUserId(uid) 7579 : UserHandle.getCallingUserId(); 7580 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7581 flags = updateFlagsForComponent(flags, userId, processName); 7582 7583 ArrayList<ProviderInfo> finalList = null; 7584 // reader 7585 synchronized (mPackages) { 7586 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7587 while (i.hasNext()) { 7588 final PackageParser.Provider p = i.next(); 7589 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7590 if (ps != null && p.info.authority != null 7591 && (processName == null 7592 || (p.info.processName.equals(processName) 7593 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7594 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7595 7596 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7597 // parameter. 7598 if (metaDataKey != null 7599 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7600 continue; 7601 } 7602 7603 if (finalList == null) { 7604 finalList = new ArrayList<ProviderInfo>(3); 7605 } 7606 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7607 ps.readUserState(userId), userId); 7608 if (info != null) { 7609 finalList.add(info); 7610 } 7611 } 7612 } 7613 } 7614 7615 if (finalList != null) { 7616 Collections.sort(finalList, mProviderInitOrderSorter); 7617 return new ParceledListSlice<ProviderInfo>(finalList); 7618 } 7619 7620 return ParceledListSlice.emptyList(); 7621 } 7622 7623 @Override 7624 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7625 // reader 7626 synchronized (mPackages) { 7627 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7628 return PackageParser.generateInstrumentationInfo(i, flags); 7629 } 7630 } 7631 7632 @Override 7633 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7634 String targetPackage, int flags) { 7635 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7636 } 7637 7638 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7639 int flags) { 7640 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7641 7642 // reader 7643 synchronized (mPackages) { 7644 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7645 while (i.hasNext()) { 7646 final PackageParser.Instrumentation p = i.next(); 7647 if (targetPackage == null 7648 || targetPackage.equals(p.info.targetPackage)) { 7649 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7650 flags); 7651 if (ii != null) { 7652 finalList.add(ii); 7653 } 7654 } 7655 } 7656 } 7657 7658 return finalList; 7659 } 7660 7661 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7662 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7663 try { 7664 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7665 } finally { 7666 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7667 } 7668 } 7669 7670 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7671 final File[] files = dir.listFiles(); 7672 if (ArrayUtils.isEmpty(files)) { 7673 Log.d(TAG, "No files in app dir " + dir); 7674 return; 7675 } 7676 7677 if (DEBUG_PACKAGE_SCANNING) { 7678 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7679 + " flags=0x" + Integer.toHexString(parseFlags)); 7680 } 7681 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7682 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7683 7684 // Submit files for parsing in parallel 7685 int fileCount = 0; 7686 for (File file : files) { 7687 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7688 && !PackageInstallerService.isStageName(file.getName()); 7689 if (!isPackage) { 7690 // Ignore entries which are not packages 7691 continue; 7692 } 7693 parallelPackageParser.submit(file, parseFlags); 7694 fileCount++; 7695 } 7696 7697 // Process results one by one 7698 for (; fileCount > 0; fileCount--) { 7699 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7700 Throwable throwable = parseResult.throwable; 7701 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7702 7703 if (throwable == null) { 7704 // Static shared libraries have synthetic package names 7705 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7706 renameStaticSharedLibraryPackage(parseResult.pkg); 7707 } 7708 try { 7709 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7710 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7711 currentTime, null); 7712 } 7713 } catch (PackageManagerException e) { 7714 errorCode = e.error; 7715 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7716 } 7717 } else if (throwable instanceof PackageParser.PackageParserException) { 7718 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7719 throwable; 7720 errorCode = e.error; 7721 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7722 } else { 7723 throw new IllegalStateException("Unexpected exception occurred while parsing " 7724 + parseResult.scanFile, throwable); 7725 } 7726 7727 // Delete invalid userdata apps 7728 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7729 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7730 logCriticalInfo(Log.WARN, 7731 "Deleting invalid package at " + parseResult.scanFile); 7732 removeCodePathLI(parseResult.scanFile); 7733 } 7734 } 7735 parallelPackageParser.close(); 7736 } 7737 7738 private static File getSettingsProblemFile() { 7739 File dataDir = Environment.getDataDirectory(); 7740 File systemDir = new File(dataDir, "system"); 7741 File fname = new File(systemDir, "uiderrors.txt"); 7742 return fname; 7743 } 7744 7745 static void reportSettingsProblem(int priority, String msg) { 7746 logCriticalInfo(priority, msg); 7747 } 7748 7749 public static void logCriticalInfo(int priority, String msg) { 7750 Slog.println(priority, TAG, msg); 7751 EventLogTags.writePmCriticalInfo(msg); 7752 try { 7753 File fname = getSettingsProblemFile(); 7754 FileOutputStream out = new FileOutputStream(fname, true); 7755 PrintWriter pw = new FastPrintWriter(out); 7756 SimpleDateFormat formatter = new SimpleDateFormat(); 7757 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7758 pw.println(dateString + ": " + msg); 7759 pw.close(); 7760 FileUtils.setPermissions( 7761 fname.toString(), 7762 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7763 -1, -1); 7764 } catch (java.io.IOException e) { 7765 } 7766 } 7767 7768 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7769 if (srcFile.isDirectory()) { 7770 final File baseFile = new File(pkg.baseCodePath); 7771 long maxModifiedTime = baseFile.lastModified(); 7772 if (pkg.splitCodePaths != null) { 7773 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7774 final File splitFile = new File(pkg.splitCodePaths[i]); 7775 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7776 } 7777 } 7778 return maxModifiedTime; 7779 } 7780 return srcFile.lastModified(); 7781 } 7782 7783 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7784 final int policyFlags) throws PackageManagerException { 7785 // When upgrading from pre-N MR1, verify the package time stamp using the package 7786 // directory and not the APK file. 7787 final long lastModifiedTime = mIsPreNMR1Upgrade 7788 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7789 if (ps != null 7790 && ps.codePath.equals(srcFile) 7791 && ps.timeStamp == lastModifiedTime 7792 && !isCompatSignatureUpdateNeeded(pkg) 7793 && !isRecoverSignatureUpdateNeeded(pkg)) { 7794 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7795 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7796 ArraySet<PublicKey> signingKs; 7797 synchronized (mPackages) { 7798 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7799 } 7800 if (ps.signatures.mSignatures != null 7801 && ps.signatures.mSignatures.length != 0 7802 && signingKs != null) { 7803 // Optimization: reuse the existing cached certificates 7804 // if the package appears to be unchanged. 7805 pkg.mSignatures = ps.signatures.mSignatures; 7806 pkg.mSigningKeys = signingKs; 7807 return; 7808 } 7809 7810 Slog.w(TAG, "PackageSetting for " + ps.name 7811 + " is missing signatures. Collecting certs again to recover them."); 7812 } else { 7813 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7814 } 7815 7816 try { 7817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7818 PackageParser.collectCertificates(pkg, policyFlags); 7819 } catch (PackageParserException e) { 7820 throw PackageManagerException.from(e); 7821 } finally { 7822 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7823 } 7824 } 7825 7826 /** 7827 * Traces a package scan. 7828 * @see #scanPackageLI(File, int, int, long, UserHandle) 7829 */ 7830 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7831 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7832 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7833 try { 7834 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7835 } finally { 7836 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7837 } 7838 } 7839 7840 /** 7841 * Scans a package and returns the newly parsed package. 7842 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7843 */ 7844 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7845 long currentTime, UserHandle user) throws PackageManagerException { 7846 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7847 PackageParser pp = new PackageParser(); 7848 pp.setSeparateProcesses(mSeparateProcesses); 7849 pp.setOnlyCoreApps(mOnlyCore); 7850 pp.setDisplayMetrics(mMetrics); 7851 pp.setCallback(mPackageParserCallback); 7852 7853 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7854 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7855 } 7856 7857 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7858 final PackageParser.Package pkg; 7859 try { 7860 pkg = pp.parsePackage(scanFile, parseFlags); 7861 } catch (PackageParserException e) { 7862 throw PackageManagerException.from(e); 7863 } finally { 7864 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7865 } 7866 7867 // Static shared libraries have synthetic package names 7868 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7869 renameStaticSharedLibraryPackage(pkg); 7870 } 7871 7872 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7873 } 7874 7875 /** 7876 * Scans a package and returns the newly parsed package. 7877 * @throws PackageManagerException on a parse error. 7878 */ 7879 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7880 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7881 throws PackageManagerException { 7882 // If the package has children and this is the first dive in the function 7883 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7884 // packages (parent and children) would be successfully scanned before the 7885 // actual scan since scanning mutates internal state and we want to atomically 7886 // install the package and its children. 7887 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7888 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7889 scanFlags |= SCAN_CHECK_ONLY; 7890 } 7891 } else { 7892 scanFlags &= ~SCAN_CHECK_ONLY; 7893 } 7894 7895 // Scan the parent 7896 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7897 scanFlags, currentTime, user); 7898 7899 // Scan the children 7900 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7901 for (int i = 0; i < childCount; i++) { 7902 PackageParser.Package childPackage = pkg.childPackages.get(i); 7903 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7904 currentTime, user); 7905 } 7906 7907 7908 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7909 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7910 } 7911 7912 return scannedPkg; 7913 } 7914 7915 /** 7916 * Scans a package and returns the newly parsed package. 7917 * @throws PackageManagerException on a parse error. 7918 */ 7919 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7920 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7921 throws PackageManagerException { 7922 PackageSetting ps = null; 7923 PackageSetting updatedPkg; 7924 // reader 7925 synchronized (mPackages) { 7926 // Look to see if we already know about this package. 7927 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7928 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7929 // This package has been renamed to its original name. Let's 7930 // use that. 7931 ps = mSettings.getPackageLPr(oldName); 7932 } 7933 // If there was no original package, see one for the real package name. 7934 if (ps == null) { 7935 ps = mSettings.getPackageLPr(pkg.packageName); 7936 } 7937 // Check to see if this package could be hiding/updating a system 7938 // package. Must look for it either under the original or real 7939 // package name depending on our state. 7940 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7941 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7942 7943 // If this is a package we don't know about on the system partition, we 7944 // may need to remove disabled child packages on the system partition 7945 // or may need to not add child packages if the parent apk is updated 7946 // on the data partition and no longer defines this child package. 7947 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7948 // If this is a parent package for an updated system app and this system 7949 // app got an OTA update which no longer defines some of the child packages 7950 // we have to prune them from the disabled system packages. 7951 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7952 if (disabledPs != null) { 7953 final int scannedChildCount = (pkg.childPackages != null) 7954 ? pkg.childPackages.size() : 0; 7955 final int disabledChildCount = disabledPs.childPackageNames != null 7956 ? disabledPs.childPackageNames.size() : 0; 7957 for (int i = 0; i < disabledChildCount; i++) { 7958 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7959 boolean disabledPackageAvailable = false; 7960 for (int j = 0; j < scannedChildCount; j++) { 7961 PackageParser.Package childPkg = pkg.childPackages.get(j); 7962 if (childPkg.packageName.equals(disabledChildPackageName)) { 7963 disabledPackageAvailable = true; 7964 break; 7965 } 7966 } 7967 if (!disabledPackageAvailable) { 7968 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7969 } 7970 } 7971 } 7972 } 7973 } 7974 7975 boolean updatedPkgBetter = false; 7976 // First check if this is a system package that may involve an update 7977 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7978 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7979 // it needs to drop FLAG_PRIVILEGED. 7980 if (locationIsPrivileged(scanFile)) { 7981 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7982 } else { 7983 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7984 } 7985 7986 if (ps != null && !ps.codePath.equals(scanFile)) { 7987 // The path has changed from what was last scanned... check the 7988 // version of the new path against what we have stored to determine 7989 // what to do. 7990 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7991 if (pkg.mVersionCode <= ps.versionCode) { 7992 // The system package has been updated and the code path does not match 7993 // Ignore entry. Skip it. 7994 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7995 + " ignored: updated version " + ps.versionCode 7996 + " better than this " + pkg.mVersionCode); 7997 if (!updatedPkg.codePath.equals(scanFile)) { 7998 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7999 + ps.name + " changing from " + updatedPkg.codePathString 8000 + " to " + scanFile); 8001 updatedPkg.codePath = scanFile; 8002 updatedPkg.codePathString = scanFile.toString(); 8003 updatedPkg.resourcePath = scanFile; 8004 updatedPkg.resourcePathString = scanFile.toString(); 8005 } 8006 updatedPkg.pkg = pkg; 8007 updatedPkg.versionCode = pkg.mVersionCode; 8008 8009 // Update the disabled system child packages to point to the package too. 8010 final int childCount = updatedPkg.childPackageNames != null 8011 ? updatedPkg.childPackageNames.size() : 0; 8012 for (int i = 0; i < childCount; i++) { 8013 String childPackageName = updatedPkg.childPackageNames.get(i); 8014 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8015 childPackageName); 8016 if (updatedChildPkg != null) { 8017 updatedChildPkg.pkg = pkg; 8018 updatedChildPkg.versionCode = pkg.mVersionCode; 8019 } 8020 } 8021 8022 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8023 + scanFile + " ignored: updated version " + ps.versionCode 8024 + " better than this " + pkg.mVersionCode); 8025 } else { 8026 // The current app on the system partition is better than 8027 // what we have updated to on the data partition; switch 8028 // back to the system partition version. 8029 // At this point, its safely assumed that package installation for 8030 // apps in system partition will go through. If not there won't be a working 8031 // version of the app 8032 // writer 8033 synchronized (mPackages) { 8034 // Just remove the loaded entries from package lists. 8035 mPackages.remove(ps.name); 8036 } 8037 8038 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8039 + " reverting from " + ps.codePathString 8040 + ": new version " + pkg.mVersionCode 8041 + " better than installed " + ps.versionCode); 8042 8043 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8044 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8045 synchronized (mInstallLock) { 8046 args.cleanUpResourcesLI(); 8047 } 8048 synchronized (mPackages) { 8049 mSettings.enableSystemPackageLPw(ps.name); 8050 } 8051 updatedPkgBetter = true; 8052 } 8053 } 8054 } 8055 8056 if (updatedPkg != null) { 8057 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8058 // initially 8059 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8060 8061 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8062 // flag set initially 8063 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8064 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8065 } 8066 } 8067 8068 // Verify certificates against what was last scanned 8069 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8070 8071 /* 8072 * A new system app appeared, but we already had a non-system one of the 8073 * same name installed earlier. 8074 */ 8075 boolean shouldHideSystemApp = false; 8076 if (updatedPkg == null && ps != null 8077 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8078 /* 8079 * Check to make sure the signatures match first. If they don't, 8080 * wipe the installed application and its data. 8081 */ 8082 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8083 != PackageManager.SIGNATURE_MATCH) { 8084 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8085 + " signatures don't match existing userdata copy; removing"); 8086 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8087 "scanPackageInternalLI")) { 8088 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8089 } 8090 ps = null; 8091 } else { 8092 /* 8093 * If the newly-added system app is an older version than the 8094 * already installed version, hide it. It will be scanned later 8095 * and re-added like an update. 8096 */ 8097 if (pkg.mVersionCode <= ps.versionCode) { 8098 shouldHideSystemApp = true; 8099 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8100 + " but new version " + pkg.mVersionCode + " better than installed " 8101 + ps.versionCode + "; hiding system"); 8102 } else { 8103 /* 8104 * The newly found system app is a newer version that the 8105 * one previously installed. Simply remove the 8106 * already-installed application and replace it with our own 8107 * while keeping the application data. 8108 */ 8109 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8110 + " reverting from " + ps.codePathString + ": new version " 8111 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8112 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8113 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8114 synchronized (mInstallLock) { 8115 args.cleanUpResourcesLI(); 8116 } 8117 } 8118 } 8119 } 8120 8121 // The apk is forward locked (not public) if its code and resources 8122 // are kept in different files. (except for app in either system or 8123 // vendor path). 8124 // TODO grab this value from PackageSettings 8125 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8126 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8127 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8128 } 8129 } 8130 8131 // TODO: extend to support forward-locked splits 8132 String resourcePath = null; 8133 String baseResourcePath = null; 8134 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8135 if (ps != null && ps.resourcePathString != null) { 8136 resourcePath = ps.resourcePathString; 8137 baseResourcePath = ps.resourcePathString; 8138 } else { 8139 // Should not happen at all. Just log an error. 8140 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8141 } 8142 } else { 8143 resourcePath = pkg.codePath; 8144 baseResourcePath = pkg.baseCodePath; 8145 } 8146 8147 // Set application objects path explicitly. 8148 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8149 pkg.setApplicationInfoCodePath(pkg.codePath); 8150 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8151 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8152 pkg.setApplicationInfoResourcePath(resourcePath); 8153 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8154 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8155 8156 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8157 if (ps != null && ps.getInstantApp(userId)) { 8158 scanFlags |= SCAN_AS_INSTANT_APP; 8159 } 8160 8161 // Note that we invoke the following method only if we are about to unpack an application 8162 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8163 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8164 8165 /* 8166 * If the system app should be overridden by a previously installed 8167 * data, hide the system app now and let the /data/app scan pick it up 8168 * again. 8169 */ 8170 if (shouldHideSystemApp) { 8171 synchronized (mPackages) { 8172 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8173 } 8174 } 8175 8176 return scannedPkg; 8177 } 8178 8179 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8180 // Derive the new package synthetic package name 8181 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8182 + pkg.staticSharedLibVersion); 8183 } 8184 8185 private static String fixProcessName(String defProcessName, 8186 String processName) { 8187 if (processName == null) { 8188 return defProcessName; 8189 } 8190 return processName; 8191 } 8192 8193 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8194 throws PackageManagerException { 8195 if (pkgSetting.signatures.mSignatures != null) { 8196 // Already existing package. Make sure signatures match 8197 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8198 == PackageManager.SIGNATURE_MATCH; 8199 if (!match) { 8200 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8201 == PackageManager.SIGNATURE_MATCH; 8202 } 8203 if (!match) { 8204 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8205 == PackageManager.SIGNATURE_MATCH; 8206 } 8207 if (!match) { 8208 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8209 + pkg.packageName + " signatures do not match the " 8210 + "previously installed version; ignoring!"); 8211 } 8212 } 8213 8214 // Check for shared user signatures 8215 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8216 // Already existing package. Make sure signatures match 8217 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8218 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8219 if (!match) { 8220 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8221 == PackageManager.SIGNATURE_MATCH; 8222 } 8223 if (!match) { 8224 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8225 == PackageManager.SIGNATURE_MATCH; 8226 } 8227 if (!match) { 8228 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8229 "Package " + pkg.packageName 8230 + " has no signatures that match those in shared user " 8231 + pkgSetting.sharedUser.name + "; ignoring!"); 8232 } 8233 } 8234 } 8235 8236 /** 8237 * Enforces that only the system UID or root's UID can call a method exposed 8238 * via Binder. 8239 * 8240 * @param message used as message if SecurityException is thrown 8241 * @throws SecurityException if the caller is not system or root 8242 */ 8243 private static final void enforceSystemOrRoot(String message) { 8244 final int uid = Binder.getCallingUid(); 8245 if (uid != Process.SYSTEM_UID && uid != 0) { 8246 throw new SecurityException(message); 8247 } 8248 } 8249 8250 @Override 8251 public void performFstrimIfNeeded() { 8252 enforceSystemOrRoot("Only the system can request fstrim"); 8253 8254 // Before everything else, see whether we need to fstrim. 8255 try { 8256 IStorageManager sm = PackageHelper.getStorageManager(); 8257 if (sm != null) { 8258 boolean doTrim = false; 8259 final long interval = android.provider.Settings.Global.getLong( 8260 mContext.getContentResolver(), 8261 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8262 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8263 if (interval > 0) { 8264 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8265 if (timeSinceLast > interval) { 8266 doTrim = true; 8267 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8268 + "; running immediately"); 8269 } 8270 } 8271 if (doTrim) { 8272 final boolean dexOptDialogShown; 8273 synchronized (mPackages) { 8274 dexOptDialogShown = mDexOptDialogShown; 8275 } 8276 if (!isFirstBoot() && dexOptDialogShown) { 8277 try { 8278 ActivityManager.getService().showBootMessage( 8279 mContext.getResources().getString( 8280 R.string.android_upgrading_fstrim), true); 8281 } catch (RemoteException e) { 8282 } 8283 } 8284 sm.runMaintenance(); 8285 } 8286 } else { 8287 Slog.e(TAG, "storageManager service unavailable!"); 8288 } 8289 } catch (RemoteException e) { 8290 // Can't happen; StorageManagerService is local 8291 } 8292 } 8293 8294 @Override 8295 public void updatePackagesIfNeeded() { 8296 enforceSystemOrRoot("Only the system can request package update"); 8297 8298 // We need to re-extract after an OTA. 8299 boolean causeUpgrade = isUpgrade(); 8300 8301 // First boot or factory reset. 8302 // Note: we also handle devices that are upgrading to N right now as if it is their 8303 // first boot, as they do not have profile data. 8304 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8305 8306 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8307 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8308 8309 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8310 return; 8311 } 8312 8313 List<PackageParser.Package> pkgs; 8314 synchronized (mPackages) { 8315 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8316 } 8317 8318 final long startTime = System.nanoTime(); 8319 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8320 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8321 8322 final int elapsedTimeSeconds = 8323 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8324 8325 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8326 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8327 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8328 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8329 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8330 } 8331 8332 /** 8333 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8334 * containing statistics about the invocation. The array consists of three elements, 8335 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8336 * and {@code numberOfPackagesFailed}. 8337 */ 8338 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8339 String compilerFilter) { 8340 8341 int numberOfPackagesVisited = 0; 8342 int numberOfPackagesOptimized = 0; 8343 int numberOfPackagesSkipped = 0; 8344 int numberOfPackagesFailed = 0; 8345 final int numberOfPackagesToDexopt = pkgs.size(); 8346 8347 for (PackageParser.Package pkg : pkgs) { 8348 numberOfPackagesVisited++; 8349 8350 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8351 if (DEBUG_DEXOPT) { 8352 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8353 } 8354 numberOfPackagesSkipped++; 8355 continue; 8356 } 8357 8358 if (DEBUG_DEXOPT) { 8359 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8360 numberOfPackagesToDexopt + ": " + pkg.packageName); 8361 } 8362 8363 if (showDialog) { 8364 try { 8365 ActivityManager.getService().showBootMessage( 8366 mContext.getResources().getString(R.string.android_upgrading_apk, 8367 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8368 } catch (RemoteException e) { 8369 } 8370 synchronized (mPackages) { 8371 mDexOptDialogShown = true; 8372 } 8373 } 8374 8375 // If the OTA updates a system app which was previously preopted to a non-preopted state 8376 // the app might end up being verified at runtime. That's because by default the apps 8377 // are verify-profile but for preopted apps there's no profile. 8378 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8379 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8380 // filter (by default interpret-only). 8381 // Note that at this stage unused apps are already filtered. 8382 if (isSystemApp(pkg) && 8383 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8384 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8385 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8386 } 8387 8388 // checkProfiles is false to avoid merging profiles during boot which 8389 // might interfere with background compilation (b/28612421). 8390 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8391 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8392 // trade-off worth doing to save boot time work. 8393 int dexOptStatus = performDexOptTraced(pkg.packageName, 8394 false /* checkProfiles */, 8395 compilerFilter, 8396 false /* force */); 8397 switch (dexOptStatus) { 8398 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8399 numberOfPackagesOptimized++; 8400 break; 8401 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8402 numberOfPackagesSkipped++; 8403 break; 8404 case PackageDexOptimizer.DEX_OPT_FAILED: 8405 numberOfPackagesFailed++; 8406 break; 8407 default: 8408 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8409 break; 8410 } 8411 } 8412 8413 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8414 numberOfPackagesFailed }; 8415 } 8416 8417 @Override 8418 public void notifyPackageUse(String packageName, int reason) { 8419 synchronized (mPackages) { 8420 PackageParser.Package p = mPackages.get(packageName); 8421 if (p == null) { 8422 return; 8423 } 8424 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8425 } 8426 } 8427 8428 @Override 8429 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8430 int userId = UserHandle.getCallingUserId(); 8431 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8432 if (ai == null) { 8433 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8434 + loadingPackageName + ", user=" + userId); 8435 return; 8436 } 8437 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8438 } 8439 8440 // TODO: this is not used nor needed. Delete it. 8441 @Override 8442 public boolean performDexOptIfNeeded(String packageName) { 8443 int dexOptStatus = performDexOptTraced(packageName, 8444 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8445 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8446 } 8447 8448 @Override 8449 public boolean performDexOpt(String packageName, 8450 boolean checkProfiles, int compileReason, boolean force) { 8451 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8452 getCompilerFilterForReason(compileReason), force); 8453 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8454 } 8455 8456 @Override 8457 public boolean performDexOptMode(String packageName, 8458 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8459 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8460 targetCompilerFilter, force); 8461 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8462 } 8463 8464 private int performDexOptTraced(String packageName, 8465 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8466 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8467 try { 8468 return performDexOptInternal(packageName, checkProfiles, 8469 targetCompilerFilter, force); 8470 } finally { 8471 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8472 } 8473 } 8474 8475 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8476 // if the package can now be considered up to date for the given filter. 8477 private int performDexOptInternal(String packageName, 8478 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8479 PackageParser.Package p; 8480 synchronized (mPackages) { 8481 p = mPackages.get(packageName); 8482 if (p == null) { 8483 // Package could not be found. Report failure. 8484 return PackageDexOptimizer.DEX_OPT_FAILED; 8485 } 8486 mPackageUsage.maybeWriteAsync(mPackages); 8487 mCompilerStats.maybeWriteAsync(); 8488 } 8489 long callingId = Binder.clearCallingIdentity(); 8490 try { 8491 synchronized (mInstallLock) { 8492 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8493 targetCompilerFilter, force); 8494 } 8495 } finally { 8496 Binder.restoreCallingIdentity(callingId); 8497 } 8498 } 8499 8500 public ArraySet<String> getOptimizablePackages() { 8501 ArraySet<String> pkgs = new ArraySet<String>(); 8502 synchronized (mPackages) { 8503 for (PackageParser.Package p : mPackages.values()) { 8504 if (PackageDexOptimizer.canOptimizePackage(p)) { 8505 pkgs.add(p.packageName); 8506 } 8507 } 8508 } 8509 return pkgs; 8510 } 8511 8512 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8513 boolean checkProfiles, String targetCompilerFilter, 8514 boolean force) { 8515 // Select the dex optimizer based on the force parameter. 8516 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8517 // allocate an object here. 8518 PackageDexOptimizer pdo = force 8519 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8520 : mPackageDexOptimizer; 8521 8522 // Dexopt all dependencies first. Note: we ignore the return value and march on 8523 // on errors. 8524 // Note that we are going to call performDexOpt on those libraries as many times as 8525 // they are referenced in packages. When we do a batch of performDexOpt (for example 8526 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8527 // and the first package that uses the library will dexopt it. The 8528 // others will see that the compiled code for the library is up to date. 8529 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8530 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8531 if (!deps.isEmpty()) { 8532 for (PackageParser.Package depPackage : deps) { 8533 // TODO: Analyze and investigate if we (should) profile libraries. 8534 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8535 false /* checkProfiles */, 8536 targetCompilerFilter, 8537 getOrCreateCompilerPackageStats(depPackage), 8538 true /* isUsedByOtherApps */); 8539 } 8540 } 8541 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8542 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8543 mDexManager.isUsedByOtherApps(p.packageName)); 8544 } 8545 8546 // Performs dexopt on the used secondary dex files belonging to the given package. 8547 // Returns true if all dex files were process successfully (which could mean either dexopt or 8548 // skip). Returns false if any of the files caused errors. 8549 @Override 8550 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8551 boolean force) { 8552 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8553 } 8554 8555 public boolean performDexOptSecondary(String packageName, int compileReason, 8556 boolean force) { 8557 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8558 } 8559 8560 /** 8561 * Reconcile the information we have about the secondary dex files belonging to 8562 * {@code packagName} and the actual dex files. For all dex files that were 8563 * deleted, update the internal records and delete the generated oat files. 8564 */ 8565 @Override 8566 public void reconcileSecondaryDexFiles(String packageName) { 8567 mDexManager.reconcileSecondaryDexFiles(packageName); 8568 } 8569 8570 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8571 // a reference there. 8572 /*package*/ DexManager getDexManager() { 8573 return mDexManager; 8574 } 8575 8576 /** 8577 * Execute the background dexopt job immediately. 8578 */ 8579 @Override 8580 public boolean runBackgroundDexoptJob() { 8581 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8582 } 8583 8584 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8585 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8586 || p.usesStaticLibraries != null) { 8587 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8588 Set<String> collectedNames = new HashSet<>(); 8589 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8590 8591 retValue.remove(p); 8592 8593 return retValue; 8594 } else { 8595 return Collections.emptyList(); 8596 } 8597 } 8598 8599 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8600 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8601 if (!collectedNames.contains(p.packageName)) { 8602 collectedNames.add(p.packageName); 8603 collected.add(p); 8604 8605 if (p.usesLibraries != null) { 8606 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8607 null, collected, collectedNames); 8608 } 8609 if (p.usesOptionalLibraries != null) { 8610 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8611 null, collected, collectedNames); 8612 } 8613 if (p.usesStaticLibraries != null) { 8614 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8615 p.usesStaticLibrariesVersions, collected, collectedNames); 8616 } 8617 } 8618 } 8619 8620 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8621 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8622 final int libNameCount = libs.size(); 8623 for (int i = 0; i < libNameCount; i++) { 8624 String libName = libs.get(i); 8625 int version = (versions != null && versions.length == libNameCount) 8626 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8627 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8628 if (libPkg != null) { 8629 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8630 } 8631 } 8632 } 8633 8634 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8635 synchronized (mPackages) { 8636 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8637 if (libEntry != null) { 8638 return mPackages.get(libEntry.apk); 8639 } 8640 return null; 8641 } 8642 } 8643 8644 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8645 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8646 if (versionedLib == null) { 8647 return null; 8648 } 8649 return versionedLib.get(version); 8650 } 8651 8652 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8653 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8654 pkg.staticSharedLibName); 8655 if (versionedLib == null) { 8656 return null; 8657 } 8658 int previousLibVersion = -1; 8659 final int versionCount = versionedLib.size(); 8660 for (int i = 0; i < versionCount; i++) { 8661 final int libVersion = versionedLib.keyAt(i); 8662 if (libVersion < pkg.staticSharedLibVersion) { 8663 previousLibVersion = Math.max(previousLibVersion, libVersion); 8664 } 8665 } 8666 if (previousLibVersion >= 0) { 8667 return versionedLib.get(previousLibVersion); 8668 } 8669 return null; 8670 } 8671 8672 public void shutdown() { 8673 mPackageUsage.writeNow(mPackages); 8674 mCompilerStats.writeNow(); 8675 } 8676 8677 @Override 8678 public void dumpProfiles(String packageName) { 8679 PackageParser.Package pkg; 8680 synchronized (mPackages) { 8681 pkg = mPackages.get(packageName); 8682 if (pkg == null) { 8683 throw new IllegalArgumentException("Unknown package: " + packageName); 8684 } 8685 } 8686 /* Only the shell, root, or the app user should be able to dump profiles. */ 8687 int callingUid = Binder.getCallingUid(); 8688 if (callingUid != Process.SHELL_UID && 8689 callingUid != Process.ROOT_UID && 8690 callingUid != pkg.applicationInfo.uid) { 8691 throw new SecurityException("dumpProfiles"); 8692 } 8693 8694 synchronized (mInstallLock) { 8695 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8696 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8697 try { 8698 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8699 String codePaths = TextUtils.join(";", allCodePaths); 8700 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8701 } catch (InstallerException e) { 8702 Slog.w(TAG, "Failed to dump profiles", e); 8703 } 8704 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8705 } 8706 } 8707 8708 @Override 8709 public void forceDexOpt(String packageName) { 8710 enforceSystemOrRoot("forceDexOpt"); 8711 8712 PackageParser.Package pkg; 8713 synchronized (mPackages) { 8714 pkg = mPackages.get(packageName); 8715 if (pkg == null) { 8716 throw new IllegalArgumentException("Unknown package: " + packageName); 8717 } 8718 } 8719 8720 synchronized (mInstallLock) { 8721 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8722 8723 // Whoever is calling forceDexOpt wants a fully compiled package. 8724 // Don't use profiles since that may cause compilation to be skipped. 8725 final int res = performDexOptInternalWithDependenciesLI(pkg, 8726 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8727 true /* force */); 8728 8729 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8730 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8731 throw new IllegalStateException("Failed to dexopt: " + res); 8732 } 8733 } 8734 } 8735 8736 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8737 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8738 Slog.w(TAG, "Unable to update from " + oldPkg.name 8739 + " to " + newPkg.packageName 8740 + ": old package not in system partition"); 8741 return false; 8742 } else if (mPackages.get(oldPkg.name) != null) { 8743 Slog.w(TAG, "Unable to update from " + oldPkg.name 8744 + " to " + newPkg.packageName 8745 + ": old package still exists"); 8746 return false; 8747 } 8748 return true; 8749 } 8750 8751 void removeCodePathLI(File codePath) { 8752 if (codePath.isDirectory()) { 8753 try { 8754 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8755 } catch (InstallerException e) { 8756 Slog.w(TAG, "Failed to remove code path", e); 8757 } 8758 } else { 8759 codePath.delete(); 8760 } 8761 } 8762 8763 private int[] resolveUserIds(int userId) { 8764 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8765 } 8766 8767 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8768 if (pkg == null) { 8769 Slog.wtf(TAG, "Package was null!", new Throwable()); 8770 return; 8771 } 8772 clearAppDataLeafLIF(pkg, userId, flags); 8773 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8774 for (int i = 0; i < childCount; i++) { 8775 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8776 } 8777 } 8778 8779 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8780 final PackageSetting ps; 8781 synchronized (mPackages) { 8782 ps = mSettings.mPackages.get(pkg.packageName); 8783 } 8784 for (int realUserId : resolveUserIds(userId)) { 8785 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8786 try { 8787 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8788 ceDataInode); 8789 } catch (InstallerException e) { 8790 Slog.w(TAG, String.valueOf(e)); 8791 } 8792 } 8793 } 8794 8795 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8796 if (pkg == null) { 8797 Slog.wtf(TAG, "Package was null!", new Throwable()); 8798 return; 8799 } 8800 destroyAppDataLeafLIF(pkg, userId, flags); 8801 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8802 for (int i = 0; i < childCount; i++) { 8803 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8804 } 8805 } 8806 8807 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8808 final PackageSetting ps; 8809 synchronized (mPackages) { 8810 ps = mSettings.mPackages.get(pkg.packageName); 8811 } 8812 for (int realUserId : resolveUserIds(userId)) { 8813 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8814 try { 8815 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8816 ceDataInode); 8817 } catch (InstallerException e) { 8818 Slog.w(TAG, String.valueOf(e)); 8819 } 8820 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8821 } 8822 } 8823 8824 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8825 if (pkg == null) { 8826 Slog.wtf(TAG, "Package was null!", new Throwable()); 8827 return; 8828 } 8829 destroyAppProfilesLeafLIF(pkg); 8830 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8831 for (int i = 0; i < childCount; i++) { 8832 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8833 } 8834 } 8835 8836 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8837 try { 8838 mInstaller.destroyAppProfiles(pkg.packageName); 8839 } catch (InstallerException e) { 8840 Slog.w(TAG, String.valueOf(e)); 8841 } 8842 } 8843 8844 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8845 if (pkg == null) { 8846 Slog.wtf(TAG, "Package was null!", new Throwable()); 8847 return; 8848 } 8849 clearAppProfilesLeafLIF(pkg); 8850 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8851 for (int i = 0; i < childCount; i++) { 8852 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8853 } 8854 } 8855 8856 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8857 try { 8858 mInstaller.clearAppProfiles(pkg.packageName); 8859 } catch (InstallerException e) { 8860 Slog.w(TAG, String.valueOf(e)); 8861 } 8862 } 8863 8864 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8865 long lastUpdateTime) { 8866 // Set parent install/update time 8867 PackageSetting ps = (PackageSetting) pkg.mExtras; 8868 if (ps != null) { 8869 ps.firstInstallTime = firstInstallTime; 8870 ps.lastUpdateTime = lastUpdateTime; 8871 } 8872 // Set children install/update time 8873 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8874 for (int i = 0; i < childCount; i++) { 8875 PackageParser.Package childPkg = pkg.childPackages.get(i); 8876 ps = (PackageSetting) childPkg.mExtras; 8877 if (ps != null) { 8878 ps.firstInstallTime = firstInstallTime; 8879 ps.lastUpdateTime = lastUpdateTime; 8880 } 8881 } 8882 } 8883 8884 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8885 PackageParser.Package changingLib) { 8886 if (file.path != null) { 8887 usesLibraryFiles.add(file.path); 8888 return; 8889 } 8890 PackageParser.Package p = mPackages.get(file.apk); 8891 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8892 // If we are doing this while in the middle of updating a library apk, 8893 // then we need to make sure to use that new apk for determining the 8894 // dependencies here. (We haven't yet finished committing the new apk 8895 // to the package manager state.) 8896 if (p == null || p.packageName.equals(changingLib.packageName)) { 8897 p = changingLib; 8898 } 8899 } 8900 if (p != null) { 8901 usesLibraryFiles.addAll(p.getAllCodePaths()); 8902 } 8903 } 8904 8905 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8906 PackageParser.Package changingLib) throws PackageManagerException { 8907 if (pkg == null) { 8908 return; 8909 } 8910 ArraySet<String> usesLibraryFiles = null; 8911 if (pkg.usesLibraries != null) { 8912 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8913 null, null, pkg.packageName, changingLib, true, null); 8914 } 8915 if (pkg.usesStaticLibraries != null) { 8916 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8917 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8918 pkg.packageName, changingLib, true, usesLibraryFiles); 8919 } 8920 if (pkg.usesOptionalLibraries != null) { 8921 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8922 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8923 } 8924 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8925 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8926 } else { 8927 pkg.usesLibraryFiles = null; 8928 } 8929 } 8930 8931 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8932 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8933 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8934 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8935 throws PackageManagerException { 8936 final int libCount = requestedLibraries.size(); 8937 for (int i = 0; i < libCount; i++) { 8938 final String libName = requestedLibraries.get(i); 8939 final int libVersion = requiredVersions != null ? requiredVersions[i] 8940 : SharedLibraryInfo.VERSION_UNDEFINED; 8941 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8942 if (libEntry == null) { 8943 if (required) { 8944 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8945 "Package " + packageName + " requires unavailable shared library " 8946 + libName + "; failing!"); 8947 } else { 8948 Slog.w(TAG, "Package " + packageName 8949 + " desires unavailable shared library " 8950 + libName + "; ignoring!"); 8951 } 8952 } else { 8953 if (requiredVersions != null && requiredCertDigests != null) { 8954 if (libEntry.info.getVersion() != requiredVersions[i]) { 8955 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8956 "Package " + packageName + " requires unavailable static shared" 8957 + " library " + libName + " version " 8958 + libEntry.info.getVersion() + "; failing!"); 8959 } 8960 8961 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8962 if (libPkg == null) { 8963 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8964 "Package " + packageName + " requires unavailable static shared" 8965 + " library; failing!"); 8966 } 8967 8968 String expectedCertDigest = requiredCertDigests[i]; 8969 String libCertDigest = PackageUtils.computeCertSha256Digest( 8970 libPkg.mSignatures[0]); 8971 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8972 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8973 "Package " + packageName + " requires differently signed" + 8974 " static shared library; failing!"); 8975 } 8976 } 8977 8978 if (outUsedLibraries == null) { 8979 outUsedLibraries = new ArraySet<>(); 8980 } 8981 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8982 } 8983 } 8984 return outUsedLibraries; 8985 } 8986 8987 private static boolean hasString(List<String> list, List<String> which) { 8988 if (list == null) { 8989 return false; 8990 } 8991 for (int i=list.size()-1; i>=0; i--) { 8992 for (int j=which.size()-1; j>=0; j--) { 8993 if (which.get(j).equals(list.get(i))) { 8994 return true; 8995 } 8996 } 8997 } 8998 return false; 8999 } 9000 9001 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9002 PackageParser.Package changingPkg) { 9003 ArrayList<PackageParser.Package> res = null; 9004 for (PackageParser.Package pkg : mPackages.values()) { 9005 if (changingPkg != null 9006 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9007 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9008 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9009 changingPkg.staticSharedLibName)) { 9010 return null; 9011 } 9012 if (res == null) { 9013 res = new ArrayList<>(); 9014 } 9015 res.add(pkg); 9016 try { 9017 updateSharedLibrariesLPr(pkg, changingPkg); 9018 } catch (PackageManagerException e) { 9019 // If a system app update or an app and a required lib missing we 9020 // delete the package and for updated system apps keep the data as 9021 // it is better for the user to reinstall than to be in an limbo 9022 // state. Also libs disappearing under an app should never happen 9023 // - just in case. 9024 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9025 final int flags = pkg.isUpdatedSystemApp() 9026 ? PackageManager.DELETE_KEEP_DATA : 0; 9027 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9028 flags , null, true, null); 9029 } 9030 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9031 } 9032 } 9033 return res; 9034 } 9035 9036 /** 9037 * Derive the value of the {@code cpuAbiOverride} based on the provided 9038 * value and an optional stored value from the package settings. 9039 */ 9040 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9041 String cpuAbiOverride = null; 9042 9043 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9044 cpuAbiOverride = null; 9045 } else if (abiOverride != null) { 9046 cpuAbiOverride = abiOverride; 9047 } else if (settings != null) { 9048 cpuAbiOverride = settings.cpuAbiOverrideString; 9049 } 9050 9051 return cpuAbiOverride; 9052 } 9053 9054 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9055 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9056 throws PackageManagerException { 9057 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9058 // If the package has children and this is the first dive in the function 9059 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9060 // whether all packages (parent and children) would be successfully scanned 9061 // before the actual scan since scanning mutates internal state and we want 9062 // to atomically install the package and its children. 9063 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9064 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9065 scanFlags |= SCAN_CHECK_ONLY; 9066 } 9067 } else { 9068 scanFlags &= ~SCAN_CHECK_ONLY; 9069 } 9070 9071 final PackageParser.Package scannedPkg; 9072 try { 9073 // Scan the parent 9074 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9075 // Scan the children 9076 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9077 for (int i = 0; i < childCount; i++) { 9078 PackageParser.Package childPkg = pkg.childPackages.get(i); 9079 scanPackageLI(childPkg, policyFlags, 9080 scanFlags, currentTime, user); 9081 } 9082 } finally { 9083 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9084 } 9085 9086 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9087 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9088 } 9089 9090 return scannedPkg; 9091 } 9092 9093 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9094 int scanFlags, long currentTime, @Nullable UserHandle user) 9095 throws PackageManagerException { 9096 boolean success = false; 9097 try { 9098 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9099 currentTime, user); 9100 success = true; 9101 return res; 9102 } finally { 9103 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9104 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9105 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9106 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9107 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9108 } 9109 } 9110 } 9111 9112 /** 9113 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9114 */ 9115 private static boolean apkHasCode(String fileName) { 9116 StrictJarFile jarFile = null; 9117 try { 9118 jarFile = new StrictJarFile(fileName, 9119 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9120 return jarFile.findEntry("classes.dex") != null; 9121 } catch (IOException ignore) { 9122 } finally { 9123 try { 9124 if (jarFile != null) { 9125 jarFile.close(); 9126 } 9127 } catch (IOException ignore) {} 9128 } 9129 return false; 9130 } 9131 9132 /** 9133 * Enforces code policy for the package. This ensures that if an APK has 9134 * declared hasCode="true" in its manifest that the APK actually contains 9135 * code. 9136 * 9137 * @throws PackageManagerException If bytecode could not be found when it should exist 9138 */ 9139 private static void assertCodePolicy(PackageParser.Package pkg) 9140 throws PackageManagerException { 9141 final boolean shouldHaveCode = 9142 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9143 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9144 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9145 "Package " + pkg.baseCodePath + " code is missing"); 9146 } 9147 9148 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9149 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9150 final boolean splitShouldHaveCode = 9151 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9152 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9153 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9154 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9155 } 9156 } 9157 } 9158 } 9159 9160 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9161 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9162 throws PackageManagerException { 9163 if (DEBUG_PACKAGE_SCANNING) { 9164 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9165 Log.d(TAG, "Scanning package " + pkg.packageName); 9166 } 9167 9168 applyPolicy(pkg, policyFlags); 9169 9170 assertPackageIsValid(pkg, policyFlags, scanFlags); 9171 9172 // Initialize package source and resource directories 9173 final File scanFile = new File(pkg.codePath); 9174 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9175 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9176 9177 SharedUserSetting suid = null; 9178 PackageSetting pkgSetting = null; 9179 9180 // Getting the package setting may have a side-effect, so if we 9181 // are only checking if scan would succeed, stash a copy of the 9182 // old setting to restore at the end. 9183 PackageSetting nonMutatedPs = null; 9184 9185 // We keep references to the derived CPU Abis from settings in oder to reuse 9186 // them in the case where we're not upgrading or booting for the first time. 9187 String primaryCpuAbiFromSettings = null; 9188 String secondaryCpuAbiFromSettings = null; 9189 9190 // writer 9191 synchronized (mPackages) { 9192 if (pkg.mSharedUserId != null) { 9193 // SIDE EFFECTS; may potentially allocate a new shared user 9194 suid = mSettings.getSharedUserLPw( 9195 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9196 if (DEBUG_PACKAGE_SCANNING) { 9197 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9198 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9199 + "): packages=" + suid.packages); 9200 } 9201 } 9202 9203 // Check if we are renaming from an original package name. 9204 PackageSetting origPackage = null; 9205 String realName = null; 9206 if (pkg.mOriginalPackages != null) { 9207 // This package may need to be renamed to a previously 9208 // installed name. Let's check on that... 9209 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9210 if (pkg.mOriginalPackages.contains(renamed)) { 9211 // This package had originally been installed as the 9212 // original name, and we have already taken care of 9213 // transitioning to the new one. Just update the new 9214 // one to continue using the old name. 9215 realName = pkg.mRealPackage; 9216 if (!pkg.packageName.equals(renamed)) { 9217 // Callers into this function may have already taken 9218 // care of renaming the package; only do it here if 9219 // it is not already done. 9220 pkg.setPackageName(renamed); 9221 } 9222 } else { 9223 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9224 if ((origPackage = mSettings.getPackageLPr( 9225 pkg.mOriginalPackages.get(i))) != null) { 9226 // We do have the package already installed under its 9227 // original name... should we use it? 9228 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9229 // New package is not compatible with original. 9230 origPackage = null; 9231 continue; 9232 } else if (origPackage.sharedUser != null) { 9233 // Make sure uid is compatible between packages. 9234 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9235 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9236 + " to " + pkg.packageName + ": old uid " 9237 + origPackage.sharedUser.name 9238 + " differs from " + pkg.mSharedUserId); 9239 origPackage = null; 9240 continue; 9241 } 9242 // TODO: Add case when shared user id is added [b/28144775] 9243 } else { 9244 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9245 + pkg.packageName + " to old name " + origPackage.name); 9246 } 9247 break; 9248 } 9249 } 9250 } 9251 } 9252 9253 if (mTransferedPackages.contains(pkg.packageName)) { 9254 Slog.w(TAG, "Package " + pkg.packageName 9255 + " was transferred to another, but its .apk remains"); 9256 } 9257 9258 // See comments in nonMutatedPs declaration 9259 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9260 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9261 if (foundPs != null) { 9262 nonMutatedPs = new PackageSetting(foundPs); 9263 } 9264 } 9265 9266 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9267 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9268 if (foundPs != null) { 9269 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9270 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9271 } 9272 } 9273 9274 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9275 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9276 PackageManagerService.reportSettingsProblem(Log.WARN, 9277 "Package " + pkg.packageName + " shared user changed from " 9278 + (pkgSetting.sharedUser != null 9279 ? pkgSetting.sharedUser.name : "<nothing>") 9280 + " to " 9281 + (suid != null ? suid.name : "<nothing>") 9282 + "; replacing with new"); 9283 pkgSetting = null; 9284 } 9285 final PackageSetting oldPkgSetting = 9286 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9287 final PackageSetting disabledPkgSetting = 9288 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9289 9290 String[] usesStaticLibraries = null; 9291 if (pkg.usesStaticLibraries != null) { 9292 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9293 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9294 } 9295 9296 if (pkgSetting == null) { 9297 final String parentPackageName = (pkg.parentPackage != null) 9298 ? pkg.parentPackage.packageName : null; 9299 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9300 // REMOVE SharedUserSetting from method; update in a separate call 9301 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9302 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9303 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9304 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9305 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9306 true /*allowInstall*/, instantApp, parentPackageName, 9307 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9308 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9309 // SIDE EFFECTS; updates system state; move elsewhere 9310 if (origPackage != null) { 9311 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9312 } 9313 mSettings.addUserToSettingLPw(pkgSetting); 9314 } else { 9315 // REMOVE SharedUserSetting from method; update in a separate call. 9316 // 9317 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9318 // secondaryCpuAbi are not known at this point so we always update them 9319 // to null here, only to reset them at a later point. 9320 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9321 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9322 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9323 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9324 UserManagerService.getInstance(), usesStaticLibraries, 9325 pkg.usesStaticLibrariesVersions); 9326 } 9327 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9328 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9329 9330 // SIDE EFFECTS; modifies system state; move elsewhere 9331 if (pkgSetting.origPackage != null) { 9332 // If we are first transitioning from an original package, 9333 // fix up the new package's name now. We need to do this after 9334 // looking up the package under its new name, so getPackageLP 9335 // can take care of fiddling things correctly. 9336 pkg.setPackageName(origPackage.name); 9337 9338 // File a report about this. 9339 String msg = "New package " + pkgSetting.realName 9340 + " renamed to replace old package " + pkgSetting.name; 9341 reportSettingsProblem(Log.WARN, msg); 9342 9343 // Make a note of it. 9344 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9345 mTransferedPackages.add(origPackage.name); 9346 } 9347 9348 // No longer need to retain this. 9349 pkgSetting.origPackage = null; 9350 } 9351 9352 // SIDE EFFECTS; modifies system state; move elsewhere 9353 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9354 // Make a note of it. 9355 mTransferedPackages.add(pkg.packageName); 9356 } 9357 9358 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9359 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9360 } 9361 9362 if ((scanFlags & SCAN_BOOTING) == 0 9363 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9364 // Check all shared libraries and map to their actual file path. 9365 // We only do this here for apps not on a system dir, because those 9366 // are the only ones that can fail an install due to this. We 9367 // will take care of the system apps by updating all of their 9368 // library paths after the scan is done. Also during the initial 9369 // scan don't update any libs as we do this wholesale after all 9370 // apps are scanned to avoid dependency based scanning. 9371 updateSharedLibrariesLPr(pkg, null); 9372 } 9373 9374 if (mFoundPolicyFile) { 9375 SELinuxMMAC.assignSeInfoValue(pkg); 9376 } 9377 pkg.applicationInfo.uid = pkgSetting.appId; 9378 pkg.mExtras = pkgSetting; 9379 9380 9381 // Static shared libs have same package with different versions where 9382 // we internally use a synthetic package name to allow multiple versions 9383 // of the same package, therefore we need to compare signatures against 9384 // the package setting for the latest library version. 9385 PackageSetting signatureCheckPs = pkgSetting; 9386 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9387 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9388 if (libraryEntry != null) { 9389 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9390 } 9391 } 9392 9393 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9394 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9395 // We just determined the app is signed correctly, so bring 9396 // over the latest parsed certs. 9397 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9398 } else { 9399 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9400 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9401 "Package " + pkg.packageName + " upgrade keys do not match the " 9402 + "previously installed version"); 9403 } else { 9404 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9405 String msg = "System package " + pkg.packageName 9406 + " signature changed; retaining data."; 9407 reportSettingsProblem(Log.WARN, msg); 9408 } 9409 } 9410 } else { 9411 try { 9412 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9413 verifySignaturesLP(signatureCheckPs, pkg); 9414 // We just determined the app is signed correctly, so bring 9415 // over the latest parsed certs. 9416 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9417 } catch (PackageManagerException e) { 9418 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9419 throw e; 9420 } 9421 // The signature has changed, but this package is in the system 9422 // image... let's recover! 9423 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9424 // However... if this package is part of a shared user, but it 9425 // doesn't match the signature of the shared user, let's fail. 9426 // What this means is that you can't change the signatures 9427 // associated with an overall shared user, which doesn't seem all 9428 // that unreasonable. 9429 if (signatureCheckPs.sharedUser != null) { 9430 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9431 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9432 throw new PackageManagerException( 9433 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9434 "Signature mismatch for shared user: " 9435 + pkgSetting.sharedUser); 9436 } 9437 } 9438 // File a report about this. 9439 String msg = "System package " + pkg.packageName 9440 + " signature changed; retaining data."; 9441 reportSettingsProblem(Log.WARN, msg); 9442 } 9443 } 9444 9445 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9446 // This package wants to adopt ownership of permissions from 9447 // another package. 9448 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9449 final String origName = pkg.mAdoptPermissions.get(i); 9450 final PackageSetting orig = mSettings.getPackageLPr(origName); 9451 if (orig != null) { 9452 if (verifyPackageUpdateLPr(orig, pkg)) { 9453 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9454 + pkg.packageName); 9455 // SIDE EFFECTS; updates permissions system state; move elsewhere 9456 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9457 } 9458 } 9459 } 9460 } 9461 } 9462 9463 pkg.applicationInfo.processName = fixProcessName( 9464 pkg.applicationInfo.packageName, 9465 pkg.applicationInfo.processName); 9466 9467 if (pkg != mPlatformPackage) { 9468 // Get all of our default paths setup 9469 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9470 } 9471 9472 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9473 9474 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9475 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9476 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9477 derivePackageAbi( 9478 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9479 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9480 9481 // Some system apps still use directory structure for native libraries 9482 // in which case we might end up not detecting abi solely based on apk 9483 // structure. Try to detect abi based on directory structure. 9484 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9485 pkg.applicationInfo.primaryCpuAbi == null) { 9486 setBundledAppAbisAndRoots(pkg, pkgSetting); 9487 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9488 } 9489 } else { 9490 // This is not a first boot or an upgrade, don't bother deriving the 9491 // ABI during the scan. Instead, trust the value that was stored in the 9492 // package setting. 9493 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9494 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9495 9496 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9497 9498 if (DEBUG_ABI_SELECTION) { 9499 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9500 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9501 pkg.applicationInfo.secondaryCpuAbi); 9502 } 9503 } 9504 } else { 9505 if ((scanFlags & SCAN_MOVE) != 0) { 9506 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9507 // but we already have this packages package info in the PackageSetting. We just 9508 // use that and derive the native library path based on the new codepath. 9509 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9510 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9511 } 9512 9513 // Set native library paths again. For moves, the path will be updated based on the 9514 // ABIs we've determined above. For non-moves, the path will be updated based on the 9515 // ABIs we determined during compilation, but the path will depend on the final 9516 // package path (after the rename away from the stage path). 9517 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9518 } 9519 9520 // This is a special case for the "system" package, where the ABI is 9521 // dictated by the zygote configuration (and init.rc). We should keep track 9522 // of this ABI so that we can deal with "normal" applications that run under 9523 // the same UID correctly. 9524 if (mPlatformPackage == pkg) { 9525 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9526 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9527 } 9528 9529 // If there's a mismatch between the abi-override in the package setting 9530 // and the abiOverride specified for the install. Warn about this because we 9531 // would've already compiled the app without taking the package setting into 9532 // account. 9533 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9534 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9535 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9536 " for package " + pkg.packageName); 9537 } 9538 } 9539 9540 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9541 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9542 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9543 9544 // Copy the derived override back to the parsed package, so that we can 9545 // update the package settings accordingly. 9546 pkg.cpuAbiOverride = cpuAbiOverride; 9547 9548 if (DEBUG_ABI_SELECTION) { 9549 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9550 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9551 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9552 } 9553 9554 // Push the derived path down into PackageSettings so we know what to 9555 // clean up at uninstall time. 9556 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9557 9558 if (DEBUG_ABI_SELECTION) { 9559 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9560 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9561 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9562 } 9563 9564 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9565 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9566 // We don't do this here during boot because we can do it all 9567 // at once after scanning all existing packages. 9568 // 9569 // We also do this *before* we perform dexopt on this package, so that 9570 // we can avoid redundant dexopts, and also to make sure we've got the 9571 // code and package path correct. 9572 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9573 } 9574 9575 if (mFactoryTest && pkg.requestedPermissions.contains( 9576 android.Manifest.permission.FACTORY_TEST)) { 9577 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9578 } 9579 9580 if (isSystemApp(pkg)) { 9581 pkgSetting.isOrphaned = true; 9582 } 9583 9584 // Take care of first install / last update times. 9585 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9586 if (currentTime != 0) { 9587 if (pkgSetting.firstInstallTime == 0) { 9588 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9589 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9590 pkgSetting.lastUpdateTime = currentTime; 9591 } 9592 } else if (pkgSetting.firstInstallTime == 0) { 9593 // We need *something*. Take time time stamp of the file. 9594 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9595 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9596 if (scanFileTime != pkgSetting.timeStamp) { 9597 // A package on the system image has changed; consider this 9598 // to be an update. 9599 pkgSetting.lastUpdateTime = scanFileTime; 9600 } 9601 } 9602 pkgSetting.setTimeStamp(scanFileTime); 9603 9604 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9605 if (nonMutatedPs != null) { 9606 synchronized (mPackages) { 9607 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9608 } 9609 } 9610 } else { 9611 final int userId = user == null ? 0 : user.getIdentifier(); 9612 // Modify state for the given package setting 9613 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9614 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9615 if (pkgSetting.getInstantApp(userId)) { 9616 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9617 } 9618 } 9619 return pkg; 9620 } 9621 9622 /** 9623 * Applies policy to the parsed package based upon the given policy flags. 9624 * Ensures the package is in a good state. 9625 * <p> 9626 * Implementation detail: This method must NOT have any side effect. It would 9627 * ideally be static, but, it requires locks to read system state. 9628 */ 9629 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9630 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9631 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9632 if (pkg.applicationInfo.isDirectBootAware()) { 9633 // we're direct boot aware; set for all components 9634 for (PackageParser.Service s : pkg.services) { 9635 s.info.encryptionAware = s.info.directBootAware = true; 9636 } 9637 for (PackageParser.Provider p : pkg.providers) { 9638 p.info.encryptionAware = p.info.directBootAware = true; 9639 } 9640 for (PackageParser.Activity a : pkg.activities) { 9641 a.info.encryptionAware = a.info.directBootAware = true; 9642 } 9643 for (PackageParser.Activity r : pkg.receivers) { 9644 r.info.encryptionAware = r.info.directBootAware = true; 9645 } 9646 } 9647 } else { 9648 // Only allow system apps to be flagged as core apps. 9649 pkg.coreApp = false; 9650 // clear flags not applicable to regular apps 9651 pkg.applicationInfo.privateFlags &= 9652 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9653 pkg.applicationInfo.privateFlags &= 9654 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9655 } 9656 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9657 9658 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9659 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9660 } 9661 9662 if (!isSystemApp(pkg)) { 9663 // Only system apps can use these features. 9664 pkg.mOriginalPackages = null; 9665 pkg.mRealPackage = null; 9666 pkg.mAdoptPermissions = null; 9667 } 9668 } 9669 9670 /** 9671 * Asserts the parsed package is valid according to the given policy. If the 9672 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9673 * <p> 9674 * Implementation detail: This method must NOT have any side effects. It would 9675 * ideally be static, but, it requires locks to read system state. 9676 * 9677 * @throws PackageManagerException If the package fails any of the validation checks 9678 */ 9679 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9680 throws PackageManagerException { 9681 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9682 assertCodePolicy(pkg); 9683 } 9684 9685 if (pkg.applicationInfo.getCodePath() == null || 9686 pkg.applicationInfo.getResourcePath() == null) { 9687 // Bail out. The resource and code paths haven't been set. 9688 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9689 "Code and resource paths haven't been set correctly"); 9690 } 9691 9692 // Make sure we're not adding any bogus keyset info 9693 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9694 ksms.assertScannedPackageValid(pkg); 9695 9696 synchronized (mPackages) { 9697 // The special "android" package can only be defined once 9698 if (pkg.packageName.equals("android")) { 9699 if (mAndroidApplication != null) { 9700 Slog.w(TAG, "*************************************************"); 9701 Slog.w(TAG, "Core android package being redefined. Skipping."); 9702 Slog.w(TAG, " codePath=" + pkg.codePath); 9703 Slog.w(TAG, "*************************************************"); 9704 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9705 "Core android package being redefined. Skipping."); 9706 } 9707 } 9708 9709 // A package name must be unique; don't allow duplicates 9710 if (mPackages.containsKey(pkg.packageName)) { 9711 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9712 "Application package " + pkg.packageName 9713 + " already installed. Skipping duplicate."); 9714 } 9715 9716 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9717 // Static libs have a synthetic package name containing the version 9718 // but we still want the base name to be unique. 9719 if (mPackages.containsKey(pkg.manifestPackageName)) { 9720 throw new PackageManagerException( 9721 "Duplicate static shared lib provider package"); 9722 } 9723 9724 // Static shared libraries should have at least O target SDK 9725 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9726 throw new PackageManagerException( 9727 "Packages declaring static-shared libs must target O SDK or higher"); 9728 } 9729 9730 // Package declaring static a shared lib cannot be instant apps 9731 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9732 throw new PackageManagerException( 9733 "Packages declaring static-shared libs cannot be instant apps"); 9734 } 9735 9736 // Package declaring static a shared lib cannot be renamed since the package 9737 // name is synthetic and apps can't code around package manager internals. 9738 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9739 throw new PackageManagerException( 9740 "Packages declaring static-shared libs cannot be renamed"); 9741 } 9742 9743 // Package declaring static a shared lib cannot declare child packages 9744 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9745 throw new PackageManagerException( 9746 "Packages declaring static-shared libs cannot have child packages"); 9747 } 9748 9749 // Package declaring static a shared lib cannot declare dynamic libs 9750 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9751 throw new PackageManagerException( 9752 "Packages declaring static-shared libs cannot declare dynamic libs"); 9753 } 9754 9755 // Package declaring static a shared lib cannot declare shared users 9756 if (pkg.mSharedUserId != null) { 9757 throw new PackageManagerException( 9758 "Packages declaring static-shared libs cannot declare shared users"); 9759 } 9760 9761 // Static shared libs cannot declare activities 9762 if (!pkg.activities.isEmpty()) { 9763 throw new PackageManagerException( 9764 "Static shared libs cannot declare activities"); 9765 } 9766 9767 // Static shared libs cannot declare services 9768 if (!pkg.services.isEmpty()) { 9769 throw new PackageManagerException( 9770 "Static shared libs cannot declare services"); 9771 } 9772 9773 // Static shared libs cannot declare providers 9774 if (!pkg.providers.isEmpty()) { 9775 throw new PackageManagerException( 9776 "Static shared libs cannot declare content providers"); 9777 } 9778 9779 // Static shared libs cannot declare receivers 9780 if (!pkg.receivers.isEmpty()) { 9781 throw new PackageManagerException( 9782 "Static shared libs cannot declare broadcast receivers"); 9783 } 9784 9785 // Static shared libs cannot declare permission groups 9786 if (!pkg.permissionGroups.isEmpty()) { 9787 throw new PackageManagerException( 9788 "Static shared libs cannot declare permission groups"); 9789 } 9790 9791 // Static shared libs cannot declare permissions 9792 if (!pkg.permissions.isEmpty()) { 9793 throw new PackageManagerException( 9794 "Static shared libs cannot declare permissions"); 9795 } 9796 9797 // Static shared libs cannot declare protected broadcasts 9798 if (pkg.protectedBroadcasts != null) { 9799 throw new PackageManagerException( 9800 "Static shared libs cannot declare protected broadcasts"); 9801 } 9802 9803 // Static shared libs cannot be overlay targets 9804 if (pkg.mOverlayTarget != null) { 9805 throw new PackageManagerException( 9806 "Static shared libs cannot be overlay targets"); 9807 } 9808 9809 // The version codes must be ordered as lib versions 9810 int minVersionCode = Integer.MIN_VALUE; 9811 int maxVersionCode = Integer.MAX_VALUE; 9812 9813 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9814 pkg.staticSharedLibName); 9815 if (versionedLib != null) { 9816 final int versionCount = versionedLib.size(); 9817 for (int i = 0; i < versionCount; i++) { 9818 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9819 // TODO: We will change version code to long, so in the new API it is long 9820 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9821 .getVersionCode(); 9822 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9823 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9824 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9825 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9826 } else { 9827 minVersionCode = maxVersionCode = libVersionCode; 9828 break; 9829 } 9830 } 9831 } 9832 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9833 throw new PackageManagerException("Static shared" 9834 + " lib version codes must be ordered as lib versions"); 9835 } 9836 } 9837 9838 // Only privileged apps and updated privileged apps can add child packages. 9839 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9840 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9841 throw new PackageManagerException("Only privileged apps can add child " 9842 + "packages. Ignoring package " + pkg.packageName); 9843 } 9844 final int childCount = pkg.childPackages.size(); 9845 for (int i = 0; i < childCount; i++) { 9846 PackageParser.Package childPkg = pkg.childPackages.get(i); 9847 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9848 childPkg.packageName)) { 9849 throw new PackageManagerException("Can't override child of " 9850 + "another disabled app. Ignoring package " + pkg.packageName); 9851 } 9852 } 9853 } 9854 9855 // If we're only installing presumed-existing packages, require that the 9856 // scanned APK is both already known and at the path previously established 9857 // for it. Previously unknown packages we pick up normally, but if we have an 9858 // a priori expectation about this package's install presence, enforce it. 9859 // With a singular exception for new system packages. When an OTA contains 9860 // a new system package, we allow the codepath to change from a system location 9861 // to the user-installed location. If we don't allow this change, any newer, 9862 // user-installed version of the application will be ignored. 9863 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9864 if (mExpectingBetter.containsKey(pkg.packageName)) { 9865 logCriticalInfo(Log.WARN, 9866 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9867 } else { 9868 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9869 if (known != null) { 9870 if (DEBUG_PACKAGE_SCANNING) { 9871 Log.d(TAG, "Examining " + pkg.codePath 9872 + " and requiring known paths " + known.codePathString 9873 + " & " + known.resourcePathString); 9874 } 9875 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9876 || !pkg.applicationInfo.getResourcePath().equals( 9877 known.resourcePathString)) { 9878 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9879 "Application package " + pkg.packageName 9880 + " found at " + pkg.applicationInfo.getCodePath() 9881 + " but expected at " + known.codePathString 9882 + "; ignoring."); 9883 } 9884 } 9885 } 9886 } 9887 9888 // Verify that this new package doesn't have any content providers 9889 // that conflict with existing packages. Only do this if the 9890 // package isn't already installed, since we don't want to break 9891 // things that are installed. 9892 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9893 final int N = pkg.providers.size(); 9894 int i; 9895 for (i=0; i<N; i++) { 9896 PackageParser.Provider p = pkg.providers.get(i); 9897 if (p.info.authority != null) { 9898 String names[] = p.info.authority.split(";"); 9899 for (int j = 0; j < names.length; j++) { 9900 if (mProvidersByAuthority.containsKey(names[j])) { 9901 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9902 final String otherPackageName = 9903 ((other != null && other.getComponentName() != null) ? 9904 other.getComponentName().getPackageName() : "?"); 9905 throw new PackageManagerException( 9906 INSTALL_FAILED_CONFLICTING_PROVIDER, 9907 "Can't install because provider name " + names[j] 9908 + " (in package " + pkg.applicationInfo.packageName 9909 + ") is already used by " + otherPackageName); 9910 } 9911 } 9912 } 9913 } 9914 } 9915 } 9916 } 9917 9918 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9919 int type, String declaringPackageName, int declaringVersionCode) { 9920 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9921 if (versionedLib == null) { 9922 versionedLib = new SparseArray<>(); 9923 mSharedLibraries.put(name, versionedLib); 9924 if (type == SharedLibraryInfo.TYPE_STATIC) { 9925 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9926 } 9927 } else if (versionedLib.indexOfKey(version) >= 0) { 9928 return false; 9929 } 9930 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9931 version, type, declaringPackageName, declaringVersionCode); 9932 versionedLib.put(version, libEntry); 9933 return true; 9934 } 9935 9936 private boolean removeSharedLibraryLPw(String name, int version) { 9937 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9938 if (versionedLib == null) { 9939 return false; 9940 } 9941 final int libIdx = versionedLib.indexOfKey(version); 9942 if (libIdx < 0) { 9943 return false; 9944 } 9945 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9946 versionedLib.remove(version); 9947 if (versionedLib.size() <= 0) { 9948 mSharedLibraries.remove(name); 9949 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9950 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9951 .getPackageName()); 9952 } 9953 } 9954 return true; 9955 } 9956 9957 /** 9958 * Adds a scanned package to the system. When this method is finished, the package will 9959 * be available for query, resolution, etc... 9960 */ 9961 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9962 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9963 final String pkgName = pkg.packageName; 9964 if (mCustomResolverComponentName != null && 9965 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9966 setUpCustomResolverActivity(pkg); 9967 } 9968 9969 if (pkg.packageName.equals("android")) { 9970 synchronized (mPackages) { 9971 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9972 // Set up information for our fall-back user intent resolution activity. 9973 mPlatformPackage = pkg; 9974 pkg.mVersionCode = mSdkVersion; 9975 mAndroidApplication = pkg.applicationInfo; 9976 if (!mResolverReplaced) { 9977 mResolveActivity.applicationInfo = mAndroidApplication; 9978 mResolveActivity.name = ResolverActivity.class.getName(); 9979 mResolveActivity.packageName = mAndroidApplication.packageName; 9980 mResolveActivity.processName = "system:ui"; 9981 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9982 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9983 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9984 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9985 mResolveActivity.exported = true; 9986 mResolveActivity.enabled = true; 9987 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9988 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9989 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9990 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9991 | ActivityInfo.CONFIG_ORIENTATION 9992 | ActivityInfo.CONFIG_KEYBOARD 9993 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9994 mResolveInfo.activityInfo = mResolveActivity; 9995 mResolveInfo.priority = 0; 9996 mResolveInfo.preferredOrder = 0; 9997 mResolveInfo.match = 0; 9998 mResolveComponentName = new ComponentName( 9999 mAndroidApplication.packageName, mResolveActivity.name); 10000 } 10001 } 10002 } 10003 } 10004 10005 ArrayList<PackageParser.Package> clientLibPkgs = null; 10006 // writer 10007 synchronized (mPackages) { 10008 boolean hasStaticSharedLibs = false; 10009 10010 // Any app can add new static shared libraries 10011 if (pkg.staticSharedLibName != null) { 10012 // Static shared libs don't allow renaming as they have synthetic package 10013 // names to allow install of multiple versions, so use name from manifest. 10014 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10015 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10016 pkg.manifestPackageName, pkg.mVersionCode)) { 10017 hasStaticSharedLibs = true; 10018 } else { 10019 Slog.w(TAG, "Package " + pkg.packageName + " library " 10020 + pkg.staticSharedLibName + " already exists; skipping"); 10021 } 10022 // Static shared libs cannot be updated once installed since they 10023 // use synthetic package name which includes the version code, so 10024 // not need to update other packages's shared lib dependencies. 10025 } 10026 10027 if (!hasStaticSharedLibs 10028 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10029 // Only system apps can add new dynamic shared libraries. 10030 if (pkg.libraryNames != null) { 10031 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10032 String name = pkg.libraryNames.get(i); 10033 boolean allowed = false; 10034 if (pkg.isUpdatedSystemApp()) { 10035 // New library entries can only be added through the 10036 // system image. This is important to get rid of a lot 10037 // of nasty edge cases: for example if we allowed a non- 10038 // system update of the app to add a library, then uninstalling 10039 // the update would make the library go away, and assumptions 10040 // we made such as through app install filtering would now 10041 // have allowed apps on the device which aren't compatible 10042 // with it. Better to just have the restriction here, be 10043 // conservative, and create many fewer cases that can negatively 10044 // impact the user experience. 10045 final PackageSetting sysPs = mSettings 10046 .getDisabledSystemPkgLPr(pkg.packageName); 10047 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10048 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10049 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10050 allowed = true; 10051 break; 10052 } 10053 } 10054 } 10055 } else { 10056 allowed = true; 10057 } 10058 if (allowed) { 10059 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10060 SharedLibraryInfo.VERSION_UNDEFINED, 10061 SharedLibraryInfo.TYPE_DYNAMIC, 10062 pkg.packageName, pkg.mVersionCode)) { 10063 Slog.w(TAG, "Package " + pkg.packageName + " library " 10064 + name + " already exists; skipping"); 10065 } 10066 } else { 10067 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10068 + name + " that is not declared on system image; skipping"); 10069 } 10070 } 10071 10072 if ((scanFlags & SCAN_BOOTING) == 0) { 10073 // If we are not booting, we need to update any applications 10074 // that are clients of our shared library. If we are booting, 10075 // this will all be done once the scan is complete. 10076 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10077 } 10078 } 10079 } 10080 } 10081 10082 if ((scanFlags & SCAN_BOOTING) != 0) { 10083 // No apps can run during boot scan, so they don't need to be frozen 10084 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10085 // Caller asked to not kill app, so it's probably not frozen 10086 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10087 // Caller asked us to ignore frozen check for some reason; they 10088 // probably didn't know the package name 10089 } else { 10090 // We're doing major surgery on this package, so it better be frozen 10091 // right now to keep it from launching 10092 checkPackageFrozen(pkgName); 10093 } 10094 10095 // Also need to kill any apps that are dependent on the library. 10096 if (clientLibPkgs != null) { 10097 for (int i=0; i<clientLibPkgs.size(); i++) { 10098 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10099 killApplication(clientPkg.applicationInfo.packageName, 10100 clientPkg.applicationInfo.uid, "update lib"); 10101 } 10102 } 10103 10104 // writer 10105 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10106 10107 synchronized (mPackages) { 10108 // We don't expect installation to fail beyond this point 10109 10110 // Add the new setting to mSettings 10111 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10112 // Add the new setting to mPackages 10113 mPackages.put(pkg.applicationInfo.packageName, pkg); 10114 // Make sure we don't accidentally delete its data. 10115 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10116 while (iter.hasNext()) { 10117 PackageCleanItem item = iter.next(); 10118 if (pkgName.equals(item.packageName)) { 10119 iter.remove(); 10120 } 10121 } 10122 10123 // Add the package's KeySets to the global KeySetManagerService 10124 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10125 ksms.addScannedPackageLPw(pkg); 10126 10127 int N = pkg.providers.size(); 10128 StringBuilder r = null; 10129 int i; 10130 for (i=0; i<N; i++) { 10131 PackageParser.Provider p = pkg.providers.get(i); 10132 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10133 p.info.processName); 10134 mProviders.addProvider(p); 10135 p.syncable = p.info.isSyncable; 10136 if (p.info.authority != null) { 10137 String names[] = p.info.authority.split(";"); 10138 p.info.authority = null; 10139 for (int j = 0; j < names.length; j++) { 10140 if (j == 1 && p.syncable) { 10141 // We only want the first authority for a provider to possibly be 10142 // syncable, so if we already added this provider using a different 10143 // authority clear the syncable flag. We copy the provider before 10144 // changing it because the mProviders object contains a reference 10145 // to a provider that we don't want to change. 10146 // Only do this for the second authority since the resulting provider 10147 // object can be the same for all future authorities for this provider. 10148 p = new PackageParser.Provider(p); 10149 p.syncable = false; 10150 } 10151 if (!mProvidersByAuthority.containsKey(names[j])) { 10152 mProvidersByAuthority.put(names[j], p); 10153 if (p.info.authority == null) { 10154 p.info.authority = names[j]; 10155 } else { 10156 p.info.authority = p.info.authority + ";" + names[j]; 10157 } 10158 if (DEBUG_PACKAGE_SCANNING) { 10159 if (chatty) 10160 Log.d(TAG, "Registered content provider: " + names[j] 10161 + ", className = " + p.info.name + ", isSyncable = " 10162 + p.info.isSyncable); 10163 } 10164 } else { 10165 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10166 Slog.w(TAG, "Skipping provider name " + names[j] + 10167 " (in package " + pkg.applicationInfo.packageName + 10168 "): name already used by " 10169 + ((other != null && other.getComponentName() != null) 10170 ? other.getComponentName().getPackageName() : "?")); 10171 } 10172 } 10173 } 10174 if (chatty) { 10175 if (r == null) { 10176 r = new StringBuilder(256); 10177 } else { 10178 r.append(' '); 10179 } 10180 r.append(p.info.name); 10181 } 10182 } 10183 if (r != null) { 10184 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10185 } 10186 10187 N = pkg.services.size(); 10188 r = null; 10189 for (i=0; i<N; i++) { 10190 PackageParser.Service s = pkg.services.get(i); 10191 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10192 s.info.processName); 10193 mServices.addService(s); 10194 if (chatty) { 10195 if (r == null) { 10196 r = new StringBuilder(256); 10197 } else { 10198 r.append(' '); 10199 } 10200 r.append(s.info.name); 10201 } 10202 } 10203 if (r != null) { 10204 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10205 } 10206 10207 N = pkg.receivers.size(); 10208 r = null; 10209 for (i=0; i<N; i++) { 10210 PackageParser.Activity a = pkg.receivers.get(i); 10211 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10212 a.info.processName); 10213 mReceivers.addActivity(a, "receiver"); 10214 if (chatty) { 10215 if (r == null) { 10216 r = new StringBuilder(256); 10217 } else { 10218 r.append(' '); 10219 } 10220 r.append(a.info.name); 10221 } 10222 } 10223 if (r != null) { 10224 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10225 } 10226 10227 N = pkg.activities.size(); 10228 r = null; 10229 for (i=0; i<N; i++) { 10230 PackageParser.Activity a = pkg.activities.get(i); 10231 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10232 a.info.processName); 10233 mActivities.addActivity(a, "activity"); 10234 if (chatty) { 10235 if (r == null) { 10236 r = new StringBuilder(256); 10237 } else { 10238 r.append(' '); 10239 } 10240 r.append(a.info.name); 10241 } 10242 } 10243 if (r != null) { 10244 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10245 } 10246 10247 N = pkg.permissionGroups.size(); 10248 r = null; 10249 for (i=0; i<N; i++) { 10250 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10251 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10252 final String curPackageName = cur == null ? null : cur.info.packageName; 10253 // Dont allow ephemeral apps to define new permission groups. 10254 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10255 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10256 + pg.info.packageName 10257 + " ignored: instant apps cannot define new permission groups."); 10258 continue; 10259 } 10260 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10261 if (cur == null || isPackageUpdate) { 10262 mPermissionGroups.put(pg.info.name, pg); 10263 if (chatty) { 10264 if (r == null) { 10265 r = new StringBuilder(256); 10266 } else { 10267 r.append(' '); 10268 } 10269 if (isPackageUpdate) { 10270 r.append("UPD:"); 10271 } 10272 r.append(pg.info.name); 10273 } 10274 } else { 10275 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10276 + pg.info.packageName + " ignored: original from " 10277 + cur.info.packageName); 10278 if (chatty) { 10279 if (r == null) { 10280 r = new StringBuilder(256); 10281 } else { 10282 r.append(' '); 10283 } 10284 r.append("DUP:"); 10285 r.append(pg.info.name); 10286 } 10287 } 10288 } 10289 if (r != null) { 10290 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10291 } 10292 10293 N = pkg.permissions.size(); 10294 r = null; 10295 for (i=0; i<N; i++) { 10296 PackageParser.Permission p = pkg.permissions.get(i); 10297 10298 // Dont allow ephemeral apps to define new permissions. 10299 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10300 Slog.w(TAG, "Permission " + p.info.name + " from package " 10301 + p.info.packageName 10302 + " ignored: instant apps cannot define new permissions."); 10303 continue; 10304 } 10305 10306 // Assume by default that we did not install this permission into the system. 10307 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10308 10309 // Now that permission groups have a special meaning, we ignore permission 10310 // groups for legacy apps to prevent unexpected behavior. In particular, 10311 // permissions for one app being granted to someone just becase they happen 10312 // to be in a group defined by another app (before this had no implications). 10313 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10314 p.group = mPermissionGroups.get(p.info.group); 10315 // Warn for a permission in an unknown group. 10316 if (p.info.group != null && p.group == null) { 10317 Slog.w(TAG, "Permission " + p.info.name + " from package " 10318 + p.info.packageName + " in an unknown group " + p.info.group); 10319 } 10320 } 10321 10322 ArrayMap<String, BasePermission> permissionMap = 10323 p.tree ? mSettings.mPermissionTrees 10324 : mSettings.mPermissions; 10325 BasePermission bp = permissionMap.get(p.info.name); 10326 10327 // Allow system apps to redefine non-system permissions 10328 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10329 final boolean currentOwnerIsSystem = (bp.perm != null 10330 && isSystemApp(bp.perm.owner)); 10331 if (isSystemApp(p.owner)) { 10332 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10333 // It's a built-in permission and no owner, take ownership now 10334 bp.packageSetting = pkgSetting; 10335 bp.perm = p; 10336 bp.uid = pkg.applicationInfo.uid; 10337 bp.sourcePackage = p.info.packageName; 10338 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10339 } else if (!currentOwnerIsSystem) { 10340 String msg = "New decl " + p.owner + " of permission " 10341 + p.info.name + " is system; overriding " + bp.sourcePackage; 10342 reportSettingsProblem(Log.WARN, msg); 10343 bp = null; 10344 } 10345 } 10346 } 10347 10348 if (bp == null) { 10349 bp = new BasePermission(p.info.name, p.info.packageName, 10350 BasePermission.TYPE_NORMAL); 10351 permissionMap.put(p.info.name, bp); 10352 } 10353 10354 if (bp.perm == null) { 10355 if (bp.sourcePackage == null 10356 || bp.sourcePackage.equals(p.info.packageName)) { 10357 BasePermission tree = findPermissionTreeLP(p.info.name); 10358 if (tree == null 10359 || tree.sourcePackage.equals(p.info.packageName)) { 10360 bp.packageSetting = pkgSetting; 10361 bp.perm = p; 10362 bp.uid = pkg.applicationInfo.uid; 10363 bp.sourcePackage = p.info.packageName; 10364 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10365 if (chatty) { 10366 if (r == null) { 10367 r = new StringBuilder(256); 10368 } else { 10369 r.append(' '); 10370 } 10371 r.append(p.info.name); 10372 } 10373 } else { 10374 Slog.w(TAG, "Permission " + p.info.name + " from package " 10375 + p.info.packageName + " ignored: base tree " 10376 + tree.name + " is from package " 10377 + tree.sourcePackage); 10378 } 10379 } else { 10380 Slog.w(TAG, "Permission " + p.info.name + " from package " 10381 + p.info.packageName + " ignored: original from " 10382 + bp.sourcePackage); 10383 } 10384 } else if (chatty) { 10385 if (r == null) { 10386 r = new StringBuilder(256); 10387 } else { 10388 r.append(' '); 10389 } 10390 r.append("DUP:"); 10391 r.append(p.info.name); 10392 } 10393 if (bp.perm == p) { 10394 bp.protectionLevel = p.info.protectionLevel; 10395 } 10396 } 10397 10398 if (r != null) { 10399 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10400 } 10401 10402 N = pkg.instrumentation.size(); 10403 r = null; 10404 for (i=0; i<N; i++) { 10405 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10406 a.info.packageName = pkg.applicationInfo.packageName; 10407 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10408 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10409 a.info.splitNames = pkg.splitNames; 10410 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10411 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10412 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10413 a.info.dataDir = pkg.applicationInfo.dataDir; 10414 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10415 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10416 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10417 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10418 mInstrumentation.put(a.getComponentName(), a); 10419 if (chatty) { 10420 if (r == null) { 10421 r = new StringBuilder(256); 10422 } else { 10423 r.append(' '); 10424 } 10425 r.append(a.info.name); 10426 } 10427 } 10428 if (r != null) { 10429 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10430 } 10431 10432 if (pkg.protectedBroadcasts != null) { 10433 N = pkg.protectedBroadcasts.size(); 10434 for (i=0; i<N; i++) { 10435 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10436 } 10437 } 10438 } 10439 10440 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10441 } 10442 10443 /** 10444 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10445 * is derived purely on the basis of the contents of {@code scanFile} and 10446 * {@code cpuAbiOverride}. 10447 * 10448 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10449 */ 10450 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10451 String cpuAbiOverride, boolean extractLibs, 10452 File appLib32InstallDir) 10453 throws PackageManagerException { 10454 // Give ourselves some initial paths; we'll come back for another 10455 // pass once we've determined ABI below. 10456 setNativeLibraryPaths(pkg, appLib32InstallDir); 10457 10458 // We would never need to extract libs for forward-locked and external packages, 10459 // since the container service will do it for us. We shouldn't attempt to 10460 // extract libs from system app when it was not updated. 10461 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10462 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10463 extractLibs = false; 10464 } 10465 10466 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10467 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10468 10469 NativeLibraryHelper.Handle handle = null; 10470 try { 10471 handle = NativeLibraryHelper.Handle.create(pkg); 10472 // TODO(multiArch): This can be null for apps that didn't go through the 10473 // usual installation process. We can calculate it again, like we 10474 // do during install time. 10475 // 10476 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10477 // unnecessary. 10478 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10479 10480 // Null out the abis so that they can be recalculated. 10481 pkg.applicationInfo.primaryCpuAbi = null; 10482 pkg.applicationInfo.secondaryCpuAbi = null; 10483 if (isMultiArch(pkg.applicationInfo)) { 10484 // Warn if we've set an abiOverride for multi-lib packages.. 10485 // By definition, we need to copy both 32 and 64 bit libraries for 10486 // such packages. 10487 if (pkg.cpuAbiOverride != null 10488 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10489 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10490 } 10491 10492 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10493 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10494 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10495 if (extractLibs) { 10496 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10497 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10498 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10499 useIsaSpecificSubdirs); 10500 } else { 10501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10502 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10503 } 10504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10505 } 10506 10507 maybeThrowExceptionForMultiArchCopy( 10508 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10509 10510 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10511 if (extractLibs) { 10512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10513 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10514 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10515 useIsaSpecificSubdirs); 10516 } else { 10517 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10518 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10519 } 10520 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10521 } 10522 10523 maybeThrowExceptionForMultiArchCopy( 10524 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10525 10526 if (abi64 >= 0) { 10527 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10528 } 10529 10530 if (abi32 >= 0) { 10531 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10532 if (abi64 >= 0) { 10533 if (pkg.use32bitAbi) { 10534 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10535 pkg.applicationInfo.primaryCpuAbi = abi; 10536 } else { 10537 pkg.applicationInfo.secondaryCpuAbi = abi; 10538 } 10539 } else { 10540 pkg.applicationInfo.primaryCpuAbi = abi; 10541 } 10542 } 10543 10544 } else { 10545 String[] abiList = (cpuAbiOverride != null) ? 10546 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10547 10548 // Enable gross and lame hacks for apps that are built with old 10549 // SDK tools. We must scan their APKs for renderscript bitcode and 10550 // not launch them if it's present. Don't bother checking on devices 10551 // that don't have 64 bit support. 10552 boolean needsRenderScriptOverride = false; 10553 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10554 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10555 abiList = Build.SUPPORTED_32_BIT_ABIS; 10556 needsRenderScriptOverride = true; 10557 } 10558 10559 final int copyRet; 10560 if (extractLibs) { 10561 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10562 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10563 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10564 } else { 10565 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10566 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10567 } 10568 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10569 10570 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10571 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10572 "Error unpackaging native libs for app, errorCode=" + copyRet); 10573 } 10574 10575 if (copyRet >= 0) { 10576 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10577 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10578 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10579 } else if (needsRenderScriptOverride) { 10580 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10581 } 10582 } 10583 } catch (IOException ioe) { 10584 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10585 } finally { 10586 IoUtils.closeQuietly(handle); 10587 } 10588 10589 // Now that we've calculated the ABIs and determined if it's an internal app, 10590 // we will go ahead and populate the nativeLibraryPath. 10591 setNativeLibraryPaths(pkg, appLib32InstallDir); 10592 } 10593 10594 /** 10595 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10596 * i.e, so that all packages can be run inside a single process if required. 10597 * 10598 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10599 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10600 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10601 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10602 * updating a package that belongs to a shared user. 10603 * 10604 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10605 * adds unnecessary complexity. 10606 */ 10607 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10608 PackageParser.Package scannedPackage) { 10609 String requiredInstructionSet = null; 10610 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10611 requiredInstructionSet = VMRuntime.getInstructionSet( 10612 scannedPackage.applicationInfo.primaryCpuAbi); 10613 } 10614 10615 PackageSetting requirer = null; 10616 for (PackageSetting ps : packagesForUser) { 10617 // If packagesForUser contains scannedPackage, we skip it. This will happen 10618 // when scannedPackage is an update of an existing package. Without this check, 10619 // we will never be able to change the ABI of any package belonging to a shared 10620 // user, even if it's compatible with other packages. 10621 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10622 if (ps.primaryCpuAbiString == null) { 10623 continue; 10624 } 10625 10626 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10627 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10628 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10629 // this but there's not much we can do. 10630 String errorMessage = "Instruction set mismatch, " 10631 + ((requirer == null) ? "[caller]" : requirer) 10632 + " requires " + requiredInstructionSet + " whereas " + ps 10633 + " requires " + instructionSet; 10634 Slog.w(TAG, errorMessage); 10635 } 10636 10637 if (requiredInstructionSet == null) { 10638 requiredInstructionSet = instructionSet; 10639 requirer = ps; 10640 } 10641 } 10642 } 10643 10644 if (requiredInstructionSet != null) { 10645 String adjustedAbi; 10646 if (requirer != null) { 10647 // requirer != null implies that either scannedPackage was null or that scannedPackage 10648 // did not require an ABI, in which case we have to adjust scannedPackage to match 10649 // the ABI of the set (which is the same as requirer's ABI) 10650 adjustedAbi = requirer.primaryCpuAbiString; 10651 if (scannedPackage != null) { 10652 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10653 } 10654 } else { 10655 // requirer == null implies that we're updating all ABIs in the set to 10656 // match scannedPackage. 10657 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10658 } 10659 10660 for (PackageSetting ps : packagesForUser) { 10661 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10662 if (ps.primaryCpuAbiString != null) { 10663 continue; 10664 } 10665 10666 ps.primaryCpuAbiString = adjustedAbi; 10667 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10668 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10669 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10670 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10671 + " (requirer=" 10672 + (requirer != null ? requirer.pkg : "null") 10673 + ", scannedPackage=" 10674 + (scannedPackage != null ? scannedPackage : "null") 10675 + ")"); 10676 try { 10677 mInstaller.rmdex(ps.codePathString, 10678 getDexCodeInstructionSet(getPreferredInstructionSet())); 10679 } catch (InstallerException ignored) { 10680 } 10681 } 10682 } 10683 } 10684 } 10685 } 10686 10687 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10688 synchronized (mPackages) { 10689 mResolverReplaced = true; 10690 // Set up information for custom user intent resolution activity. 10691 mResolveActivity.applicationInfo = pkg.applicationInfo; 10692 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10693 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10694 mResolveActivity.processName = pkg.applicationInfo.packageName; 10695 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10696 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10697 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10698 mResolveActivity.theme = 0; 10699 mResolveActivity.exported = true; 10700 mResolveActivity.enabled = true; 10701 mResolveInfo.activityInfo = mResolveActivity; 10702 mResolveInfo.priority = 0; 10703 mResolveInfo.preferredOrder = 0; 10704 mResolveInfo.match = 0; 10705 mResolveComponentName = mCustomResolverComponentName; 10706 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10707 mResolveComponentName); 10708 } 10709 } 10710 10711 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10712 if (installerActivity == null) { 10713 if (DEBUG_EPHEMERAL) { 10714 Slog.d(TAG, "Clear ephemeral installer activity"); 10715 } 10716 mInstantAppInstallerActivity = null; 10717 return; 10718 } 10719 10720 if (DEBUG_EPHEMERAL) { 10721 Slog.d(TAG, "Set ephemeral installer activity: " 10722 + installerActivity.getComponentName()); 10723 } 10724 // Set up information for ephemeral installer activity 10725 mInstantAppInstallerActivity = installerActivity; 10726 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10727 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10728 mInstantAppInstallerActivity.exported = true; 10729 mInstantAppInstallerActivity.enabled = true; 10730 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10731 mInstantAppInstallerInfo.priority = 0; 10732 mInstantAppInstallerInfo.preferredOrder = 1; 10733 mInstantAppInstallerInfo.isDefault = true; 10734 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10735 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10736 } 10737 10738 private static String calculateBundledApkRoot(final String codePathString) { 10739 final File codePath = new File(codePathString); 10740 final File codeRoot; 10741 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10742 codeRoot = Environment.getRootDirectory(); 10743 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10744 codeRoot = Environment.getOemDirectory(); 10745 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10746 codeRoot = Environment.getVendorDirectory(); 10747 } else { 10748 // Unrecognized code path; take its top real segment as the apk root: 10749 // e.g. /something/app/blah.apk => /something 10750 try { 10751 File f = codePath.getCanonicalFile(); 10752 File parent = f.getParentFile(); // non-null because codePath is a file 10753 File tmp; 10754 while ((tmp = parent.getParentFile()) != null) { 10755 f = parent; 10756 parent = tmp; 10757 } 10758 codeRoot = f; 10759 Slog.w(TAG, "Unrecognized code path " 10760 + codePath + " - using " + codeRoot); 10761 } catch (IOException e) { 10762 // Can't canonicalize the code path -- shenanigans? 10763 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10764 return Environment.getRootDirectory().getPath(); 10765 } 10766 } 10767 return codeRoot.getPath(); 10768 } 10769 10770 /** 10771 * Derive and set the location of native libraries for the given package, 10772 * which varies depending on where and how the package was installed. 10773 */ 10774 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10775 final ApplicationInfo info = pkg.applicationInfo; 10776 final String codePath = pkg.codePath; 10777 final File codeFile = new File(codePath); 10778 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10779 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10780 10781 info.nativeLibraryRootDir = null; 10782 info.nativeLibraryRootRequiresIsa = false; 10783 info.nativeLibraryDir = null; 10784 info.secondaryNativeLibraryDir = null; 10785 10786 if (isApkFile(codeFile)) { 10787 // Monolithic install 10788 if (bundledApp) { 10789 // If "/system/lib64/apkname" exists, assume that is the per-package 10790 // native library directory to use; otherwise use "/system/lib/apkname". 10791 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10792 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10793 getPrimaryInstructionSet(info)); 10794 10795 // This is a bundled system app so choose the path based on the ABI. 10796 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10797 // is just the default path. 10798 final String apkName = deriveCodePathName(codePath); 10799 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10800 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10801 apkName).getAbsolutePath(); 10802 10803 if (info.secondaryCpuAbi != null) { 10804 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10805 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10806 secondaryLibDir, apkName).getAbsolutePath(); 10807 } 10808 } else if (asecApp) { 10809 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10810 .getAbsolutePath(); 10811 } else { 10812 final String apkName = deriveCodePathName(codePath); 10813 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10814 .getAbsolutePath(); 10815 } 10816 10817 info.nativeLibraryRootRequiresIsa = false; 10818 info.nativeLibraryDir = info.nativeLibraryRootDir; 10819 } else { 10820 // Cluster install 10821 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10822 info.nativeLibraryRootRequiresIsa = true; 10823 10824 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10825 getPrimaryInstructionSet(info)).getAbsolutePath(); 10826 10827 if (info.secondaryCpuAbi != null) { 10828 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10829 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10830 } 10831 } 10832 } 10833 10834 /** 10835 * Calculate the abis and roots for a bundled app. These can uniquely 10836 * be determined from the contents of the system partition, i.e whether 10837 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10838 * of this information, and instead assume that the system was built 10839 * sensibly. 10840 */ 10841 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10842 PackageSetting pkgSetting) { 10843 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10844 10845 // If "/system/lib64/apkname" exists, assume that is the per-package 10846 // native library directory to use; otherwise use "/system/lib/apkname". 10847 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10848 setBundledAppAbi(pkg, apkRoot, apkName); 10849 // pkgSetting might be null during rescan following uninstall of updates 10850 // to a bundled app, so accommodate that possibility. The settings in 10851 // that case will be established later from the parsed package. 10852 // 10853 // If the settings aren't null, sync them up with what we've just derived. 10854 // note that apkRoot isn't stored in the package settings. 10855 if (pkgSetting != null) { 10856 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10857 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10858 } 10859 } 10860 10861 /** 10862 * Deduces the ABI of a bundled app and sets the relevant fields on the 10863 * parsed pkg object. 10864 * 10865 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10866 * under which system libraries are installed. 10867 * @param apkName the name of the installed package. 10868 */ 10869 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10870 final File codeFile = new File(pkg.codePath); 10871 10872 final boolean has64BitLibs; 10873 final boolean has32BitLibs; 10874 if (isApkFile(codeFile)) { 10875 // Monolithic install 10876 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10877 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10878 } else { 10879 // Cluster install 10880 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10881 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10882 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10883 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10884 has64BitLibs = (new File(rootDir, isa)).exists(); 10885 } else { 10886 has64BitLibs = false; 10887 } 10888 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10889 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10890 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10891 has32BitLibs = (new File(rootDir, isa)).exists(); 10892 } else { 10893 has32BitLibs = false; 10894 } 10895 } 10896 10897 if (has64BitLibs && !has32BitLibs) { 10898 // The package has 64 bit libs, but not 32 bit libs. Its primary 10899 // ABI should be 64 bit. We can safely assume here that the bundled 10900 // native libraries correspond to the most preferred ABI in the list. 10901 10902 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10903 pkg.applicationInfo.secondaryCpuAbi = null; 10904 } else if (has32BitLibs && !has64BitLibs) { 10905 // The package has 32 bit libs but not 64 bit libs. Its primary 10906 // ABI should be 32 bit. 10907 10908 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10909 pkg.applicationInfo.secondaryCpuAbi = null; 10910 } else if (has32BitLibs && has64BitLibs) { 10911 // The application has both 64 and 32 bit bundled libraries. We check 10912 // here that the app declares multiArch support, and warn if it doesn't. 10913 // 10914 // We will be lenient here and record both ABIs. The primary will be the 10915 // ABI that's higher on the list, i.e, a device that's configured to prefer 10916 // 64 bit apps will see a 64 bit primary ABI, 10917 10918 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10919 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10920 } 10921 10922 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10923 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10924 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10925 } else { 10926 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10927 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10928 } 10929 } else { 10930 pkg.applicationInfo.primaryCpuAbi = null; 10931 pkg.applicationInfo.secondaryCpuAbi = null; 10932 } 10933 } 10934 10935 private void killApplication(String pkgName, int appId, String reason) { 10936 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10937 } 10938 10939 private void killApplication(String pkgName, int appId, int userId, String reason) { 10940 // Request the ActivityManager to kill the process(only for existing packages) 10941 // so that we do not end up in a confused state while the user is still using the older 10942 // version of the application while the new one gets installed. 10943 final long token = Binder.clearCallingIdentity(); 10944 try { 10945 IActivityManager am = ActivityManager.getService(); 10946 if (am != null) { 10947 try { 10948 am.killApplication(pkgName, appId, userId, reason); 10949 } catch (RemoteException e) { 10950 } 10951 } 10952 } finally { 10953 Binder.restoreCallingIdentity(token); 10954 } 10955 } 10956 10957 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10958 // Remove the parent package setting 10959 PackageSetting ps = (PackageSetting) pkg.mExtras; 10960 if (ps != null) { 10961 removePackageLI(ps, chatty); 10962 } 10963 // Remove the child package setting 10964 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10965 for (int i = 0; i < childCount; i++) { 10966 PackageParser.Package childPkg = pkg.childPackages.get(i); 10967 ps = (PackageSetting) childPkg.mExtras; 10968 if (ps != null) { 10969 removePackageLI(ps, chatty); 10970 } 10971 } 10972 } 10973 10974 void removePackageLI(PackageSetting ps, boolean chatty) { 10975 if (DEBUG_INSTALL) { 10976 if (chatty) 10977 Log.d(TAG, "Removing package " + ps.name); 10978 } 10979 10980 // writer 10981 synchronized (mPackages) { 10982 mPackages.remove(ps.name); 10983 final PackageParser.Package pkg = ps.pkg; 10984 if (pkg != null) { 10985 cleanPackageDataStructuresLILPw(pkg, chatty); 10986 } 10987 } 10988 } 10989 10990 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10991 if (DEBUG_INSTALL) { 10992 if (chatty) 10993 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10994 } 10995 10996 // writer 10997 synchronized (mPackages) { 10998 // Remove the parent package 10999 mPackages.remove(pkg.applicationInfo.packageName); 11000 cleanPackageDataStructuresLILPw(pkg, chatty); 11001 11002 // Remove the child packages 11003 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11004 for (int i = 0; i < childCount; i++) { 11005 PackageParser.Package childPkg = pkg.childPackages.get(i); 11006 mPackages.remove(childPkg.applicationInfo.packageName); 11007 cleanPackageDataStructuresLILPw(childPkg, chatty); 11008 } 11009 } 11010 } 11011 11012 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11013 int N = pkg.providers.size(); 11014 StringBuilder r = null; 11015 int i; 11016 for (i=0; i<N; i++) { 11017 PackageParser.Provider p = pkg.providers.get(i); 11018 mProviders.removeProvider(p); 11019 if (p.info.authority == null) { 11020 11021 /* There was another ContentProvider with this authority when 11022 * this app was installed so this authority is null, 11023 * Ignore it as we don't have to unregister the provider. 11024 */ 11025 continue; 11026 } 11027 String names[] = p.info.authority.split(";"); 11028 for (int j = 0; j < names.length; j++) { 11029 if (mProvidersByAuthority.get(names[j]) == p) { 11030 mProvidersByAuthority.remove(names[j]); 11031 if (DEBUG_REMOVE) { 11032 if (chatty) 11033 Log.d(TAG, "Unregistered content provider: " + names[j] 11034 + ", className = " + p.info.name + ", isSyncable = " 11035 + p.info.isSyncable); 11036 } 11037 } 11038 } 11039 if (DEBUG_REMOVE && chatty) { 11040 if (r == null) { 11041 r = new StringBuilder(256); 11042 } else { 11043 r.append(' '); 11044 } 11045 r.append(p.info.name); 11046 } 11047 } 11048 if (r != null) { 11049 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11050 } 11051 11052 N = pkg.services.size(); 11053 r = null; 11054 for (i=0; i<N; i++) { 11055 PackageParser.Service s = pkg.services.get(i); 11056 mServices.removeService(s); 11057 if (chatty) { 11058 if (r == null) { 11059 r = new StringBuilder(256); 11060 } else { 11061 r.append(' '); 11062 } 11063 r.append(s.info.name); 11064 } 11065 } 11066 if (r != null) { 11067 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11068 } 11069 11070 N = pkg.receivers.size(); 11071 r = null; 11072 for (i=0; i<N; i++) { 11073 PackageParser.Activity a = pkg.receivers.get(i); 11074 mReceivers.removeActivity(a, "receiver"); 11075 if (DEBUG_REMOVE && chatty) { 11076 if (r == null) { 11077 r = new StringBuilder(256); 11078 } else { 11079 r.append(' '); 11080 } 11081 r.append(a.info.name); 11082 } 11083 } 11084 if (r != null) { 11085 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11086 } 11087 11088 N = pkg.activities.size(); 11089 r = null; 11090 for (i=0; i<N; i++) { 11091 PackageParser.Activity a = pkg.activities.get(i); 11092 mActivities.removeActivity(a, "activity"); 11093 if (DEBUG_REMOVE && chatty) { 11094 if (r == null) { 11095 r = new StringBuilder(256); 11096 } else { 11097 r.append(' '); 11098 } 11099 r.append(a.info.name); 11100 } 11101 } 11102 if (r != null) { 11103 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11104 } 11105 11106 N = pkg.permissions.size(); 11107 r = null; 11108 for (i=0; i<N; i++) { 11109 PackageParser.Permission p = pkg.permissions.get(i); 11110 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11111 if (bp == null) { 11112 bp = mSettings.mPermissionTrees.get(p.info.name); 11113 } 11114 if (bp != null && bp.perm == p) { 11115 bp.perm = null; 11116 if (DEBUG_REMOVE && chatty) { 11117 if (r == null) { 11118 r = new StringBuilder(256); 11119 } else { 11120 r.append(' '); 11121 } 11122 r.append(p.info.name); 11123 } 11124 } 11125 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11126 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11127 if (appOpPkgs != null) { 11128 appOpPkgs.remove(pkg.packageName); 11129 } 11130 } 11131 } 11132 if (r != null) { 11133 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11134 } 11135 11136 N = pkg.requestedPermissions.size(); 11137 r = null; 11138 for (i=0; i<N; i++) { 11139 String perm = pkg.requestedPermissions.get(i); 11140 BasePermission bp = mSettings.mPermissions.get(perm); 11141 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11142 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11143 if (appOpPkgs != null) { 11144 appOpPkgs.remove(pkg.packageName); 11145 if (appOpPkgs.isEmpty()) { 11146 mAppOpPermissionPackages.remove(perm); 11147 } 11148 } 11149 } 11150 } 11151 if (r != null) { 11152 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11153 } 11154 11155 N = pkg.instrumentation.size(); 11156 r = null; 11157 for (i=0; i<N; i++) { 11158 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11159 mInstrumentation.remove(a.getComponentName()); 11160 if (DEBUG_REMOVE && chatty) { 11161 if (r == null) { 11162 r = new StringBuilder(256); 11163 } else { 11164 r.append(' '); 11165 } 11166 r.append(a.info.name); 11167 } 11168 } 11169 if (r != null) { 11170 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11171 } 11172 11173 r = null; 11174 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11175 // Only system apps can hold shared libraries. 11176 if (pkg.libraryNames != null) { 11177 for (i = 0; i < pkg.libraryNames.size(); i++) { 11178 String name = pkg.libraryNames.get(i); 11179 if (removeSharedLibraryLPw(name, 0)) { 11180 if (DEBUG_REMOVE && chatty) { 11181 if (r == null) { 11182 r = new StringBuilder(256); 11183 } else { 11184 r.append(' '); 11185 } 11186 r.append(name); 11187 } 11188 } 11189 } 11190 } 11191 } 11192 11193 r = null; 11194 11195 // Any package can hold static shared libraries. 11196 if (pkg.staticSharedLibName != null) { 11197 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11198 if (DEBUG_REMOVE && chatty) { 11199 if (r == null) { 11200 r = new StringBuilder(256); 11201 } else { 11202 r.append(' '); 11203 } 11204 r.append(pkg.staticSharedLibName); 11205 } 11206 } 11207 } 11208 11209 if (r != null) { 11210 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11211 } 11212 } 11213 11214 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11215 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11216 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11217 return true; 11218 } 11219 } 11220 return false; 11221 } 11222 11223 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11224 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11225 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11226 11227 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11228 // Update the parent permissions 11229 updatePermissionsLPw(pkg.packageName, pkg, flags); 11230 // Update the child permissions 11231 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11232 for (int i = 0; i < childCount; i++) { 11233 PackageParser.Package childPkg = pkg.childPackages.get(i); 11234 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11235 } 11236 } 11237 11238 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11239 int flags) { 11240 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11241 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11242 } 11243 11244 private void updatePermissionsLPw(String changingPkg, 11245 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11246 // Make sure there are no dangling permission trees. 11247 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11248 while (it.hasNext()) { 11249 final BasePermission bp = it.next(); 11250 if (bp.packageSetting == null) { 11251 // We may not yet have parsed the package, so just see if 11252 // we still know about its settings. 11253 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11254 } 11255 if (bp.packageSetting == null) { 11256 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11257 + " from package " + bp.sourcePackage); 11258 it.remove(); 11259 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11260 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11261 Slog.i(TAG, "Removing old permission tree: " + bp.name 11262 + " from package " + bp.sourcePackage); 11263 flags |= UPDATE_PERMISSIONS_ALL; 11264 it.remove(); 11265 } 11266 } 11267 } 11268 11269 // Make sure all dynamic permissions have been assigned to a package, 11270 // and make sure there are no dangling permissions. 11271 it = mSettings.mPermissions.values().iterator(); 11272 while (it.hasNext()) { 11273 final BasePermission bp = it.next(); 11274 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11275 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11276 + bp.name + " pkg=" + bp.sourcePackage 11277 + " info=" + bp.pendingInfo); 11278 if (bp.packageSetting == null && bp.pendingInfo != null) { 11279 final BasePermission tree = findPermissionTreeLP(bp.name); 11280 if (tree != null && tree.perm != null) { 11281 bp.packageSetting = tree.packageSetting; 11282 bp.perm = new PackageParser.Permission(tree.perm.owner, 11283 new PermissionInfo(bp.pendingInfo)); 11284 bp.perm.info.packageName = tree.perm.info.packageName; 11285 bp.perm.info.name = bp.name; 11286 bp.uid = tree.uid; 11287 } 11288 } 11289 } 11290 if (bp.packageSetting == null) { 11291 // We may not yet have parsed the package, so just see if 11292 // we still know about its settings. 11293 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11294 } 11295 if (bp.packageSetting == null) { 11296 Slog.w(TAG, "Removing dangling permission: " + bp.name 11297 + " from package " + bp.sourcePackage); 11298 it.remove(); 11299 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11300 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11301 Slog.i(TAG, "Removing old permission: " + bp.name 11302 + " from package " + bp.sourcePackage); 11303 flags |= UPDATE_PERMISSIONS_ALL; 11304 it.remove(); 11305 } 11306 } 11307 } 11308 11309 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11310 // Now update the permissions for all packages, in particular 11311 // replace the granted permissions of the system packages. 11312 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11313 for (PackageParser.Package pkg : mPackages.values()) { 11314 if (pkg != pkgInfo) { 11315 // Only replace for packages on requested volume 11316 final String volumeUuid = getVolumeUuidForPackage(pkg); 11317 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11318 && Objects.equals(replaceVolumeUuid, volumeUuid); 11319 grantPermissionsLPw(pkg, replace, changingPkg); 11320 } 11321 } 11322 } 11323 11324 if (pkgInfo != null) { 11325 // Only replace for packages on requested volume 11326 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11327 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11328 && Objects.equals(replaceVolumeUuid, volumeUuid); 11329 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11330 } 11331 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11332 } 11333 11334 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11335 String packageOfInterest) { 11336 // IMPORTANT: There are two types of permissions: install and runtime. 11337 // Install time permissions are granted when the app is installed to 11338 // all device users and users added in the future. Runtime permissions 11339 // are granted at runtime explicitly to specific users. Normal and signature 11340 // protected permissions are install time permissions. Dangerous permissions 11341 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11342 // otherwise they are runtime permissions. This function does not manage 11343 // runtime permissions except for the case an app targeting Lollipop MR1 11344 // being upgraded to target a newer SDK, in which case dangerous permissions 11345 // are transformed from install time to runtime ones. 11346 11347 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11348 if (ps == null) { 11349 return; 11350 } 11351 11352 PermissionsState permissionsState = ps.getPermissionsState(); 11353 PermissionsState origPermissions = permissionsState; 11354 11355 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11356 11357 boolean runtimePermissionsRevoked = false; 11358 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11359 11360 boolean changedInstallPermission = false; 11361 11362 if (replace) { 11363 ps.installPermissionsFixed = false; 11364 if (!ps.isSharedUser()) { 11365 origPermissions = new PermissionsState(permissionsState); 11366 permissionsState.reset(); 11367 } else { 11368 // We need to know only about runtime permission changes since the 11369 // calling code always writes the install permissions state but 11370 // the runtime ones are written only if changed. The only cases of 11371 // changed runtime permissions here are promotion of an install to 11372 // runtime and revocation of a runtime from a shared user. 11373 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11374 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11375 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11376 runtimePermissionsRevoked = true; 11377 } 11378 } 11379 } 11380 11381 permissionsState.setGlobalGids(mGlobalGids); 11382 11383 final int N = pkg.requestedPermissions.size(); 11384 for (int i=0; i<N; i++) { 11385 final String name = pkg.requestedPermissions.get(i); 11386 final BasePermission bp = mSettings.mPermissions.get(name); 11387 11388 if (DEBUG_INSTALL) { 11389 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11390 } 11391 11392 if (bp == null || bp.packageSetting == null) { 11393 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11394 Slog.w(TAG, "Unknown permission " + name 11395 + " in package " + pkg.packageName); 11396 } 11397 continue; 11398 } 11399 11400 11401 // Limit ephemeral apps to ephemeral allowed permissions. 11402 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11403 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11404 + pkg.packageName); 11405 continue; 11406 } 11407 11408 final String perm = bp.name; 11409 boolean allowedSig = false; 11410 int grant = GRANT_DENIED; 11411 11412 // Keep track of app op permissions. 11413 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11414 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11415 if (pkgs == null) { 11416 pkgs = new ArraySet<>(); 11417 mAppOpPermissionPackages.put(bp.name, pkgs); 11418 } 11419 pkgs.add(pkg.packageName); 11420 } 11421 11422 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11423 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11424 >= Build.VERSION_CODES.M; 11425 switch (level) { 11426 case PermissionInfo.PROTECTION_NORMAL: { 11427 // For all apps normal permissions are install time ones. 11428 grant = GRANT_INSTALL; 11429 } break; 11430 11431 case PermissionInfo.PROTECTION_DANGEROUS: { 11432 // If a permission review is required for legacy apps we represent 11433 // their permissions as always granted runtime ones since we need 11434 // to keep the review required permission flag per user while an 11435 // install permission's state is shared across all users. 11436 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11437 // For legacy apps dangerous permissions are install time ones. 11438 grant = GRANT_INSTALL; 11439 } else if (origPermissions.hasInstallPermission(bp.name)) { 11440 // For legacy apps that became modern, install becomes runtime. 11441 grant = GRANT_UPGRADE; 11442 } else if (mPromoteSystemApps 11443 && isSystemApp(ps) 11444 && mExistingSystemPackages.contains(ps.name)) { 11445 // For legacy system apps, install becomes runtime. 11446 // We cannot check hasInstallPermission() for system apps since those 11447 // permissions were granted implicitly and not persisted pre-M. 11448 grant = GRANT_UPGRADE; 11449 } else { 11450 // For modern apps keep runtime permissions unchanged. 11451 grant = GRANT_RUNTIME; 11452 } 11453 } break; 11454 11455 case PermissionInfo.PROTECTION_SIGNATURE: { 11456 // For all apps signature permissions are install time ones. 11457 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11458 if (allowedSig) { 11459 grant = GRANT_INSTALL; 11460 } 11461 } break; 11462 } 11463 11464 if (DEBUG_INSTALL) { 11465 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11466 } 11467 11468 if (grant != GRANT_DENIED) { 11469 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11470 // If this is an existing, non-system package, then 11471 // we can't add any new permissions to it. 11472 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11473 // Except... if this is a permission that was added 11474 // to the platform (note: need to only do this when 11475 // updating the platform). 11476 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11477 grant = GRANT_DENIED; 11478 } 11479 } 11480 } 11481 11482 switch (grant) { 11483 case GRANT_INSTALL: { 11484 // Revoke this as runtime permission to handle the case of 11485 // a runtime permission being downgraded to an install one. 11486 // Also in permission review mode we keep dangerous permissions 11487 // for legacy apps 11488 for (int userId : UserManagerService.getInstance().getUserIds()) { 11489 if (origPermissions.getRuntimePermissionState( 11490 bp.name, userId) != null) { 11491 // Revoke the runtime permission and clear the flags. 11492 origPermissions.revokeRuntimePermission(bp, userId); 11493 origPermissions.updatePermissionFlags(bp, userId, 11494 PackageManager.MASK_PERMISSION_FLAGS, 0); 11495 // If we revoked a permission permission, we have to write. 11496 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11497 changedRuntimePermissionUserIds, userId); 11498 } 11499 } 11500 // Grant an install permission. 11501 if (permissionsState.grantInstallPermission(bp) != 11502 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11503 changedInstallPermission = true; 11504 } 11505 } break; 11506 11507 case GRANT_RUNTIME: { 11508 // Grant previously granted runtime permissions. 11509 for (int userId : UserManagerService.getInstance().getUserIds()) { 11510 PermissionState permissionState = origPermissions 11511 .getRuntimePermissionState(bp.name, userId); 11512 int flags = permissionState != null 11513 ? permissionState.getFlags() : 0; 11514 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11515 // Don't propagate the permission in a permission review mode if 11516 // the former was revoked, i.e. marked to not propagate on upgrade. 11517 // Note that in a permission review mode install permissions are 11518 // represented as constantly granted runtime ones since we need to 11519 // keep a per user state associated with the permission. Also the 11520 // revoke on upgrade flag is no longer applicable and is reset. 11521 final boolean revokeOnUpgrade = (flags & PackageManager 11522 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11523 if (revokeOnUpgrade) { 11524 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11525 // Since we changed the flags, we have to write. 11526 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11527 changedRuntimePermissionUserIds, userId); 11528 } 11529 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11530 if (permissionsState.grantRuntimePermission(bp, userId) == 11531 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11532 // If we cannot put the permission as it was, 11533 // we have to write. 11534 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11535 changedRuntimePermissionUserIds, userId); 11536 } 11537 } 11538 11539 // If the app supports runtime permissions no need for a review. 11540 if (mPermissionReviewRequired 11541 && appSupportsRuntimePermissions 11542 && (flags & PackageManager 11543 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11544 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11545 // Since we changed the flags, we have to write. 11546 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11547 changedRuntimePermissionUserIds, userId); 11548 } 11549 } else if (mPermissionReviewRequired 11550 && !appSupportsRuntimePermissions) { 11551 // For legacy apps that need a permission review, every new 11552 // runtime permission is granted but it is pending a review. 11553 // We also need to review only platform defined runtime 11554 // permissions as these are the only ones the platform knows 11555 // how to disable the API to simulate revocation as legacy 11556 // apps don't expect to run with revoked permissions. 11557 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11558 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11559 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11560 // We changed the flags, hence have to write. 11561 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11562 changedRuntimePermissionUserIds, userId); 11563 } 11564 } 11565 if (permissionsState.grantRuntimePermission(bp, userId) 11566 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11567 // We changed the permission, hence have to write. 11568 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11569 changedRuntimePermissionUserIds, userId); 11570 } 11571 } 11572 // Propagate the permission flags. 11573 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11574 } 11575 } break; 11576 11577 case GRANT_UPGRADE: { 11578 // Grant runtime permissions for a previously held install permission. 11579 PermissionState permissionState = origPermissions 11580 .getInstallPermissionState(bp.name); 11581 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11582 11583 if (origPermissions.revokeInstallPermission(bp) 11584 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11585 // We will be transferring the permission flags, so clear them. 11586 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11587 PackageManager.MASK_PERMISSION_FLAGS, 0); 11588 changedInstallPermission = true; 11589 } 11590 11591 // If the permission is not to be promoted to runtime we ignore it and 11592 // also its other flags as they are not applicable to install permissions. 11593 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11594 for (int userId : currentUserIds) { 11595 if (permissionsState.grantRuntimePermission(bp, userId) != 11596 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11597 // Transfer the permission flags. 11598 permissionsState.updatePermissionFlags(bp, userId, 11599 flags, flags); 11600 // If we granted the permission, we have to write. 11601 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11602 changedRuntimePermissionUserIds, userId); 11603 } 11604 } 11605 } 11606 } break; 11607 11608 default: { 11609 if (packageOfInterest == null 11610 || packageOfInterest.equals(pkg.packageName)) { 11611 Slog.w(TAG, "Not granting permission " + perm 11612 + " to package " + pkg.packageName 11613 + " because it was previously installed without"); 11614 } 11615 } break; 11616 } 11617 } else { 11618 if (permissionsState.revokeInstallPermission(bp) != 11619 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11620 // Also drop the permission flags. 11621 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11622 PackageManager.MASK_PERMISSION_FLAGS, 0); 11623 changedInstallPermission = true; 11624 Slog.i(TAG, "Un-granting permission " + perm 11625 + " from package " + pkg.packageName 11626 + " (protectionLevel=" + bp.protectionLevel 11627 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11628 + ")"); 11629 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11630 // Don't print warning for app op permissions, since it is fine for them 11631 // not to be granted, there is a UI for the user to decide. 11632 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11633 Slog.w(TAG, "Not granting permission " + perm 11634 + " to package " + pkg.packageName 11635 + " (protectionLevel=" + bp.protectionLevel 11636 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11637 + ")"); 11638 } 11639 } 11640 } 11641 } 11642 11643 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11644 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11645 // This is the first that we have heard about this package, so the 11646 // permissions we have now selected are fixed until explicitly 11647 // changed. 11648 ps.installPermissionsFixed = true; 11649 } 11650 11651 // Persist the runtime permissions state for users with changes. If permissions 11652 // were revoked because no app in the shared user declares them we have to 11653 // write synchronously to avoid losing runtime permissions state. 11654 for (int userId : changedRuntimePermissionUserIds) { 11655 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11656 } 11657 } 11658 11659 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11660 boolean allowed = false; 11661 final int NP = PackageParser.NEW_PERMISSIONS.length; 11662 for (int ip=0; ip<NP; ip++) { 11663 final PackageParser.NewPermissionInfo npi 11664 = PackageParser.NEW_PERMISSIONS[ip]; 11665 if (npi.name.equals(perm) 11666 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11667 allowed = true; 11668 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11669 + pkg.packageName); 11670 break; 11671 } 11672 } 11673 return allowed; 11674 } 11675 11676 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11677 BasePermission bp, PermissionsState origPermissions) { 11678 boolean privilegedPermission = (bp.protectionLevel 11679 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11680 boolean privappPermissionsDisable = 11681 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11682 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11683 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11684 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11685 && !platformPackage && platformPermission) { 11686 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11687 .getPrivAppPermissions(pkg.packageName); 11688 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11689 if (!whitelisted) { 11690 Slog.w(TAG, "Privileged permission " + perm + " for package " 11691 + pkg.packageName + " - not in privapp-permissions whitelist"); 11692 // Only report violations for apps on system image 11693 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11694 if (mPrivappPermissionsViolations == null) { 11695 mPrivappPermissionsViolations = new ArraySet<>(); 11696 } 11697 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11698 } 11699 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11700 return false; 11701 } 11702 } 11703 } 11704 boolean allowed = (compareSignatures( 11705 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11706 == PackageManager.SIGNATURE_MATCH) 11707 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11708 == PackageManager.SIGNATURE_MATCH); 11709 if (!allowed && privilegedPermission) { 11710 if (isSystemApp(pkg)) { 11711 // For updated system applications, a system permission 11712 // is granted only if it had been defined by the original application. 11713 if (pkg.isUpdatedSystemApp()) { 11714 final PackageSetting sysPs = mSettings 11715 .getDisabledSystemPkgLPr(pkg.packageName); 11716 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11717 // If the original was granted this permission, we take 11718 // that grant decision as read and propagate it to the 11719 // update. 11720 if (sysPs.isPrivileged()) { 11721 allowed = true; 11722 } 11723 } else { 11724 // The system apk may have been updated with an older 11725 // version of the one on the data partition, but which 11726 // granted a new system permission that it didn't have 11727 // before. In this case we do want to allow the app to 11728 // now get the new permission if the ancestral apk is 11729 // privileged to get it. 11730 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11731 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11732 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11733 allowed = true; 11734 break; 11735 } 11736 } 11737 } 11738 // Also if a privileged parent package on the system image or any of 11739 // its children requested a privileged permission, the updated child 11740 // packages can also get the permission. 11741 if (pkg.parentPackage != null) { 11742 final PackageSetting disabledSysParentPs = mSettings 11743 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11744 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11745 && disabledSysParentPs.isPrivileged()) { 11746 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11747 allowed = true; 11748 } else if (disabledSysParentPs.pkg.childPackages != null) { 11749 final int count = disabledSysParentPs.pkg.childPackages.size(); 11750 for (int i = 0; i < count; i++) { 11751 PackageParser.Package disabledSysChildPkg = 11752 disabledSysParentPs.pkg.childPackages.get(i); 11753 if (isPackageRequestingPermission(disabledSysChildPkg, 11754 perm)) { 11755 allowed = true; 11756 break; 11757 } 11758 } 11759 } 11760 } 11761 } 11762 } 11763 } else { 11764 allowed = isPrivilegedApp(pkg); 11765 } 11766 } 11767 } 11768 if (!allowed) { 11769 if (!allowed && (bp.protectionLevel 11770 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11771 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11772 // If this was a previously normal/dangerous permission that got moved 11773 // to a system permission as part of the runtime permission redesign, then 11774 // we still want to blindly grant it to old apps. 11775 allowed = true; 11776 } 11777 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11778 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11779 // If this permission is to be granted to the system installer and 11780 // this app is an installer, then it gets the permission. 11781 allowed = true; 11782 } 11783 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11784 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11785 // If this permission is to be granted to the system verifier and 11786 // this app is a verifier, then it gets the permission. 11787 allowed = true; 11788 } 11789 if (!allowed && (bp.protectionLevel 11790 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11791 && isSystemApp(pkg)) { 11792 // Any pre-installed system app is allowed to get this permission. 11793 allowed = true; 11794 } 11795 if (!allowed && (bp.protectionLevel 11796 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11797 // For development permissions, a development permission 11798 // is granted only if it was already granted. 11799 allowed = origPermissions.hasInstallPermission(perm); 11800 } 11801 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11802 && pkg.packageName.equals(mSetupWizardPackage)) { 11803 // If this permission is to be granted to the system setup wizard and 11804 // this app is a setup wizard, then it gets the permission. 11805 allowed = true; 11806 } 11807 } 11808 return allowed; 11809 } 11810 11811 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11812 final int permCount = pkg.requestedPermissions.size(); 11813 for (int j = 0; j < permCount; j++) { 11814 String requestedPermission = pkg.requestedPermissions.get(j); 11815 if (permission.equals(requestedPermission)) { 11816 return true; 11817 } 11818 } 11819 return false; 11820 } 11821 11822 final class ActivityIntentResolver 11823 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11824 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11825 boolean defaultOnly, int userId) { 11826 if (!sUserManager.exists(userId)) return null; 11827 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11828 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11829 } 11830 11831 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11832 int userId) { 11833 if (!sUserManager.exists(userId)) return null; 11834 mFlags = flags; 11835 return super.queryIntent(intent, resolvedType, 11836 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11837 userId); 11838 } 11839 11840 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11841 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11842 if (!sUserManager.exists(userId)) return null; 11843 if (packageActivities == null) { 11844 return null; 11845 } 11846 mFlags = flags; 11847 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11848 final int N = packageActivities.size(); 11849 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11850 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11851 11852 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11853 for (int i = 0; i < N; ++i) { 11854 intentFilters = packageActivities.get(i).intents; 11855 if (intentFilters != null && intentFilters.size() > 0) { 11856 PackageParser.ActivityIntentInfo[] array = 11857 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11858 intentFilters.toArray(array); 11859 listCut.add(array); 11860 } 11861 } 11862 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11863 } 11864 11865 /** 11866 * Finds a privileged activity that matches the specified activity names. 11867 */ 11868 private PackageParser.Activity findMatchingActivity( 11869 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11870 for (PackageParser.Activity sysActivity : activityList) { 11871 if (sysActivity.info.name.equals(activityInfo.name)) { 11872 return sysActivity; 11873 } 11874 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11875 return sysActivity; 11876 } 11877 if (sysActivity.info.targetActivity != null) { 11878 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11879 return sysActivity; 11880 } 11881 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11882 return sysActivity; 11883 } 11884 } 11885 } 11886 return null; 11887 } 11888 11889 public class IterGenerator<E> { 11890 public Iterator<E> generate(ActivityIntentInfo info) { 11891 return null; 11892 } 11893 } 11894 11895 public class ActionIterGenerator extends IterGenerator<String> { 11896 @Override 11897 public Iterator<String> generate(ActivityIntentInfo info) { 11898 return info.actionsIterator(); 11899 } 11900 } 11901 11902 public class CategoriesIterGenerator extends IterGenerator<String> { 11903 @Override 11904 public Iterator<String> generate(ActivityIntentInfo info) { 11905 return info.categoriesIterator(); 11906 } 11907 } 11908 11909 public class SchemesIterGenerator extends IterGenerator<String> { 11910 @Override 11911 public Iterator<String> generate(ActivityIntentInfo info) { 11912 return info.schemesIterator(); 11913 } 11914 } 11915 11916 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11917 @Override 11918 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11919 return info.authoritiesIterator(); 11920 } 11921 } 11922 11923 /** 11924 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11925 * MODIFIED. Do not pass in a list that should not be changed. 11926 */ 11927 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11928 IterGenerator<T> generator, Iterator<T> searchIterator) { 11929 // loop through the set of actions; every one must be found in the intent filter 11930 while (searchIterator.hasNext()) { 11931 // we must have at least one filter in the list to consider a match 11932 if (intentList.size() == 0) { 11933 break; 11934 } 11935 11936 final T searchAction = searchIterator.next(); 11937 11938 // loop through the set of intent filters 11939 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11940 while (intentIter.hasNext()) { 11941 final ActivityIntentInfo intentInfo = intentIter.next(); 11942 boolean selectionFound = false; 11943 11944 // loop through the intent filter's selection criteria; at least one 11945 // of them must match the searched criteria 11946 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11947 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11948 final T intentSelection = intentSelectionIter.next(); 11949 if (intentSelection != null && intentSelection.equals(searchAction)) { 11950 selectionFound = true; 11951 break; 11952 } 11953 } 11954 11955 // the selection criteria wasn't found in this filter's set; this filter 11956 // is not a potential match 11957 if (!selectionFound) { 11958 intentIter.remove(); 11959 } 11960 } 11961 } 11962 } 11963 11964 private boolean isProtectedAction(ActivityIntentInfo filter) { 11965 final Iterator<String> actionsIter = filter.actionsIterator(); 11966 while (actionsIter != null && actionsIter.hasNext()) { 11967 final String filterAction = actionsIter.next(); 11968 if (PROTECTED_ACTIONS.contains(filterAction)) { 11969 return true; 11970 } 11971 } 11972 return false; 11973 } 11974 11975 /** 11976 * Adjusts the priority of the given intent filter according to policy. 11977 * <p> 11978 * <ul> 11979 * <li>The priority for non privileged applications is capped to '0'</li> 11980 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11981 * <li>The priority for unbundled updates to privileged applications is capped to the 11982 * priority defined on the system partition</li> 11983 * </ul> 11984 * <p> 11985 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11986 * allowed to obtain any priority on any action. 11987 */ 11988 private void adjustPriority( 11989 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11990 // nothing to do; priority is fine as-is 11991 if (intent.getPriority() <= 0) { 11992 return; 11993 } 11994 11995 final ActivityInfo activityInfo = intent.activity.info; 11996 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11997 11998 final boolean privilegedApp = 11999 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12000 if (!privilegedApp) { 12001 // non-privileged applications can never define a priority >0 12002 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12003 + " package: " + applicationInfo.packageName 12004 + " activity: " + intent.activity.className 12005 + " origPrio: " + intent.getPriority()); 12006 intent.setPriority(0); 12007 return; 12008 } 12009 12010 if (systemActivities == null) { 12011 // the system package is not disabled; we're parsing the system partition 12012 if (isProtectedAction(intent)) { 12013 if (mDeferProtectedFilters) { 12014 // We can't deal with these just yet. No component should ever obtain a 12015 // >0 priority for a protected actions, with ONE exception -- the setup 12016 // wizard. The setup wizard, however, cannot be known until we're able to 12017 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12018 // until all intent filters have been processed. Chicken, meet egg. 12019 // Let the filter temporarily have a high priority and rectify the 12020 // priorities after all system packages have been scanned. 12021 mProtectedFilters.add(intent); 12022 if (DEBUG_FILTERS) { 12023 Slog.i(TAG, "Protected action; save for later;" 12024 + " package: " + applicationInfo.packageName 12025 + " activity: " + intent.activity.className 12026 + " origPrio: " + intent.getPriority()); 12027 } 12028 return; 12029 } else { 12030 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12031 Slog.i(TAG, "No setup wizard;" 12032 + " All protected intents capped to priority 0"); 12033 } 12034 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12035 if (DEBUG_FILTERS) { 12036 Slog.i(TAG, "Found setup wizard;" 12037 + " allow priority " + intent.getPriority() + ";" 12038 + " package: " + intent.activity.info.packageName 12039 + " activity: " + intent.activity.className 12040 + " priority: " + intent.getPriority()); 12041 } 12042 // setup wizard gets whatever it wants 12043 return; 12044 } 12045 Slog.w(TAG, "Protected action; cap priority to 0;" 12046 + " package: " + intent.activity.info.packageName 12047 + " activity: " + intent.activity.className 12048 + " origPrio: " + intent.getPriority()); 12049 intent.setPriority(0); 12050 return; 12051 } 12052 } 12053 // privileged apps on the system image get whatever priority they request 12054 return; 12055 } 12056 12057 // privileged app unbundled update ... try to find the same activity 12058 final PackageParser.Activity foundActivity = 12059 findMatchingActivity(systemActivities, activityInfo); 12060 if (foundActivity == null) { 12061 // this is a new activity; it cannot obtain >0 priority 12062 if (DEBUG_FILTERS) { 12063 Slog.i(TAG, "New activity; cap priority to 0;" 12064 + " package: " + applicationInfo.packageName 12065 + " activity: " + intent.activity.className 12066 + " origPrio: " + intent.getPriority()); 12067 } 12068 intent.setPriority(0); 12069 return; 12070 } 12071 12072 // found activity, now check for filter equivalence 12073 12074 // a shallow copy is enough; we modify the list, not its contents 12075 final List<ActivityIntentInfo> intentListCopy = 12076 new ArrayList<>(foundActivity.intents); 12077 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12078 12079 // find matching action subsets 12080 final Iterator<String> actionsIterator = intent.actionsIterator(); 12081 if (actionsIterator != null) { 12082 getIntentListSubset( 12083 intentListCopy, new ActionIterGenerator(), actionsIterator); 12084 if (intentListCopy.size() == 0) { 12085 // no more intents to match; we're not equivalent 12086 if (DEBUG_FILTERS) { 12087 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12088 + " package: " + applicationInfo.packageName 12089 + " activity: " + intent.activity.className 12090 + " origPrio: " + intent.getPriority()); 12091 } 12092 intent.setPriority(0); 12093 return; 12094 } 12095 } 12096 12097 // find matching category subsets 12098 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12099 if (categoriesIterator != null) { 12100 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12101 categoriesIterator); 12102 if (intentListCopy.size() == 0) { 12103 // no more intents to match; we're not equivalent 12104 if (DEBUG_FILTERS) { 12105 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12106 + " package: " + applicationInfo.packageName 12107 + " activity: " + intent.activity.className 12108 + " origPrio: " + intent.getPriority()); 12109 } 12110 intent.setPriority(0); 12111 return; 12112 } 12113 } 12114 12115 // find matching schemes subsets 12116 final Iterator<String> schemesIterator = intent.schemesIterator(); 12117 if (schemesIterator != null) { 12118 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12119 schemesIterator); 12120 if (intentListCopy.size() == 0) { 12121 // no more intents to match; we're not equivalent 12122 if (DEBUG_FILTERS) { 12123 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12124 + " package: " + applicationInfo.packageName 12125 + " activity: " + intent.activity.className 12126 + " origPrio: " + intent.getPriority()); 12127 } 12128 intent.setPriority(0); 12129 return; 12130 } 12131 } 12132 12133 // find matching authorities subsets 12134 final Iterator<IntentFilter.AuthorityEntry> 12135 authoritiesIterator = intent.authoritiesIterator(); 12136 if (authoritiesIterator != null) { 12137 getIntentListSubset(intentListCopy, 12138 new AuthoritiesIterGenerator(), 12139 authoritiesIterator); 12140 if (intentListCopy.size() == 0) { 12141 // no more intents to match; we're not equivalent 12142 if (DEBUG_FILTERS) { 12143 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12144 + " package: " + applicationInfo.packageName 12145 + " activity: " + intent.activity.className 12146 + " origPrio: " + intent.getPriority()); 12147 } 12148 intent.setPriority(0); 12149 return; 12150 } 12151 } 12152 12153 // we found matching filter(s); app gets the max priority of all intents 12154 int cappedPriority = 0; 12155 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12156 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12157 } 12158 if (intent.getPriority() > cappedPriority) { 12159 if (DEBUG_FILTERS) { 12160 Slog.i(TAG, "Found matching filter(s);" 12161 + " cap priority to " + cappedPriority + ";" 12162 + " package: " + applicationInfo.packageName 12163 + " activity: " + intent.activity.className 12164 + " origPrio: " + intent.getPriority()); 12165 } 12166 intent.setPriority(cappedPriority); 12167 return; 12168 } 12169 // all this for nothing; the requested priority was <= what was on the system 12170 } 12171 12172 public final void addActivity(PackageParser.Activity a, String type) { 12173 mActivities.put(a.getComponentName(), a); 12174 if (DEBUG_SHOW_INFO) 12175 Log.v( 12176 TAG, " " + type + " " + 12177 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12178 if (DEBUG_SHOW_INFO) 12179 Log.v(TAG, " Class=" + a.info.name); 12180 final int NI = a.intents.size(); 12181 for (int j=0; j<NI; j++) { 12182 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12183 if ("activity".equals(type)) { 12184 final PackageSetting ps = 12185 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12186 final List<PackageParser.Activity> systemActivities = 12187 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12188 adjustPriority(systemActivities, intent); 12189 } 12190 if (DEBUG_SHOW_INFO) { 12191 Log.v(TAG, " IntentFilter:"); 12192 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12193 } 12194 if (!intent.debugCheck()) { 12195 Log.w(TAG, "==> For Activity " + a.info.name); 12196 } 12197 addFilter(intent); 12198 } 12199 } 12200 12201 public final void removeActivity(PackageParser.Activity a, String type) { 12202 mActivities.remove(a.getComponentName()); 12203 if (DEBUG_SHOW_INFO) { 12204 Log.v(TAG, " " + type + " " 12205 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12206 : a.info.name) + ":"); 12207 Log.v(TAG, " Class=" + a.info.name); 12208 } 12209 final int NI = a.intents.size(); 12210 for (int j=0; j<NI; j++) { 12211 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12212 if (DEBUG_SHOW_INFO) { 12213 Log.v(TAG, " IntentFilter:"); 12214 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12215 } 12216 removeFilter(intent); 12217 } 12218 } 12219 12220 @Override 12221 protected boolean allowFilterResult( 12222 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12223 ActivityInfo filterAi = filter.activity.info; 12224 for (int i=dest.size()-1; i>=0; i--) { 12225 ActivityInfo destAi = dest.get(i).activityInfo; 12226 if (destAi.name == filterAi.name 12227 && destAi.packageName == filterAi.packageName) { 12228 return false; 12229 } 12230 } 12231 return true; 12232 } 12233 12234 @Override 12235 protected ActivityIntentInfo[] newArray(int size) { 12236 return new ActivityIntentInfo[size]; 12237 } 12238 12239 @Override 12240 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12241 if (!sUserManager.exists(userId)) return true; 12242 PackageParser.Package p = filter.activity.owner; 12243 if (p != null) { 12244 PackageSetting ps = (PackageSetting)p.mExtras; 12245 if (ps != null) { 12246 // System apps are never considered stopped for purposes of 12247 // filtering, because there may be no way for the user to 12248 // actually re-launch them. 12249 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12250 && ps.getStopped(userId); 12251 } 12252 } 12253 return false; 12254 } 12255 12256 @Override 12257 protected boolean isPackageForFilter(String packageName, 12258 PackageParser.ActivityIntentInfo info) { 12259 return packageName.equals(info.activity.owner.packageName); 12260 } 12261 12262 @Override 12263 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12264 int match, int userId) { 12265 if (!sUserManager.exists(userId)) return null; 12266 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12267 return null; 12268 } 12269 final PackageParser.Activity activity = info.activity; 12270 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12271 if (ps == null) { 12272 return null; 12273 } 12274 final PackageUserState userState = ps.readUserState(userId); 12275 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12276 userState, userId); 12277 if (ai == null) { 12278 return null; 12279 } 12280 final boolean matchVisibleToInstantApp = 12281 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12282 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12283 // throw out filters that aren't visible to ephemeral apps 12284 if (matchVisibleToInstantApp 12285 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12286 return null; 12287 } 12288 // throw out ephemeral filters if we're not explicitly requesting them 12289 if (!isInstantApp && userState.instantApp) { 12290 return null; 12291 } 12292 // throw out instant app filters if updates are available; will trigger 12293 // instant app resolution 12294 if (userState.instantApp && ps.isUpdateAvailable()) { 12295 return null; 12296 } 12297 final ResolveInfo res = new ResolveInfo(); 12298 res.activityInfo = ai; 12299 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12300 res.filter = info; 12301 } 12302 if (info != null) { 12303 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12304 } 12305 res.priority = info.getPriority(); 12306 res.preferredOrder = activity.owner.mPreferredOrder; 12307 //System.out.println("Result: " + res.activityInfo.className + 12308 // " = " + res.priority); 12309 res.match = match; 12310 res.isDefault = info.hasDefault; 12311 res.labelRes = info.labelRes; 12312 res.nonLocalizedLabel = info.nonLocalizedLabel; 12313 if (userNeedsBadging(userId)) { 12314 res.noResourceId = true; 12315 } else { 12316 res.icon = info.icon; 12317 } 12318 res.iconResourceId = info.icon; 12319 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12320 res.instantAppAvailable = userState.instantApp; 12321 return res; 12322 } 12323 12324 @Override 12325 protected void sortResults(List<ResolveInfo> results) { 12326 Collections.sort(results, mResolvePrioritySorter); 12327 } 12328 12329 @Override 12330 protected void dumpFilter(PrintWriter out, String prefix, 12331 PackageParser.ActivityIntentInfo filter) { 12332 out.print(prefix); out.print( 12333 Integer.toHexString(System.identityHashCode(filter.activity))); 12334 out.print(' '); 12335 filter.activity.printComponentShortName(out); 12336 out.print(" filter "); 12337 out.println(Integer.toHexString(System.identityHashCode(filter))); 12338 } 12339 12340 @Override 12341 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12342 return filter.activity; 12343 } 12344 12345 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12346 PackageParser.Activity activity = (PackageParser.Activity)label; 12347 out.print(prefix); out.print( 12348 Integer.toHexString(System.identityHashCode(activity))); 12349 out.print(' '); 12350 activity.printComponentShortName(out); 12351 if (count > 1) { 12352 out.print(" ("); out.print(count); out.print(" filters)"); 12353 } 12354 out.println(); 12355 } 12356 12357 // Keys are String (activity class name), values are Activity. 12358 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12359 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12360 private int mFlags; 12361 } 12362 12363 private final class ServiceIntentResolver 12364 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12365 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12366 boolean defaultOnly, int userId) { 12367 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12368 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12369 } 12370 12371 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12372 int userId) { 12373 if (!sUserManager.exists(userId)) return null; 12374 mFlags = flags; 12375 return super.queryIntent(intent, resolvedType, 12376 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12377 userId); 12378 } 12379 12380 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12381 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12382 if (!sUserManager.exists(userId)) return null; 12383 if (packageServices == null) { 12384 return null; 12385 } 12386 mFlags = flags; 12387 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12388 final int N = packageServices.size(); 12389 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12390 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12391 12392 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12393 for (int i = 0; i < N; ++i) { 12394 intentFilters = packageServices.get(i).intents; 12395 if (intentFilters != null && intentFilters.size() > 0) { 12396 PackageParser.ServiceIntentInfo[] array = 12397 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12398 intentFilters.toArray(array); 12399 listCut.add(array); 12400 } 12401 } 12402 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12403 } 12404 12405 public final void addService(PackageParser.Service s) { 12406 mServices.put(s.getComponentName(), s); 12407 if (DEBUG_SHOW_INFO) { 12408 Log.v(TAG, " " 12409 + (s.info.nonLocalizedLabel != null 12410 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12411 Log.v(TAG, " Class=" + s.info.name); 12412 } 12413 final int NI = s.intents.size(); 12414 int j; 12415 for (j=0; j<NI; j++) { 12416 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12417 if (DEBUG_SHOW_INFO) { 12418 Log.v(TAG, " IntentFilter:"); 12419 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12420 } 12421 if (!intent.debugCheck()) { 12422 Log.w(TAG, "==> For Service " + s.info.name); 12423 } 12424 addFilter(intent); 12425 } 12426 } 12427 12428 public final void removeService(PackageParser.Service s) { 12429 mServices.remove(s.getComponentName()); 12430 if (DEBUG_SHOW_INFO) { 12431 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12432 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12433 Log.v(TAG, " Class=" + s.info.name); 12434 } 12435 final int NI = s.intents.size(); 12436 int j; 12437 for (j=0; j<NI; j++) { 12438 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12439 if (DEBUG_SHOW_INFO) { 12440 Log.v(TAG, " IntentFilter:"); 12441 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12442 } 12443 removeFilter(intent); 12444 } 12445 } 12446 12447 @Override 12448 protected boolean allowFilterResult( 12449 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12450 ServiceInfo filterSi = filter.service.info; 12451 for (int i=dest.size()-1; i>=0; i--) { 12452 ServiceInfo destAi = dest.get(i).serviceInfo; 12453 if (destAi.name == filterSi.name 12454 && destAi.packageName == filterSi.packageName) { 12455 return false; 12456 } 12457 } 12458 return true; 12459 } 12460 12461 @Override 12462 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12463 return new PackageParser.ServiceIntentInfo[size]; 12464 } 12465 12466 @Override 12467 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12468 if (!sUserManager.exists(userId)) return true; 12469 PackageParser.Package p = filter.service.owner; 12470 if (p != null) { 12471 PackageSetting ps = (PackageSetting)p.mExtras; 12472 if (ps != null) { 12473 // System apps are never considered stopped for purposes of 12474 // filtering, because there may be no way for the user to 12475 // actually re-launch them. 12476 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12477 && ps.getStopped(userId); 12478 } 12479 } 12480 return false; 12481 } 12482 12483 @Override 12484 protected boolean isPackageForFilter(String packageName, 12485 PackageParser.ServiceIntentInfo info) { 12486 return packageName.equals(info.service.owner.packageName); 12487 } 12488 12489 @Override 12490 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12491 int match, int userId) { 12492 if (!sUserManager.exists(userId)) return null; 12493 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12494 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12495 return null; 12496 } 12497 final PackageParser.Service service = info.service; 12498 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12499 if (ps == null) { 12500 return null; 12501 } 12502 final PackageUserState userState = ps.readUserState(userId); 12503 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12504 userState, userId); 12505 if (si == null) { 12506 return null; 12507 } 12508 final boolean matchVisibleToInstantApp = 12509 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12510 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12511 // throw out filters that aren't visible to ephemeral apps 12512 if (matchVisibleToInstantApp 12513 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12514 return null; 12515 } 12516 // throw out ephemeral filters if we're not explicitly requesting them 12517 if (!isInstantApp && userState.instantApp) { 12518 return null; 12519 } 12520 // throw out instant app filters if updates are available; will trigger 12521 // instant app resolution 12522 if (userState.instantApp && ps.isUpdateAvailable()) { 12523 return null; 12524 } 12525 final ResolveInfo res = new ResolveInfo(); 12526 res.serviceInfo = si; 12527 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12528 res.filter = filter; 12529 } 12530 res.priority = info.getPriority(); 12531 res.preferredOrder = service.owner.mPreferredOrder; 12532 res.match = match; 12533 res.isDefault = info.hasDefault; 12534 res.labelRes = info.labelRes; 12535 res.nonLocalizedLabel = info.nonLocalizedLabel; 12536 res.icon = info.icon; 12537 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12538 return res; 12539 } 12540 12541 @Override 12542 protected void sortResults(List<ResolveInfo> results) { 12543 Collections.sort(results, mResolvePrioritySorter); 12544 } 12545 12546 @Override 12547 protected void dumpFilter(PrintWriter out, String prefix, 12548 PackageParser.ServiceIntentInfo filter) { 12549 out.print(prefix); out.print( 12550 Integer.toHexString(System.identityHashCode(filter.service))); 12551 out.print(' '); 12552 filter.service.printComponentShortName(out); 12553 out.print(" filter "); 12554 out.println(Integer.toHexString(System.identityHashCode(filter))); 12555 } 12556 12557 @Override 12558 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12559 return filter.service; 12560 } 12561 12562 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12563 PackageParser.Service service = (PackageParser.Service)label; 12564 out.print(prefix); out.print( 12565 Integer.toHexString(System.identityHashCode(service))); 12566 out.print(' '); 12567 service.printComponentShortName(out); 12568 if (count > 1) { 12569 out.print(" ("); out.print(count); out.print(" filters)"); 12570 } 12571 out.println(); 12572 } 12573 12574// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12575// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12576// final List<ResolveInfo> retList = Lists.newArrayList(); 12577// while (i.hasNext()) { 12578// final ResolveInfo resolveInfo = (ResolveInfo) i; 12579// if (isEnabledLP(resolveInfo.serviceInfo)) { 12580// retList.add(resolveInfo); 12581// } 12582// } 12583// return retList; 12584// } 12585 12586 // Keys are String (activity class name), values are Activity. 12587 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12588 = new ArrayMap<ComponentName, PackageParser.Service>(); 12589 private int mFlags; 12590 } 12591 12592 private final class ProviderIntentResolver 12593 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12594 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12595 boolean defaultOnly, int userId) { 12596 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12597 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12598 } 12599 12600 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12601 int userId) { 12602 if (!sUserManager.exists(userId)) 12603 return null; 12604 mFlags = flags; 12605 return super.queryIntent(intent, resolvedType, 12606 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12607 userId); 12608 } 12609 12610 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12611 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12612 if (!sUserManager.exists(userId)) 12613 return null; 12614 if (packageProviders == null) { 12615 return null; 12616 } 12617 mFlags = flags; 12618 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12619 final int N = packageProviders.size(); 12620 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12621 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12622 12623 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12624 for (int i = 0; i < N; ++i) { 12625 intentFilters = packageProviders.get(i).intents; 12626 if (intentFilters != null && intentFilters.size() > 0) { 12627 PackageParser.ProviderIntentInfo[] array = 12628 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12629 intentFilters.toArray(array); 12630 listCut.add(array); 12631 } 12632 } 12633 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12634 } 12635 12636 public final void addProvider(PackageParser.Provider p) { 12637 if (mProviders.containsKey(p.getComponentName())) { 12638 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12639 return; 12640 } 12641 12642 mProviders.put(p.getComponentName(), p); 12643 if (DEBUG_SHOW_INFO) { 12644 Log.v(TAG, " " 12645 + (p.info.nonLocalizedLabel != null 12646 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12647 Log.v(TAG, " Class=" + p.info.name); 12648 } 12649 final int NI = p.intents.size(); 12650 int j; 12651 for (j = 0; j < NI; j++) { 12652 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12653 if (DEBUG_SHOW_INFO) { 12654 Log.v(TAG, " IntentFilter:"); 12655 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12656 } 12657 if (!intent.debugCheck()) { 12658 Log.w(TAG, "==> For Provider " + p.info.name); 12659 } 12660 addFilter(intent); 12661 } 12662 } 12663 12664 public final void removeProvider(PackageParser.Provider p) { 12665 mProviders.remove(p.getComponentName()); 12666 if (DEBUG_SHOW_INFO) { 12667 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12668 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12669 Log.v(TAG, " Class=" + p.info.name); 12670 } 12671 final int NI = p.intents.size(); 12672 int j; 12673 for (j = 0; j < NI; j++) { 12674 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12675 if (DEBUG_SHOW_INFO) { 12676 Log.v(TAG, " IntentFilter:"); 12677 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12678 } 12679 removeFilter(intent); 12680 } 12681 } 12682 12683 @Override 12684 protected boolean allowFilterResult( 12685 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12686 ProviderInfo filterPi = filter.provider.info; 12687 for (int i = dest.size() - 1; i >= 0; i--) { 12688 ProviderInfo destPi = dest.get(i).providerInfo; 12689 if (destPi.name == filterPi.name 12690 && destPi.packageName == filterPi.packageName) { 12691 return false; 12692 } 12693 } 12694 return true; 12695 } 12696 12697 @Override 12698 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12699 return new PackageParser.ProviderIntentInfo[size]; 12700 } 12701 12702 @Override 12703 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12704 if (!sUserManager.exists(userId)) 12705 return true; 12706 PackageParser.Package p = filter.provider.owner; 12707 if (p != null) { 12708 PackageSetting ps = (PackageSetting) p.mExtras; 12709 if (ps != null) { 12710 // System apps are never considered stopped for purposes of 12711 // filtering, because there may be no way for the user to 12712 // actually re-launch them. 12713 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12714 && ps.getStopped(userId); 12715 } 12716 } 12717 return false; 12718 } 12719 12720 @Override 12721 protected boolean isPackageForFilter(String packageName, 12722 PackageParser.ProviderIntentInfo info) { 12723 return packageName.equals(info.provider.owner.packageName); 12724 } 12725 12726 @Override 12727 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12728 int match, int userId) { 12729 if (!sUserManager.exists(userId)) 12730 return null; 12731 final PackageParser.ProviderIntentInfo info = filter; 12732 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12733 return null; 12734 } 12735 final PackageParser.Provider provider = info.provider; 12736 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12737 if (ps == null) { 12738 return null; 12739 } 12740 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12741 ps.readUserState(userId), userId); 12742 if (pi == null) { 12743 return null; 12744 } 12745 final ResolveInfo res = new ResolveInfo(); 12746 res.providerInfo = pi; 12747 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12748 res.filter = filter; 12749 } 12750 res.priority = info.getPriority(); 12751 res.preferredOrder = provider.owner.mPreferredOrder; 12752 res.match = match; 12753 res.isDefault = info.hasDefault; 12754 res.labelRes = info.labelRes; 12755 res.nonLocalizedLabel = info.nonLocalizedLabel; 12756 res.icon = info.icon; 12757 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12758 return res; 12759 } 12760 12761 @Override 12762 protected void sortResults(List<ResolveInfo> results) { 12763 Collections.sort(results, mResolvePrioritySorter); 12764 } 12765 12766 @Override 12767 protected void dumpFilter(PrintWriter out, String prefix, 12768 PackageParser.ProviderIntentInfo filter) { 12769 out.print(prefix); 12770 out.print( 12771 Integer.toHexString(System.identityHashCode(filter.provider))); 12772 out.print(' '); 12773 filter.provider.printComponentShortName(out); 12774 out.print(" filter "); 12775 out.println(Integer.toHexString(System.identityHashCode(filter))); 12776 } 12777 12778 @Override 12779 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12780 return filter.provider; 12781 } 12782 12783 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12784 PackageParser.Provider provider = (PackageParser.Provider)label; 12785 out.print(prefix); out.print( 12786 Integer.toHexString(System.identityHashCode(provider))); 12787 out.print(' '); 12788 provider.printComponentShortName(out); 12789 if (count > 1) { 12790 out.print(" ("); out.print(count); out.print(" filters)"); 12791 } 12792 out.println(); 12793 } 12794 12795 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12796 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12797 private int mFlags; 12798 } 12799 12800 static final class EphemeralIntentResolver 12801 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12802 /** 12803 * The result that has the highest defined order. Ordering applies on a 12804 * per-package basis. Mapping is from package name to Pair of order and 12805 * EphemeralResolveInfo. 12806 * <p> 12807 * NOTE: This is implemented as a field variable for convenience and efficiency. 12808 * By having a field variable, we're able to track filter ordering as soon as 12809 * a non-zero order is defined. Otherwise, multiple loops across the result set 12810 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12811 * this needs to be contained entirely within {@link #filterResults}. 12812 */ 12813 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12814 12815 @Override 12816 protected AuxiliaryResolveInfo[] newArray(int size) { 12817 return new AuxiliaryResolveInfo[size]; 12818 } 12819 12820 @Override 12821 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12822 return true; 12823 } 12824 12825 @Override 12826 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12827 int userId) { 12828 if (!sUserManager.exists(userId)) { 12829 return null; 12830 } 12831 final String packageName = responseObj.resolveInfo.getPackageName(); 12832 final Integer order = responseObj.getOrder(); 12833 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12834 mOrderResult.get(packageName); 12835 // ordering is enabled and this item's order isn't high enough 12836 if (lastOrderResult != null && lastOrderResult.first >= order) { 12837 return null; 12838 } 12839 final InstantAppResolveInfo res = responseObj.resolveInfo; 12840 if (order > 0) { 12841 // non-zero order, enable ordering 12842 mOrderResult.put(packageName, new Pair<>(order, res)); 12843 } 12844 return responseObj; 12845 } 12846 12847 @Override 12848 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12849 // only do work if ordering is enabled [most of the time it won't be] 12850 if (mOrderResult.size() == 0) { 12851 return; 12852 } 12853 int resultSize = results.size(); 12854 for (int i = 0; i < resultSize; i++) { 12855 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12856 final String packageName = info.getPackageName(); 12857 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12858 if (savedInfo == null) { 12859 // package doesn't having ordering 12860 continue; 12861 } 12862 if (savedInfo.second == info) { 12863 // circled back to the highest ordered item; remove from order list 12864 mOrderResult.remove(savedInfo); 12865 if (mOrderResult.size() == 0) { 12866 // no more ordered items 12867 break; 12868 } 12869 continue; 12870 } 12871 // item has a worse order, remove it from the result list 12872 results.remove(i); 12873 resultSize--; 12874 i--; 12875 } 12876 } 12877 } 12878 12879 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12880 new Comparator<ResolveInfo>() { 12881 public int compare(ResolveInfo r1, ResolveInfo r2) { 12882 int v1 = r1.priority; 12883 int v2 = r2.priority; 12884 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12885 if (v1 != v2) { 12886 return (v1 > v2) ? -1 : 1; 12887 } 12888 v1 = r1.preferredOrder; 12889 v2 = r2.preferredOrder; 12890 if (v1 != v2) { 12891 return (v1 > v2) ? -1 : 1; 12892 } 12893 if (r1.isDefault != r2.isDefault) { 12894 return r1.isDefault ? -1 : 1; 12895 } 12896 v1 = r1.match; 12897 v2 = r2.match; 12898 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12899 if (v1 != v2) { 12900 return (v1 > v2) ? -1 : 1; 12901 } 12902 if (r1.system != r2.system) { 12903 return r1.system ? -1 : 1; 12904 } 12905 if (r1.activityInfo != null) { 12906 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12907 } 12908 if (r1.serviceInfo != null) { 12909 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12910 } 12911 if (r1.providerInfo != null) { 12912 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12913 } 12914 return 0; 12915 } 12916 }; 12917 12918 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12919 new Comparator<ProviderInfo>() { 12920 public int compare(ProviderInfo p1, ProviderInfo p2) { 12921 final int v1 = p1.initOrder; 12922 final int v2 = p2.initOrder; 12923 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12924 } 12925 }; 12926 12927 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12928 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12929 final int[] userIds) { 12930 mHandler.post(new Runnable() { 12931 @Override 12932 public void run() { 12933 try { 12934 final IActivityManager am = ActivityManager.getService(); 12935 if (am == null) return; 12936 final int[] resolvedUserIds; 12937 if (userIds == null) { 12938 resolvedUserIds = am.getRunningUserIds(); 12939 } else { 12940 resolvedUserIds = userIds; 12941 } 12942 for (int id : resolvedUserIds) { 12943 final Intent intent = new Intent(action, 12944 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12945 if (extras != null) { 12946 intent.putExtras(extras); 12947 } 12948 if (targetPkg != null) { 12949 intent.setPackage(targetPkg); 12950 } 12951 // Modify the UID when posting to other users 12952 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12953 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12954 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12955 intent.putExtra(Intent.EXTRA_UID, uid); 12956 } 12957 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12958 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12959 if (DEBUG_BROADCASTS) { 12960 RuntimeException here = new RuntimeException("here"); 12961 here.fillInStackTrace(); 12962 Slog.d(TAG, "Sending to user " + id + ": " 12963 + intent.toShortString(false, true, false, false) 12964 + " " + intent.getExtras(), here); 12965 } 12966 am.broadcastIntent(null, intent, null, finishedReceiver, 12967 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12968 null, finishedReceiver != null, false, id); 12969 } 12970 } catch (RemoteException ex) { 12971 } 12972 } 12973 }); 12974 } 12975 12976 /** 12977 * Check if the external storage media is available. This is true if there 12978 * is a mounted external storage medium or if the external storage is 12979 * emulated. 12980 */ 12981 private boolean isExternalMediaAvailable() { 12982 return mMediaMounted || Environment.isExternalStorageEmulated(); 12983 } 12984 12985 @Override 12986 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12987 // writer 12988 synchronized (mPackages) { 12989 if (!isExternalMediaAvailable()) { 12990 // If the external storage is no longer mounted at this point, 12991 // the caller may not have been able to delete all of this 12992 // packages files and can not delete any more. Bail. 12993 return null; 12994 } 12995 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12996 if (lastPackage != null) { 12997 pkgs.remove(lastPackage); 12998 } 12999 if (pkgs.size() > 0) { 13000 return pkgs.get(0); 13001 } 13002 } 13003 return null; 13004 } 13005 13006 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13007 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13008 userId, andCode ? 1 : 0, packageName); 13009 if (mSystemReady) { 13010 msg.sendToTarget(); 13011 } else { 13012 if (mPostSystemReadyMessages == null) { 13013 mPostSystemReadyMessages = new ArrayList<>(); 13014 } 13015 mPostSystemReadyMessages.add(msg); 13016 } 13017 } 13018 13019 void startCleaningPackages() { 13020 // reader 13021 if (!isExternalMediaAvailable()) { 13022 return; 13023 } 13024 synchronized (mPackages) { 13025 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13026 return; 13027 } 13028 } 13029 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13030 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13031 IActivityManager am = ActivityManager.getService(); 13032 if (am != null) { 13033 try { 13034 am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(), 13035 UserHandle.USER_SYSTEM); 13036 } catch (RemoteException e) { 13037 } 13038 } 13039 } 13040 13041 @Override 13042 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13043 int installFlags, String installerPackageName, int userId) { 13044 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13045 13046 final int callingUid = Binder.getCallingUid(); 13047 enforceCrossUserPermission(callingUid, userId, 13048 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13049 13050 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13051 try { 13052 if (observer != null) { 13053 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13054 } 13055 } catch (RemoteException re) { 13056 } 13057 return; 13058 } 13059 13060 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13061 installFlags |= PackageManager.INSTALL_FROM_ADB; 13062 13063 } else { 13064 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13065 // about installerPackageName. 13066 13067 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13068 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13069 } 13070 13071 UserHandle user; 13072 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13073 user = UserHandle.ALL; 13074 } else { 13075 user = new UserHandle(userId); 13076 } 13077 13078 // Only system components can circumvent runtime permissions when installing. 13079 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13080 && mContext.checkCallingOrSelfPermission(Manifest.permission 13081 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13082 throw new SecurityException("You need the " 13083 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13084 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13085 } 13086 13087 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13088 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13089 throw new IllegalArgumentException( 13090 "New installs into ASEC containers no longer supported"); 13091 } 13092 13093 final File originFile = new File(originPath); 13094 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13095 13096 final Message msg = mHandler.obtainMessage(INIT_COPY); 13097 final VerificationInfo verificationInfo = new VerificationInfo( 13098 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13099 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13100 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13101 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13102 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13103 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13104 msg.obj = params; 13105 13106 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13107 System.identityHashCode(msg.obj)); 13108 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13109 System.identityHashCode(msg.obj)); 13110 13111 mHandler.sendMessage(msg); 13112 } 13113 13114 13115 /** 13116 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13117 * it is acting on behalf on an enterprise or the user). 13118 * 13119 * Note that the ordering of the conditionals in this method is important. The checks we perform 13120 * are as follows, in this order: 13121 * 13122 * 1) If the install is being performed by a system app, we can trust the app to have set the 13123 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13124 * what it is. 13125 * 2) If the install is being performed by a device or profile owner app, the install reason 13126 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13127 * set the install reason correctly. If the app targets an older SDK version where install 13128 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13129 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13130 * 3) In all other cases, the install is being performed by a regular app that is neither part 13131 * of the system nor a device or profile owner. We have no reason to believe that this app is 13132 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13133 * set to enterprise policy and if so, change it to unknown instead. 13134 */ 13135 private int fixUpInstallReason(String installerPackageName, int installerUid, 13136 int installReason) { 13137 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13138 == PERMISSION_GRANTED) { 13139 // If the install is being performed by a system app, we trust that app to have set the 13140 // install reason correctly. 13141 return installReason; 13142 } 13143 13144 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13145 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13146 if (dpm != null) { 13147 ComponentName owner = null; 13148 try { 13149 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13150 if (owner == null) { 13151 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13152 } 13153 } catch (RemoteException e) { 13154 } 13155 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13156 // If the install is being performed by a device or profile owner, the install 13157 // reason should be enterprise policy. 13158 return PackageManager.INSTALL_REASON_POLICY; 13159 } 13160 } 13161 13162 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13163 // If the install is being performed by a regular app (i.e. neither system app nor 13164 // device or profile owner), we have no reason to believe that the app is acting on 13165 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13166 // change it to unknown instead. 13167 return PackageManager.INSTALL_REASON_UNKNOWN; 13168 } 13169 13170 // If the install is being performed by a regular app and the install reason was set to any 13171 // value but enterprise policy, leave the install reason unchanged. 13172 return installReason; 13173 } 13174 13175 void installStage(String packageName, File stagedDir, String stagedCid, 13176 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13177 String installerPackageName, int installerUid, UserHandle user, 13178 Certificate[][] certificates) { 13179 if (DEBUG_EPHEMERAL) { 13180 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13181 Slog.d(TAG, "Ephemeral install of " + packageName); 13182 } 13183 } 13184 final VerificationInfo verificationInfo = new VerificationInfo( 13185 sessionParams.originatingUri, sessionParams.referrerUri, 13186 sessionParams.originatingUid, installerUid); 13187 13188 final OriginInfo origin; 13189 if (stagedDir != null) { 13190 origin = OriginInfo.fromStagedFile(stagedDir); 13191 } else { 13192 origin = OriginInfo.fromStagedContainer(stagedCid); 13193 } 13194 13195 final Message msg = mHandler.obtainMessage(INIT_COPY); 13196 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13197 sessionParams.installReason); 13198 final InstallParams params = new InstallParams(origin, null, observer, 13199 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13200 verificationInfo, user, sessionParams.abiOverride, 13201 sessionParams.grantedRuntimePermissions, certificates, installReason); 13202 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13203 msg.obj = params; 13204 13205 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13206 System.identityHashCode(msg.obj)); 13207 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13208 System.identityHashCode(msg.obj)); 13209 13210 mHandler.sendMessage(msg); 13211 } 13212 13213 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13214 int userId) { 13215 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13216 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13217 } 13218 13219 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13220 int appId, int... userIds) { 13221 if (ArrayUtils.isEmpty(userIds)) { 13222 return; 13223 } 13224 Bundle extras = new Bundle(1); 13225 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13226 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13227 13228 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13229 packageName, extras, 0, null, null, userIds); 13230 if (isSystem) { 13231 mHandler.post(() -> { 13232 for (int userId : userIds) { 13233 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13234 } 13235 } 13236 ); 13237 } 13238 } 13239 13240 /** 13241 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13242 * automatically without needing an explicit launch. 13243 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13244 */ 13245 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13246 // If user is not running, the app didn't miss any broadcast 13247 if (!mUserManagerInternal.isUserRunning(userId)) { 13248 return; 13249 } 13250 final IActivityManager am = ActivityManager.getService(); 13251 try { 13252 // Deliver LOCKED_BOOT_COMPLETED first 13253 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13254 .setPackage(packageName); 13255 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13256 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13257 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13258 13259 // Deliver BOOT_COMPLETED only if user is unlocked 13260 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13261 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13262 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13263 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13264 } 13265 } catch (RemoteException e) { 13266 throw e.rethrowFromSystemServer(); 13267 } 13268 } 13269 13270 @Override 13271 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13272 int userId) { 13273 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13274 PackageSetting pkgSetting; 13275 final int uid = Binder.getCallingUid(); 13276 enforceCrossUserPermission(uid, userId, 13277 true /* requireFullPermission */, true /* checkShell */, 13278 "setApplicationHiddenSetting for user " + userId); 13279 13280 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13281 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13282 return false; 13283 } 13284 13285 long callingId = Binder.clearCallingIdentity(); 13286 try { 13287 boolean sendAdded = false; 13288 boolean sendRemoved = false; 13289 // writer 13290 synchronized (mPackages) { 13291 pkgSetting = mSettings.mPackages.get(packageName); 13292 if (pkgSetting == null) { 13293 return false; 13294 } 13295 // Do not allow "android" is being disabled 13296 if ("android".equals(packageName)) { 13297 Slog.w(TAG, "Cannot hide package: android"); 13298 return false; 13299 } 13300 // Cannot hide static shared libs as they are considered 13301 // a part of the using app (emulating static linking). Also 13302 // static libs are installed always on internal storage. 13303 PackageParser.Package pkg = mPackages.get(packageName); 13304 if (pkg != null && pkg.staticSharedLibName != null) { 13305 Slog.w(TAG, "Cannot hide package: " + packageName 13306 + " providing static shared library: " 13307 + pkg.staticSharedLibName); 13308 return false; 13309 } 13310 // Only allow protected packages to hide themselves. 13311 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13312 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13313 Slog.w(TAG, "Not hiding protected package: " + packageName); 13314 return false; 13315 } 13316 13317 if (pkgSetting.getHidden(userId) != hidden) { 13318 pkgSetting.setHidden(hidden, userId); 13319 mSettings.writePackageRestrictionsLPr(userId); 13320 if (hidden) { 13321 sendRemoved = true; 13322 } else { 13323 sendAdded = true; 13324 } 13325 } 13326 } 13327 if (sendAdded) { 13328 sendPackageAddedForUser(packageName, pkgSetting, userId); 13329 return true; 13330 } 13331 if (sendRemoved) { 13332 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13333 "hiding pkg"); 13334 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13335 return true; 13336 } 13337 } finally { 13338 Binder.restoreCallingIdentity(callingId); 13339 } 13340 return false; 13341 } 13342 13343 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13344 int userId) { 13345 final PackageRemovedInfo info = new PackageRemovedInfo(); 13346 info.removedPackage = packageName; 13347 info.removedUsers = new int[] {userId}; 13348 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13349 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13350 } 13351 13352 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13353 if (pkgList.length > 0) { 13354 Bundle extras = new Bundle(1); 13355 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13356 13357 sendPackageBroadcast( 13358 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13359 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13360 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13361 new int[] {userId}); 13362 } 13363 } 13364 13365 /** 13366 * Returns true if application is not found or there was an error. Otherwise it returns 13367 * the hidden state of the package for the given user. 13368 */ 13369 @Override 13370 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13371 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13372 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13373 true /* requireFullPermission */, false /* checkShell */, 13374 "getApplicationHidden for user " + userId); 13375 PackageSetting pkgSetting; 13376 long callingId = Binder.clearCallingIdentity(); 13377 try { 13378 // writer 13379 synchronized (mPackages) { 13380 pkgSetting = mSettings.mPackages.get(packageName); 13381 if (pkgSetting == null) { 13382 return true; 13383 } 13384 return pkgSetting.getHidden(userId); 13385 } 13386 } finally { 13387 Binder.restoreCallingIdentity(callingId); 13388 } 13389 } 13390 13391 /** 13392 * @hide 13393 */ 13394 @Override 13395 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13396 int installReason) { 13397 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13398 null); 13399 PackageSetting pkgSetting; 13400 final int uid = Binder.getCallingUid(); 13401 enforceCrossUserPermission(uid, userId, 13402 true /* requireFullPermission */, true /* checkShell */, 13403 "installExistingPackage for user " + userId); 13404 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13405 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13406 } 13407 13408 long callingId = Binder.clearCallingIdentity(); 13409 try { 13410 boolean installed = false; 13411 final boolean instantApp = 13412 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13413 final boolean fullApp = 13414 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13415 13416 // writer 13417 synchronized (mPackages) { 13418 pkgSetting = mSettings.mPackages.get(packageName); 13419 if (pkgSetting == null) { 13420 return PackageManager.INSTALL_FAILED_INVALID_URI; 13421 } 13422 if (!pkgSetting.getInstalled(userId)) { 13423 pkgSetting.setInstalled(true, userId); 13424 pkgSetting.setHidden(false, userId); 13425 pkgSetting.setInstallReason(installReason, userId); 13426 mSettings.writePackageRestrictionsLPr(userId); 13427 mSettings.writeKernelMappingLPr(pkgSetting); 13428 installed = true; 13429 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13430 // upgrade app from instant to full; we don't allow app downgrade 13431 installed = true; 13432 } 13433 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13434 } 13435 13436 if (installed) { 13437 if (pkgSetting.pkg != null) { 13438 synchronized (mInstallLock) { 13439 // We don't need to freeze for a brand new install 13440 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13441 } 13442 } 13443 sendPackageAddedForUser(packageName, pkgSetting, userId); 13444 synchronized (mPackages) { 13445 updateSequenceNumberLP(packageName, new int[]{ userId }); 13446 } 13447 } 13448 } finally { 13449 Binder.restoreCallingIdentity(callingId); 13450 } 13451 13452 return PackageManager.INSTALL_SUCCEEDED; 13453 } 13454 13455 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13456 boolean instantApp, boolean fullApp) { 13457 // no state specified; do nothing 13458 if (!instantApp && !fullApp) { 13459 return; 13460 } 13461 if (userId != UserHandle.USER_ALL) { 13462 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13463 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13464 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13465 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13466 } 13467 } else { 13468 for (int currentUserId : sUserManager.getUserIds()) { 13469 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13470 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13471 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13472 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13473 } 13474 } 13475 } 13476 } 13477 13478 boolean isUserRestricted(int userId, String restrictionKey) { 13479 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13480 if (restrictions.getBoolean(restrictionKey, false)) { 13481 Log.w(TAG, "User is restricted: " + restrictionKey); 13482 return true; 13483 } 13484 return false; 13485 } 13486 13487 @Override 13488 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13489 int userId) { 13490 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13491 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13492 true /* requireFullPermission */, true /* checkShell */, 13493 "setPackagesSuspended for user " + userId); 13494 13495 if (ArrayUtils.isEmpty(packageNames)) { 13496 return packageNames; 13497 } 13498 13499 // List of package names for whom the suspended state has changed. 13500 List<String> changedPackages = new ArrayList<>(packageNames.length); 13501 // List of package names for whom the suspended state is not set as requested in this 13502 // method. 13503 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13504 long callingId = Binder.clearCallingIdentity(); 13505 try { 13506 for (int i = 0; i < packageNames.length; i++) { 13507 String packageName = packageNames[i]; 13508 boolean changed = false; 13509 final int appId; 13510 synchronized (mPackages) { 13511 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13512 if (pkgSetting == null) { 13513 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13514 + "\". Skipping suspending/un-suspending."); 13515 unactionedPackages.add(packageName); 13516 continue; 13517 } 13518 appId = pkgSetting.appId; 13519 if (pkgSetting.getSuspended(userId) != suspended) { 13520 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13521 unactionedPackages.add(packageName); 13522 continue; 13523 } 13524 pkgSetting.setSuspended(suspended, userId); 13525 mSettings.writePackageRestrictionsLPr(userId); 13526 changed = true; 13527 changedPackages.add(packageName); 13528 } 13529 } 13530 13531 if (changed && suspended) { 13532 killApplication(packageName, UserHandle.getUid(userId, appId), 13533 "suspending package"); 13534 } 13535 } 13536 } finally { 13537 Binder.restoreCallingIdentity(callingId); 13538 } 13539 13540 if (!changedPackages.isEmpty()) { 13541 sendPackagesSuspendedForUser(changedPackages.toArray( 13542 new String[changedPackages.size()]), userId, suspended); 13543 } 13544 13545 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13546 } 13547 13548 @Override 13549 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13550 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13551 true /* requireFullPermission */, false /* checkShell */, 13552 "isPackageSuspendedForUser for user " + userId); 13553 synchronized (mPackages) { 13554 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13555 if (pkgSetting == null) { 13556 throw new IllegalArgumentException("Unknown target package: " + packageName); 13557 } 13558 return pkgSetting.getSuspended(userId); 13559 } 13560 } 13561 13562 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13563 if (isPackageDeviceAdmin(packageName, userId)) { 13564 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13565 + "\": has an active device admin"); 13566 return false; 13567 } 13568 13569 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13570 if (packageName.equals(activeLauncherPackageName)) { 13571 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13572 + "\": contains the active launcher"); 13573 return false; 13574 } 13575 13576 if (packageName.equals(mRequiredInstallerPackage)) { 13577 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13578 + "\": required for package installation"); 13579 return false; 13580 } 13581 13582 if (packageName.equals(mRequiredUninstallerPackage)) { 13583 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13584 + "\": required for package uninstallation"); 13585 return false; 13586 } 13587 13588 if (packageName.equals(mRequiredVerifierPackage)) { 13589 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13590 + "\": required for package verification"); 13591 return false; 13592 } 13593 13594 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13595 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13596 + "\": is the default dialer"); 13597 return false; 13598 } 13599 13600 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13601 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13602 + "\": protected package"); 13603 return false; 13604 } 13605 13606 // Cannot suspend static shared libs as they are considered 13607 // a part of the using app (emulating static linking). Also 13608 // static libs are installed always on internal storage. 13609 PackageParser.Package pkg = mPackages.get(packageName); 13610 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13611 Slog.w(TAG, "Cannot suspend package: " + packageName 13612 + " providing static shared library: " 13613 + pkg.staticSharedLibName); 13614 return false; 13615 } 13616 13617 return true; 13618 } 13619 13620 private String getActiveLauncherPackageName(int userId) { 13621 Intent intent = new Intent(Intent.ACTION_MAIN); 13622 intent.addCategory(Intent.CATEGORY_HOME); 13623 ResolveInfo resolveInfo = resolveIntent( 13624 intent, 13625 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13626 PackageManager.MATCH_DEFAULT_ONLY, 13627 userId); 13628 13629 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13630 } 13631 13632 private String getDefaultDialerPackageName(int userId) { 13633 synchronized (mPackages) { 13634 return mSettings.getDefaultDialerPackageNameLPw(userId); 13635 } 13636 } 13637 13638 @Override 13639 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13640 mContext.enforceCallingOrSelfPermission( 13641 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13642 "Only package verification agents can verify applications"); 13643 13644 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13645 final PackageVerificationResponse response = new PackageVerificationResponse( 13646 verificationCode, Binder.getCallingUid()); 13647 msg.arg1 = id; 13648 msg.obj = response; 13649 mHandler.sendMessage(msg); 13650 } 13651 13652 @Override 13653 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13654 long millisecondsToDelay) { 13655 mContext.enforceCallingOrSelfPermission( 13656 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13657 "Only package verification agents can extend verification timeouts"); 13658 13659 final PackageVerificationState state = mPendingVerification.get(id); 13660 final PackageVerificationResponse response = new PackageVerificationResponse( 13661 verificationCodeAtTimeout, Binder.getCallingUid()); 13662 13663 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13664 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13665 } 13666 if (millisecondsToDelay < 0) { 13667 millisecondsToDelay = 0; 13668 } 13669 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13670 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13671 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13672 } 13673 13674 if ((state != null) && !state.timeoutExtended()) { 13675 state.extendTimeout(); 13676 13677 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13678 msg.arg1 = id; 13679 msg.obj = response; 13680 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13681 } 13682 } 13683 13684 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13685 int verificationCode, UserHandle user) { 13686 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13687 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13688 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13689 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13690 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13691 13692 mContext.sendBroadcastAsUser(intent, user, 13693 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13694 } 13695 13696 private ComponentName matchComponentForVerifier(String packageName, 13697 List<ResolveInfo> receivers) { 13698 ActivityInfo targetReceiver = null; 13699 13700 final int NR = receivers.size(); 13701 for (int i = 0; i < NR; i++) { 13702 final ResolveInfo info = receivers.get(i); 13703 if (info.activityInfo == null) { 13704 continue; 13705 } 13706 13707 if (packageName.equals(info.activityInfo.packageName)) { 13708 targetReceiver = info.activityInfo; 13709 break; 13710 } 13711 } 13712 13713 if (targetReceiver == null) { 13714 return null; 13715 } 13716 13717 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13718 } 13719 13720 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13721 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13722 if (pkgInfo.verifiers.length == 0) { 13723 return null; 13724 } 13725 13726 final int N = pkgInfo.verifiers.length; 13727 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13728 for (int i = 0; i < N; i++) { 13729 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13730 13731 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13732 receivers); 13733 if (comp == null) { 13734 continue; 13735 } 13736 13737 final int verifierUid = getUidForVerifier(verifierInfo); 13738 if (verifierUid == -1) { 13739 continue; 13740 } 13741 13742 if (DEBUG_VERIFY) { 13743 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13744 + " with the correct signature"); 13745 } 13746 sufficientVerifiers.add(comp); 13747 verificationState.addSufficientVerifier(verifierUid); 13748 } 13749 13750 return sufficientVerifiers; 13751 } 13752 13753 private int getUidForVerifier(VerifierInfo verifierInfo) { 13754 synchronized (mPackages) { 13755 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13756 if (pkg == null) { 13757 return -1; 13758 } else if (pkg.mSignatures.length != 1) { 13759 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13760 + " has more than one signature; ignoring"); 13761 return -1; 13762 } 13763 13764 /* 13765 * If the public key of the package's signature does not match 13766 * our expected public key, then this is a different package and 13767 * we should skip. 13768 */ 13769 13770 final byte[] expectedPublicKey; 13771 try { 13772 final Signature verifierSig = pkg.mSignatures[0]; 13773 final PublicKey publicKey = verifierSig.getPublicKey(); 13774 expectedPublicKey = publicKey.getEncoded(); 13775 } catch (CertificateException e) { 13776 return -1; 13777 } 13778 13779 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13780 13781 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13782 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13783 + " does not have the expected public key; ignoring"); 13784 return -1; 13785 } 13786 13787 return pkg.applicationInfo.uid; 13788 } 13789 } 13790 13791 @Override 13792 public void finishPackageInstall(int token, boolean didLaunch) { 13793 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13794 13795 if (DEBUG_INSTALL) { 13796 Slog.v(TAG, "BM finishing package install for " + token); 13797 } 13798 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13799 13800 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13801 mHandler.sendMessage(msg); 13802 } 13803 13804 /** 13805 * Get the verification agent timeout. 13806 * 13807 * @return verification timeout in milliseconds 13808 */ 13809 private long getVerificationTimeout() { 13810 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13811 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13812 DEFAULT_VERIFICATION_TIMEOUT); 13813 } 13814 13815 /** 13816 * Get the default verification agent response code. 13817 * 13818 * @return default verification response code 13819 */ 13820 private int getDefaultVerificationResponse() { 13821 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13822 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13823 DEFAULT_VERIFICATION_RESPONSE); 13824 } 13825 13826 /** 13827 * Check whether or not package verification has been enabled. 13828 * 13829 * @return true if verification should be performed 13830 */ 13831 private boolean isVerificationEnabled(int userId, int installFlags) { 13832 if (!DEFAULT_VERIFY_ENABLE) { 13833 return false; 13834 } 13835 13836 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13837 13838 // Check if installing from ADB 13839 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13840 // Do not run verification in a test harness environment 13841 if (ActivityManager.isRunningInTestHarness()) { 13842 return false; 13843 } 13844 if (ensureVerifyAppsEnabled) { 13845 return true; 13846 } 13847 // Check if the developer does not want package verification for ADB installs 13848 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13849 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13850 return false; 13851 } 13852 } 13853 13854 if (ensureVerifyAppsEnabled) { 13855 return true; 13856 } 13857 13858 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13859 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13860 } 13861 13862 @Override 13863 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13864 throws RemoteException { 13865 mContext.enforceCallingOrSelfPermission( 13866 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13867 "Only intentfilter verification agents can verify applications"); 13868 13869 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13870 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13871 Binder.getCallingUid(), verificationCode, failedDomains); 13872 msg.arg1 = id; 13873 msg.obj = response; 13874 mHandler.sendMessage(msg); 13875 } 13876 13877 @Override 13878 public int getIntentVerificationStatus(String packageName, int userId) { 13879 synchronized (mPackages) { 13880 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13881 } 13882 } 13883 13884 @Override 13885 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13886 mContext.enforceCallingOrSelfPermission( 13887 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13888 13889 boolean result = false; 13890 synchronized (mPackages) { 13891 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13892 } 13893 if (result) { 13894 scheduleWritePackageRestrictionsLocked(userId); 13895 } 13896 return result; 13897 } 13898 13899 @Override 13900 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13901 String packageName) { 13902 synchronized (mPackages) { 13903 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13904 } 13905 } 13906 13907 @Override 13908 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13909 if (TextUtils.isEmpty(packageName)) { 13910 return ParceledListSlice.emptyList(); 13911 } 13912 synchronized (mPackages) { 13913 PackageParser.Package pkg = mPackages.get(packageName); 13914 if (pkg == null || pkg.activities == null) { 13915 return ParceledListSlice.emptyList(); 13916 } 13917 final int count = pkg.activities.size(); 13918 ArrayList<IntentFilter> result = new ArrayList<>(); 13919 for (int n=0; n<count; n++) { 13920 PackageParser.Activity activity = pkg.activities.get(n); 13921 if (activity.intents != null && activity.intents.size() > 0) { 13922 result.addAll(activity.intents); 13923 } 13924 } 13925 return new ParceledListSlice<>(result); 13926 } 13927 } 13928 13929 @Override 13930 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13931 mContext.enforceCallingOrSelfPermission( 13932 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13933 13934 synchronized (mPackages) { 13935 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13936 if (packageName != null) { 13937 result |= updateIntentVerificationStatus(packageName, 13938 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13939 userId); 13940 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13941 packageName, userId); 13942 } 13943 return result; 13944 } 13945 } 13946 13947 @Override 13948 public String getDefaultBrowserPackageName(int userId) { 13949 synchronized (mPackages) { 13950 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13951 } 13952 } 13953 13954 /** 13955 * Get the "allow unknown sources" setting. 13956 * 13957 * @return the current "allow unknown sources" setting 13958 */ 13959 private int getUnknownSourcesSettings() { 13960 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13961 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13962 -1); 13963 } 13964 13965 @Override 13966 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13967 final int uid = Binder.getCallingUid(); 13968 // writer 13969 synchronized (mPackages) { 13970 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13971 if (targetPackageSetting == null) { 13972 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13973 } 13974 13975 PackageSetting installerPackageSetting; 13976 if (installerPackageName != null) { 13977 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13978 if (installerPackageSetting == null) { 13979 throw new IllegalArgumentException("Unknown installer package: " 13980 + installerPackageName); 13981 } 13982 } else { 13983 installerPackageSetting = null; 13984 } 13985 13986 Signature[] callerSignature; 13987 Object obj = mSettings.getUserIdLPr(uid); 13988 if (obj != null) { 13989 if (obj instanceof SharedUserSetting) { 13990 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13991 } else if (obj instanceof PackageSetting) { 13992 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13993 } else { 13994 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13995 } 13996 } else { 13997 throw new SecurityException("Unknown calling UID: " + uid); 13998 } 13999 14000 // Verify: can't set installerPackageName to a package that is 14001 // not signed with the same cert as the caller. 14002 if (installerPackageSetting != null) { 14003 if (compareSignatures(callerSignature, 14004 installerPackageSetting.signatures.mSignatures) 14005 != PackageManager.SIGNATURE_MATCH) { 14006 throw new SecurityException( 14007 "Caller does not have same cert as new installer package " 14008 + installerPackageName); 14009 } 14010 } 14011 14012 // Verify: if target already has an installer package, it must 14013 // be signed with the same cert as the caller. 14014 if (targetPackageSetting.installerPackageName != null) { 14015 PackageSetting setting = mSettings.mPackages.get( 14016 targetPackageSetting.installerPackageName); 14017 // If the currently set package isn't valid, then it's always 14018 // okay to change it. 14019 if (setting != null) { 14020 if (compareSignatures(callerSignature, 14021 setting.signatures.mSignatures) 14022 != PackageManager.SIGNATURE_MATCH) { 14023 throw new SecurityException( 14024 "Caller does not have same cert as old installer package " 14025 + targetPackageSetting.installerPackageName); 14026 } 14027 } 14028 } 14029 14030 // Okay! 14031 targetPackageSetting.installerPackageName = installerPackageName; 14032 if (installerPackageName != null) { 14033 mSettings.mInstallerPackages.add(installerPackageName); 14034 } 14035 scheduleWriteSettingsLocked(); 14036 } 14037 } 14038 14039 @Override 14040 public void setApplicationCategoryHint(String packageName, int categoryHint, 14041 String callerPackageName) { 14042 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14043 callerPackageName); 14044 synchronized (mPackages) { 14045 PackageSetting ps = mSettings.mPackages.get(packageName); 14046 if (ps == null) { 14047 throw new IllegalArgumentException("Unknown target package " + packageName); 14048 } 14049 14050 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14051 throw new IllegalArgumentException("Calling package " + callerPackageName 14052 + " is not installer for " + packageName); 14053 } 14054 14055 if (ps.categoryHint != categoryHint) { 14056 ps.categoryHint = categoryHint; 14057 scheduleWriteSettingsLocked(); 14058 } 14059 } 14060 } 14061 14062 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14063 // Queue up an async operation since the package installation may take a little while. 14064 mHandler.post(new Runnable() { 14065 public void run() { 14066 mHandler.removeCallbacks(this); 14067 // Result object to be returned 14068 PackageInstalledInfo res = new PackageInstalledInfo(); 14069 res.setReturnCode(currentStatus); 14070 res.uid = -1; 14071 res.pkg = null; 14072 res.removedInfo = null; 14073 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14074 args.doPreInstall(res.returnCode); 14075 synchronized (mInstallLock) { 14076 installPackageTracedLI(args, res); 14077 } 14078 args.doPostInstall(res.returnCode, res.uid); 14079 } 14080 14081 // A restore should be performed at this point if (a) the install 14082 // succeeded, (b) the operation is not an update, and (c) the new 14083 // package has not opted out of backup participation. 14084 final boolean update = res.removedInfo != null 14085 && res.removedInfo.removedPackage != null; 14086 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14087 boolean doRestore = !update 14088 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14089 14090 // Set up the post-install work request bookkeeping. This will be used 14091 // and cleaned up by the post-install event handling regardless of whether 14092 // there's a restore pass performed. Token values are >= 1. 14093 int token; 14094 if (mNextInstallToken < 0) mNextInstallToken = 1; 14095 token = mNextInstallToken++; 14096 14097 PostInstallData data = new PostInstallData(args, res); 14098 mRunningInstalls.put(token, data); 14099 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14100 14101 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14102 // Pass responsibility to the Backup Manager. It will perform a 14103 // restore if appropriate, then pass responsibility back to the 14104 // Package Manager to run the post-install observer callbacks 14105 // and broadcasts. 14106 IBackupManager bm = IBackupManager.Stub.asInterface( 14107 ServiceManager.getService(Context.BACKUP_SERVICE)); 14108 if (bm != null) { 14109 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14110 + " to BM for possible restore"); 14111 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14112 try { 14113 // TODO: http://b/22388012 14114 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14115 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14116 } else { 14117 doRestore = false; 14118 } 14119 } catch (RemoteException e) { 14120 // can't happen; the backup manager is local 14121 } catch (Exception e) { 14122 Slog.e(TAG, "Exception trying to enqueue restore", e); 14123 doRestore = false; 14124 } 14125 } else { 14126 Slog.e(TAG, "Backup Manager not found!"); 14127 doRestore = false; 14128 } 14129 } 14130 14131 if (!doRestore) { 14132 // No restore possible, or the Backup Manager was mysteriously not 14133 // available -- just fire the post-install work request directly. 14134 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14135 14136 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14137 14138 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14139 mHandler.sendMessage(msg); 14140 } 14141 } 14142 }); 14143 } 14144 14145 /** 14146 * Callback from PackageSettings whenever an app is first transitioned out of the 14147 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14148 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14149 * here whether the app is the target of an ongoing install, and only send the 14150 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14151 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14152 * handling. 14153 */ 14154 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14155 // Serialize this with the rest of the install-process message chain. In the 14156 // restore-at-install case, this Runnable will necessarily run before the 14157 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14158 // are coherent. In the non-restore case, the app has already completed install 14159 // and been launched through some other means, so it is not in a problematic 14160 // state for observers to see the FIRST_LAUNCH signal. 14161 mHandler.post(new Runnable() { 14162 @Override 14163 public void run() { 14164 for (int i = 0; i < mRunningInstalls.size(); i++) { 14165 final PostInstallData data = mRunningInstalls.valueAt(i); 14166 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14167 continue; 14168 } 14169 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14170 // right package; but is it for the right user? 14171 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14172 if (userId == data.res.newUsers[uIndex]) { 14173 if (DEBUG_BACKUP) { 14174 Slog.i(TAG, "Package " + pkgName 14175 + " being restored so deferring FIRST_LAUNCH"); 14176 } 14177 return; 14178 } 14179 } 14180 } 14181 } 14182 // didn't find it, so not being restored 14183 if (DEBUG_BACKUP) { 14184 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14185 } 14186 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14187 } 14188 }); 14189 } 14190 14191 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14192 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14193 installerPkg, null, userIds); 14194 } 14195 14196 private abstract class HandlerParams { 14197 private static final int MAX_RETRIES = 4; 14198 14199 /** 14200 * Number of times startCopy() has been attempted and had a non-fatal 14201 * error. 14202 */ 14203 private int mRetries = 0; 14204 14205 /** User handle for the user requesting the information or installation. */ 14206 private final UserHandle mUser; 14207 String traceMethod; 14208 int traceCookie; 14209 14210 HandlerParams(UserHandle user) { 14211 mUser = user; 14212 } 14213 14214 UserHandle getUser() { 14215 return mUser; 14216 } 14217 14218 HandlerParams setTraceMethod(String traceMethod) { 14219 this.traceMethod = traceMethod; 14220 return this; 14221 } 14222 14223 HandlerParams setTraceCookie(int traceCookie) { 14224 this.traceCookie = traceCookie; 14225 return this; 14226 } 14227 14228 final boolean startCopy() { 14229 boolean res; 14230 try { 14231 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14232 14233 if (++mRetries > MAX_RETRIES) { 14234 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14235 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14236 handleServiceError(); 14237 return false; 14238 } else { 14239 handleStartCopy(); 14240 res = true; 14241 } 14242 } catch (RemoteException e) { 14243 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14244 mHandler.sendEmptyMessage(MCS_RECONNECT); 14245 res = false; 14246 } 14247 handleReturnCode(); 14248 return res; 14249 } 14250 14251 final void serviceError() { 14252 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14253 handleServiceError(); 14254 handleReturnCode(); 14255 } 14256 14257 abstract void handleStartCopy() throws RemoteException; 14258 abstract void handleServiceError(); 14259 abstract void handleReturnCode(); 14260 } 14261 14262 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14263 for (File path : paths) { 14264 try { 14265 mcs.clearDirectory(path.getAbsolutePath()); 14266 } catch (RemoteException e) { 14267 } 14268 } 14269 } 14270 14271 static class OriginInfo { 14272 /** 14273 * Location where install is coming from, before it has been 14274 * copied/renamed into place. This could be a single monolithic APK 14275 * file, or a cluster directory. This location may be untrusted. 14276 */ 14277 final File file; 14278 final String cid; 14279 14280 /** 14281 * Flag indicating that {@link #file} or {@link #cid} has already been 14282 * staged, meaning downstream users don't need to defensively copy the 14283 * contents. 14284 */ 14285 final boolean staged; 14286 14287 /** 14288 * Flag indicating that {@link #file} or {@link #cid} is an already 14289 * installed app that is being moved. 14290 */ 14291 final boolean existing; 14292 14293 final String resolvedPath; 14294 final File resolvedFile; 14295 14296 static OriginInfo fromNothing() { 14297 return new OriginInfo(null, null, false, false); 14298 } 14299 14300 static OriginInfo fromUntrustedFile(File file) { 14301 return new OriginInfo(file, null, false, false); 14302 } 14303 14304 static OriginInfo fromExistingFile(File file) { 14305 return new OriginInfo(file, null, false, true); 14306 } 14307 14308 static OriginInfo fromStagedFile(File file) { 14309 return new OriginInfo(file, null, true, false); 14310 } 14311 14312 static OriginInfo fromStagedContainer(String cid) { 14313 return new OriginInfo(null, cid, true, false); 14314 } 14315 14316 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14317 this.file = file; 14318 this.cid = cid; 14319 this.staged = staged; 14320 this.existing = existing; 14321 14322 if (cid != null) { 14323 resolvedPath = PackageHelper.getSdDir(cid); 14324 resolvedFile = new File(resolvedPath); 14325 } else if (file != null) { 14326 resolvedPath = file.getAbsolutePath(); 14327 resolvedFile = file; 14328 } else { 14329 resolvedPath = null; 14330 resolvedFile = null; 14331 } 14332 } 14333 } 14334 14335 static class MoveInfo { 14336 final int moveId; 14337 final String fromUuid; 14338 final String toUuid; 14339 final String packageName; 14340 final String dataAppName; 14341 final int appId; 14342 final String seinfo; 14343 final int targetSdkVersion; 14344 14345 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14346 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14347 this.moveId = moveId; 14348 this.fromUuid = fromUuid; 14349 this.toUuid = toUuid; 14350 this.packageName = packageName; 14351 this.dataAppName = dataAppName; 14352 this.appId = appId; 14353 this.seinfo = seinfo; 14354 this.targetSdkVersion = targetSdkVersion; 14355 } 14356 } 14357 14358 static class VerificationInfo { 14359 /** A constant used to indicate that a uid value is not present. */ 14360 public static final int NO_UID = -1; 14361 14362 /** URI referencing where the package was downloaded from. */ 14363 final Uri originatingUri; 14364 14365 /** HTTP referrer URI associated with the originatingURI. */ 14366 final Uri referrer; 14367 14368 /** UID of the application that the install request originated from. */ 14369 final int originatingUid; 14370 14371 /** UID of application requesting the install */ 14372 final int installerUid; 14373 14374 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14375 this.originatingUri = originatingUri; 14376 this.referrer = referrer; 14377 this.originatingUid = originatingUid; 14378 this.installerUid = installerUid; 14379 } 14380 } 14381 14382 class InstallParams extends HandlerParams { 14383 final OriginInfo origin; 14384 final MoveInfo move; 14385 final IPackageInstallObserver2 observer; 14386 int installFlags; 14387 final String installerPackageName; 14388 final String volumeUuid; 14389 private InstallArgs mArgs; 14390 private int mRet; 14391 final String packageAbiOverride; 14392 final String[] grantedRuntimePermissions; 14393 final VerificationInfo verificationInfo; 14394 final Certificate[][] certificates; 14395 final int installReason; 14396 14397 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14398 int installFlags, String installerPackageName, String volumeUuid, 14399 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14400 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14401 super(user); 14402 this.origin = origin; 14403 this.move = move; 14404 this.observer = observer; 14405 this.installFlags = installFlags; 14406 this.installerPackageName = installerPackageName; 14407 this.volumeUuid = volumeUuid; 14408 this.verificationInfo = verificationInfo; 14409 this.packageAbiOverride = packageAbiOverride; 14410 this.grantedRuntimePermissions = grantedPermissions; 14411 this.certificates = certificates; 14412 this.installReason = installReason; 14413 } 14414 14415 @Override 14416 public String toString() { 14417 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14418 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14419 } 14420 14421 private int installLocationPolicy(PackageInfoLite pkgLite) { 14422 String packageName = pkgLite.packageName; 14423 int installLocation = pkgLite.installLocation; 14424 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14425 // reader 14426 synchronized (mPackages) { 14427 // Currently installed package which the new package is attempting to replace or 14428 // null if no such package is installed. 14429 PackageParser.Package installedPkg = mPackages.get(packageName); 14430 // Package which currently owns the data which the new package will own if installed. 14431 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14432 // will be null whereas dataOwnerPkg will contain information about the package 14433 // which was uninstalled while keeping its data. 14434 PackageParser.Package dataOwnerPkg = installedPkg; 14435 if (dataOwnerPkg == null) { 14436 PackageSetting ps = mSettings.mPackages.get(packageName); 14437 if (ps != null) { 14438 dataOwnerPkg = ps.pkg; 14439 } 14440 } 14441 14442 if (dataOwnerPkg != null) { 14443 // If installed, the package will get access to data left on the device by its 14444 // predecessor. As a security measure, this is permited only if this is not a 14445 // version downgrade or if the predecessor package is marked as debuggable and 14446 // a downgrade is explicitly requested. 14447 // 14448 // On debuggable platform builds, downgrades are permitted even for 14449 // non-debuggable packages to make testing easier. Debuggable platform builds do 14450 // not offer security guarantees and thus it's OK to disable some security 14451 // mechanisms to make debugging/testing easier on those builds. However, even on 14452 // debuggable builds downgrades of packages are permitted only if requested via 14453 // installFlags. This is because we aim to keep the behavior of debuggable 14454 // platform builds as close as possible to the behavior of non-debuggable 14455 // platform builds. 14456 final boolean downgradeRequested = 14457 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14458 final boolean packageDebuggable = 14459 (dataOwnerPkg.applicationInfo.flags 14460 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14461 final boolean downgradePermitted = 14462 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14463 if (!downgradePermitted) { 14464 try { 14465 checkDowngrade(dataOwnerPkg, pkgLite); 14466 } catch (PackageManagerException e) { 14467 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14468 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14469 } 14470 } 14471 } 14472 14473 if (installedPkg != null) { 14474 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14475 // Check for updated system application. 14476 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14477 if (onSd) { 14478 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14479 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14480 } 14481 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14482 } else { 14483 if (onSd) { 14484 // Install flag overrides everything. 14485 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14486 } 14487 // If current upgrade specifies particular preference 14488 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14489 // Application explicitly specified internal. 14490 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14491 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14492 // App explictly prefers external. Let policy decide 14493 } else { 14494 // Prefer previous location 14495 if (isExternal(installedPkg)) { 14496 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14497 } 14498 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14499 } 14500 } 14501 } else { 14502 // Invalid install. Return error code 14503 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14504 } 14505 } 14506 } 14507 // All the special cases have been taken care of. 14508 // Return result based on recommended install location. 14509 if (onSd) { 14510 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14511 } 14512 return pkgLite.recommendedInstallLocation; 14513 } 14514 14515 /* 14516 * Invoke remote method to get package information and install 14517 * location values. Override install location based on default 14518 * policy if needed and then create install arguments based 14519 * on the install location. 14520 */ 14521 public void handleStartCopy() throws RemoteException { 14522 int ret = PackageManager.INSTALL_SUCCEEDED; 14523 14524 // If we're already staged, we've firmly committed to an install location 14525 if (origin.staged) { 14526 if (origin.file != null) { 14527 installFlags |= PackageManager.INSTALL_INTERNAL; 14528 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14529 } else if (origin.cid != null) { 14530 installFlags |= PackageManager.INSTALL_EXTERNAL; 14531 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14532 } else { 14533 throw new IllegalStateException("Invalid stage location"); 14534 } 14535 } 14536 14537 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14538 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14539 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14540 PackageInfoLite pkgLite = null; 14541 14542 if (onInt && onSd) { 14543 // Check if both bits are set. 14544 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14545 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14546 } else if (onSd && ephemeral) { 14547 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14548 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14549 } else { 14550 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14551 packageAbiOverride); 14552 14553 if (DEBUG_EPHEMERAL && ephemeral) { 14554 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14555 } 14556 14557 /* 14558 * If we have too little free space, try to free cache 14559 * before giving up. 14560 */ 14561 if (!origin.staged && pkgLite.recommendedInstallLocation 14562 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14563 // TODO: focus freeing disk space on the target device 14564 final StorageManager storage = StorageManager.from(mContext); 14565 final long lowThreshold = storage.getStorageLowBytes( 14566 Environment.getDataDirectory()); 14567 14568 final long sizeBytes = mContainerService.calculateInstalledSize( 14569 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14570 14571 try { 14572 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14573 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14574 installFlags, packageAbiOverride); 14575 } catch (InstallerException e) { 14576 Slog.w(TAG, "Failed to free cache", e); 14577 } 14578 14579 /* 14580 * The cache free must have deleted the file we 14581 * downloaded to install. 14582 * 14583 * TODO: fix the "freeCache" call to not delete 14584 * the file we care about. 14585 */ 14586 if (pkgLite.recommendedInstallLocation 14587 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14588 pkgLite.recommendedInstallLocation 14589 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14590 } 14591 } 14592 } 14593 14594 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14595 int loc = pkgLite.recommendedInstallLocation; 14596 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14597 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14598 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14599 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14600 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14601 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14602 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14603 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14604 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14605 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14606 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14607 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14608 } else { 14609 // Override with defaults if needed. 14610 loc = installLocationPolicy(pkgLite); 14611 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14612 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14613 } else if (!onSd && !onInt) { 14614 // Override install location with flags 14615 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14616 // Set the flag to install on external media. 14617 installFlags |= PackageManager.INSTALL_EXTERNAL; 14618 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14619 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14620 if (DEBUG_EPHEMERAL) { 14621 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14622 } 14623 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14624 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14625 |PackageManager.INSTALL_INTERNAL); 14626 } else { 14627 // Make sure the flag for installing on external 14628 // media is unset 14629 installFlags |= PackageManager.INSTALL_INTERNAL; 14630 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14631 } 14632 } 14633 } 14634 } 14635 14636 final InstallArgs args = createInstallArgs(this); 14637 mArgs = args; 14638 14639 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14640 // TODO: http://b/22976637 14641 // Apps installed for "all" users use the device owner to verify the app 14642 UserHandle verifierUser = getUser(); 14643 if (verifierUser == UserHandle.ALL) { 14644 verifierUser = UserHandle.SYSTEM; 14645 } 14646 14647 /* 14648 * Determine if we have any installed package verifiers. If we 14649 * do, then we'll defer to them to verify the packages. 14650 */ 14651 final int requiredUid = mRequiredVerifierPackage == null ? -1 14652 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14653 verifierUser.getIdentifier()); 14654 if (!origin.existing && requiredUid != -1 14655 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14656 final Intent verification = new Intent( 14657 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14658 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14659 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14660 PACKAGE_MIME_TYPE); 14661 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14662 14663 // Query all live verifiers based on current user state 14664 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14665 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14666 14667 if (DEBUG_VERIFY) { 14668 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14669 + verification.toString() + " with " + pkgLite.verifiers.length 14670 + " optional verifiers"); 14671 } 14672 14673 final int verificationId = mPendingVerificationToken++; 14674 14675 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14676 14677 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14678 installerPackageName); 14679 14680 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14681 installFlags); 14682 14683 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14684 pkgLite.packageName); 14685 14686 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14687 pkgLite.versionCode); 14688 14689 if (verificationInfo != null) { 14690 if (verificationInfo.originatingUri != null) { 14691 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14692 verificationInfo.originatingUri); 14693 } 14694 if (verificationInfo.referrer != null) { 14695 verification.putExtra(Intent.EXTRA_REFERRER, 14696 verificationInfo.referrer); 14697 } 14698 if (verificationInfo.originatingUid >= 0) { 14699 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14700 verificationInfo.originatingUid); 14701 } 14702 if (verificationInfo.installerUid >= 0) { 14703 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14704 verificationInfo.installerUid); 14705 } 14706 } 14707 14708 final PackageVerificationState verificationState = new PackageVerificationState( 14709 requiredUid, args); 14710 14711 mPendingVerification.append(verificationId, verificationState); 14712 14713 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14714 receivers, verificationState); 14715 14716 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14717 final long idleDuration = getVerificationTimeout(); 14718 14719 /* 14720 * If any sufficient verifiers were listed in the package 14721 * manifest, attempt to ask them. 14722 */ 14723 if (sufficientVerifiers != null) { 14724 final int N = sufficientVerifiers.size(); 14725 if (N == 0) { 14726 Slog.i(TAG, "Additional verifiers required, but none installed."); 14727 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14728 } else { 14729 for (int i = 0; i < N; i++) { 14730 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14731 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14732 verifierComponent.getPackageName(), idleDuration, 14733 verifierUser.getIdentifier(), false, "package verifier"); 14734 14735 final Intent sufficientIntent = new Intent(verification); 14736 sufficientIntent.setComponent(verifierComponent); 14737 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14738 } 14739 } 14740 } 14741 14742 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14743 mRequiredVerifierPackage, receivers); 14744 if (ret == PackageManager.INSTALL_SUCCEEDED 14745 && mRequiredVerifierPackage != null) { 14746 Trace.asyncTraceBegin( 14747 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14748 /* 14749 * Send the intent to the required verification agent, 14750 * but only start the verification timeout after the 14751 * target BroadcastReceivers have run. 14752 */ 14753 verification.setComponent(requiredVerifierComponent); 14754 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14755 mRequiredVerifierPackage, idleDuration, 14756 verifierUser.getIdentifier(), false, "package verifier"); 14757 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14758 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14759 new BroadcastReceiver() { 14760 @Override 14761 public void onReceive(Context context, Intent intent) { 14762 final Message msg = mHandler 14763 .obtainMessage(CHECK_PENDING_VERIFICATION); 14764 msg.arg1 = verificationId; 14765 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14766 } 14767 }, null, 0, null, null); 14768 14769 /* 14770 * We don't want the copy to proceed until verification 14771 * succeeds, so null out this field. 14772 */ 14773 mArgs = null; 14774 } 14775 } else { 14776 /* 14777 * No package verification is enabled, so immediately start 14778 * the remote call to initiate copy using temporary file. 14779 */ 14780 ret = args.copyApk(mContainerService, true); 14781 } 14782 } 14783 14784 mRet = ret; 14785 } 14786 14787 @Override 14788 void handleReturnCode() { 14789 // If mArgs is null, then MCS couldn't be reached. When it 14790 // reconnects, it will try again to install. At that point, this 14791 // will succeed. 14792 if (mArgs != null) { 14793 processPendingInstall(mArgs, mRet); 14794 } 14795 } 14796 14797 @Override 14798 void handleServiceError() { 14799 mArgs = createInstallArgs(this); 14800 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14801 } 14802 14803 public boolean isForwardLocked() { 14804 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14805 } 14806 } 14807 14808 /** 14809 * Used during creation of InstallArgs 14810 * 14811 * @param installFlags package installation flags 14812 * @return true if should be installed on external storage 14813 */ 14814 private static boolean installOnExternalAsec(int installFlags) { 14815 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14816 return false; 14817 } 14818 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14819 return true; 14820 } 14821 return false; 14822 } 14823 14824 /** 14825 * Used during creation of InstallArgs 14826 * 14827 * @param installFlags package installation flags 14828 * @return true if should be installed as forward locked 14829 */ 14830 private static boolean installForwardLocked(int installFlags) { 14831 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14832 } 14833 14834 private InstallArgs createInstallArgs(InstallParams params) { 14835 if (params.move != null) { 14836 return new MoveInstallArgs(params); 14837 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14838 return new AsecInstallArgs(params); 14839 } else { 14840 return new FileInstallArgs(params); 14841 } 14842 } 14843 14844 /** 14845 * Create args that describe an existing installed package. Typically used 14846 * when cleaning up old installs, or used as a move source. 14847 */ 14848 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14849 String resourcePath, String[] instructionSets) { 14850 final boolean isInAsec; 14851 if (installOnExternalAsec(installFlags)) { 14852 /* Apps on SD card are always in ASEC containers. */ 14853 isInAsec = true; 14854 } else if (installForwardLocked(installFlags) 14855 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14856 /* 14857 * Forward-locked apps are only in ASEC containers if they're the 14858 * new style 14859 */ 14860 isInAsec = true; 14861 } else { 14862 isInAsec = false; 14863 } 14864 14865 if (isInAsec) { 14866 return new AsecInstallArgs(codePath, instructionSets, 14867 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14868 } else { 14869 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14870 } 14871 } 14872 14873 static abstract class InstallArgs { 14874 /** @see InstallParams#origin */ 14875 final OriginInfo origin; 14876 /** @see InstallParams#move */ 14877 final MoveInfo move; 14878 14879 final IPackageInstallObserver2 observer; 14880 // Always refers to PackageManager flags only 14881 final int installFlags; 14882 final String installerPackageName; 14883 final String volumeUuid; 14884 final UserHandle user; 14885 final String abiOverride; 14886 final String[] installGrantPermissions; 14887 /** If non-null, drop an async trace when the install completes */ 14888 final String traceMethod; 14889 final int traceCookie; 14890 final Certificate[][] certificates; 14891 final int installReason; 14892 14893 // The list of instruction sets supported by this app. This is currently 14894 // only used during the rmdex() phase to clean up resources. We can get rid of this 14895 // if we move dex files under the common app path. 14896 /* nullable */ String[] instructionSets; 14897 14898 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14899 int installFlags, String installerPackageName, String volumeUuid, 14900 UserHandle user, String[] instructionSets, 14901 String abiOverride, String[] installGrantPermissions, 14902 String traceMethod, int traceCookie, Certificate[][] certificates, 14903 int installReason) { 14904 this.origin = origin; 14905 this.move = move; 14906 this.installFlags = installFlags; 14907 this.observer = observer; 14908 this.installerPackageName = installerPackageName; 14909 this.volumeUuid = volumeUuid; 14910 this.user = user; 14911 this.instructionSets = instructionSets; 14912 this.abiOverride = abiOverride; 14913 this.installGrantPermissions = installGrantPermissions; 14914 this.traceMethod = traceMethod; 14915 this.traceCookie = traceCookie; 14916 this.certificates = certificates; 14917 this.installReason = installReason; 14918 } 14919 14920 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14921 abstract int doPreInstall(int status); 14922 14923 /** 14924 * Rename package into final resting place. All paths on the given 14925 * scanned package should be updated to reflect the rename. 14926 */ 14927 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14928 abstract int doPostInstall(int status, int uid); 14929 14930 /** @see PackageSettingBase#codePathString */ 14931 abstract String getCodePath(); 14932 /** @see PackageSettingBase#resourcePathString */ 14933 abstract String getResourcePath(); 14934 14935 // Need installer lock especially for dex file removal. 14936 abstract void cleanUpResourcesLI(); 14937 abstract boolean doPostDeleteLI(boolean delete); 14938 14939 /** 14940 * Called before the source arguments are copied. This is used mostly 14941 * for MoveParams when it needs to read the source file to put it in the 14942 * destination. 14943 */ 14944 int doPreCopy() { 14945 return PackageManager.INSTALL_SUCCEEDED; 14946 } 14947 14948 /** 14949 * Called after the source arguments are copied. This is used mostly for 14950 * MoveParams when it needs to read the source file to put it in the 14951 * destination. 14952 */ 14953 int doPostCopy(int uid) { 14954 return PackageManager.INSTALL_SUCCEEDED; 14955 } 14956 14957 protected boolean isFwdLocked() { 14958 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14959 } 14960 14961 protected boolean isExternalAsec() { 14962 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14963 } 14964 14965 protected boolean isEphemeral() { 14966 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14967 } 14968 14969 UserHandle getUser() { 14970 return user; 14971 } 14972 } 14973 14974 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14975 if (!allCodePaths.isEmpty()) { 14976 if (instructionSets == null) { 14977 throw new IllegalStateException("instructionSet == null"); 14978 } 14979 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14980 for (String codePath : allCodePaths) { 14981 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14982 try { 14983 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14984 } catch (InstallerException ignored) { 14985 } 14986 } 14987 } 14988 } 14989 } 14990 14991 /** 14992 * Logic to handle installation of non-ASEC applications, including copying 14993 * and renaming logic. 14994 */ 14995 class FileInstallArgs extends InstallArgs { 14996 private File codeFile; 14997 private File resourceFile; 14998 14999 // Example topology: 15000 // /data/app/com.example/base.apk 15001 // /data/app/com.example/split_foo.apk 15002 // /data/app/com.example/lib/arm/libfoo.so 15003 // /data/app/com.example/lib/arm64/libfoo.so 15004 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15005 15006 /** New install */ 15007 FileInstallArgs(InstallParams params) { 15008 super(params.origin, params.move, params.observer, params.installFlags, 15009 params.installerPackageName, params.volumeUuid, 15010 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15011 params.grantedRuntimePermissions, 15012 params.traceMethod, params.traceCookie, params.certificates, 15013 params.installReason); 15014 if (isFwdLocked()) { 15015 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15016 } 15017 } 15018 15019 /** Existing install */ 15020 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15021 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15022 null, null, null, 0, null /*certificates*/, 15023 PackageManager.INSTALL_REASON_UNKNOWN); 15024 this.codeFile = (codePath != null) ? new File(codePath) : null; 15025 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15026 } 15027 15028 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15029 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15030 try { 15031 return doCopyApk(imcs, temp); 15032 } finally { 15033 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15034 } 15035 } 15036 15037 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15038 if (origin.staged) { 15039 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15040 codeFile = origin.file; 15041 resourceFile = origin.file; 15042 return PackageManager.INSTALL_SUCCEEDED; 15043 } 15044 15045 try { 15046 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15047 final File tempDir = 15048 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15049 codeFile = tempDir; 15050 resourceFile = tempDir; 15051 } catch (IOException e) { 15052 Slog.w(TAG, "Failed to create copy file: " + e); 15053 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15054 } 15055 15056 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15057 @Override 15058 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15059 if (!FileUtils.isValidExtFilename(name)) { 15060 throw new IllegalArgumentException("Invalid filename: " + name); 15061 } 15062 try { 15063 final File file = new File(codeFile, name); 15064 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15065 O_RDWR | O_CREAT, 0644); 15066 Os.chmod(file.getAbsolutePath(), 0644); 15067 return new ParcelFileDescriptor(fd); 15068 } catch (ErrnoException e) { 15069 throw new RemoteException("Failed to open: " + e.getMessage()); 15070 } 15071 } 15072 }; 15073 15074 int ret = PackageManager.INSTALL_SUCCEEDED; 15075 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15076 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15077 Slog.e(TAG, "Failed to copy package"); 15078 return ret; 15079 } 15080 15081 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15082 NativeLibraryHelper.Handle handle = null; 15083 try { 15084 handle = NativeLibraryHelper.Handle.create(codeFile); 15085 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15086 abiOverride); 15087 } catch (IOException e) { 15088 Slog.e(TAG, "Copying native libraries failed", e); 15089 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15090 } finally { 15091 IoUtils.closeQuietly(handle); 15092 } 15093 15094 return ret; 15095 } 15096 15097 int doPreInstall(int status) { 15098 if (status != PackageManager.INSTALL_SUCCEEDED) { 15099 cleanUp(); 15100 } 15101 return status; 15102 } 15103 15104 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15105 if (status != PackageManager.INSTALL_SUCCEEDED) { 15106 cleanUp(); 15107 return false; 15108 } 15109 15110 final File targetDir = codeFile.getParentFile(); 15111 final File beforeCodeFile = codeFile; 15112 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15113 15114 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15115 try { 15116 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15117 } catch (ErrnoException e) { 15118 Slog.w(TAG, "Failed to rename", e); 15119 return false; 15120 } 15121 15122 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15123 Slog.w(TAG, "Failed to restorecon"); 15124 return false; 15125 } 15126 15127 // Reflect the rename internally 15128 codeFile = afterCodeFile; 15129 resourceFile = afterCodeFile; 15130 15131 // Reflect the rename in scanned details 15132 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15133 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15134 afterCodeFile, pkg.baseCodePath)); 15135 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15136 afterCodeFile, pkg.splitCodePaths)); 15137 15138 // Reflect the rename in app info 15139 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15140 pkg.setApplicationInfoCodePath(pkg.codePath); 15141 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15142 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15143 pkg.setApplicationInfoResourcePath(pkg.codePath); 15144 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15145 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15146 15147 return true; 15148 } 15149 15150 int doPostInstall(int status, int uid) { 15151 if (status != PackageManager.INSTALL_SUCCEEDED) { 15152 cleanUp(); 15153 } 15154 return status; 15155 } 15156 15157 @Override 15158 String getCodePath() { 15159 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15160 } 15161 15162 @Override 15163 String getResourcePath() { 15164 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15165 } 15166 15167 private boolean cleanUp() { 15168 if (codeFile == null || !codeFile.exists()) { 15169 return false; 15170 } 15171 15172 removeCodePathLI(codeFile); 15173 15174 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15175 resourceFile.delete(); 15176 } 15177 15178 return true; 15179 } 15180 15181 void cleanUpResourcesLI() { 15182 // Try enumerating all code paths before deleting 15183 List<String> allCodePaths = Collections.EMPTY_LIST; 15184 if (codeFile != null && codeFile.exists()) { 15185 try { 15186 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15187 allCodePaths = pkg.getAllCodePaths(); 15188 } catch (PackageParserException e) { 15189 // Ignored; we tried our best 15190 } 15191 } 15192 15193 cleanUp(); 15194 removeDexFiles(allCodePaths, instructionSets); 15195 } 15196 15197 boolean doPostDeleteLI(boolean delete) { 15198 // XXX err, shouldn't we respect the delete flag? 15199 cleanUpResourcesLI(); 15200 return true; 15201 } 15202 } 15203 15204 private boolean isAsecExternal(String cid) { 15205 final String asecPath = PackageHelper.getSdFilesystem(cid); 15206 return !asecPath.startsWith(mAsecInternalPath); 15207 } 15208 15209 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15210 PackageManagerException { 15211 if (copyRet < 0) { 15212 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15213 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15214 throw new PackageManagerException(copyRet, message); 15215 } 15216 } 15217 } 15218 15219 /** 15220 * Extract the StorageManagerService "container ID" from the full code path of an 15221 * .apk. 15222 */ 15223 static String cidFromCodePath(String fullCodePath) { 15224 int eidx = fullCodePath.lastIndexOf("/"); 15225 String subStr1 = fullCodePath.substring(0, eidx); 15226 int sidx = subStr1.lastIndexOf("/"); 15227 return subStr1.substring(sidx+1, eidx); 15228 } 15229 15230 /** 15231 * Logic to handle installation of ASEC applications, including copying and 15232 * renaming logic. 15233 */ 15234 class AsecInstallArgs extends InstallArgs { 15235 static final String RES_FILE_NAME = "pkg.apk"; 15236 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15237 15238 String cid; 15239 String packagePath; 15240 String resourcePath; 15241 15242 /** New install */ 15243 AsecInstallArgs(InstallParams params) { 15244 super(params.origin, params.move, params.observer, params.installFlags, 15245 params.installerPackageName, params.volumeUuid, 15246 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15247 params.grantedRuntimePermissions, 15248 params.traceMethod, params.traceCookie, params.certificates, 15249 params.installReason); 15250 } 15251 15252 /** Existing install */ 15253 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15254 boolean isExternal, boolean isForwardLocked) { 15255 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15256 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15257 instructionSets, null, null, null, 0, null /*certificates*/, 15258 PackageManager.INSTALL_REASON_UNKNOWN); 15259 // Hackily pretend we're still looking at a full code path 15260 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15261 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15262 } 15263 15264 // Extract cid from fullCodePath 15265 int eidx = fullCodePath.lastIndexOf("/"); 15266 String subStr1 = fullCodePath.substring(0, eidx); 15267 int sidx = subStr1.lastIndexOf("/"); 15268 cid = subStr1.substring(sidx+1, eidx); 15269 setMountPath(subStr1); 15270 } 15271 15272 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15273 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15274 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15275 instructionSets, null, null, null, 0, null /*certificates*/, 15276 PackageManager.INSTALL_REASON_UNKNOWN); 15277 this.cid = cid; 15278 setMountPath(PackageHelper.getSdDir(cid)); 15279 } 15280 15281 void createCopyFile() { 15282 cid = mInstallerService.allocateExternalStageCidLegacy(); 15283 } 15284 15285 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15286 if (origin.staged && origin.cid != null) { 15287 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15288 cid = origin.cid; 15289 setMountPath(PackageHelper.getSdDir(cid)); 15290 return PackageManager.INSTALL_SUCCEEDED; 15291 } 15292 15293 if (temp) { 15294 createCopyFile(); 15295 } else { 15296 /* 15297 * Pre-emptively destroy the container since it's destroyed if 15298 * copying fails due to it existing anyway. 15299 */ 15300 PackageHelper.destroySdDir(cid); 15301 } 15302 15303 final String newMountPath = imcs.copyPackageToContainer( 15304 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15305 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15306 15307 if (newMountPath != null) { 15308 setMountPath(newMountPath); 15309 return PackageManager.INSTALL_SUCCEEDED; 15310 } else { 15311 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15312 } 15313 } 15314 15315 @Override 15316 String getCodePath() { 15317 return packagePath; 15318 } 15319 15320 @Override 15321 String getResourcePath() { 15322 return resourcePath; 15323 } 15324 15325 int doPreInstall(int status) { 15326 if (status != PackageManager.INSTALL_SUCCEEDED) { 15327 // Destroy container 15328 PackageHelper.destroySdDir(cid); 15329 } else { 15330 boolean mounted = PackageHelper.isContainerMounted(cid); 15331 if (!mounted) { 15332 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15333 Process.SYSTEM_UID); 15334 if (newMountPath != null) { 15335 setMountPath(newMountPath); 15336 } else { 15337 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15338 } 15339 } 15340 } 15341 return status; 15342 } 15343 15344 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15345 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15346 String newMountPath = null; 15347 if (PackageHelper.isContainerMounted(cid)) { 15348 // Unmount the container 15349 if (!PackageHelper.unMountSdDir(cid)) { 15350 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15351 return false; 15352 } 15353 } 15354 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15355 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15356 " which might be stale. Will try to clean up."); 15357 // Clean up the stale container and proceed to recreate. 15358 if (!PackageHelper.destroySdDir(newCacheId)) { 15359 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15360 return false; 15361 } 15362 // Successfully cleaned up stale container. Try to rename again. 15363 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15364 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15365 + " inspite of cleaning it up."); 15366 return false; 15367 } 15368 } 15369 if (!PackageHelper.isContainerMounted(newCacheId)) { 15370 Slog.w(TAG, "Mounting container " + newCacheId); 15371 newMountPath = PackageHelper.mountSdDir(newCacheId, 15372 getEncryptKey(), Process.SYSTEM_UID); 15373 } else { 15374 newMountPath = PackageHelper.getSdDir(newCacheId); 15375 } 15376 if (newMountPath == null) { 15377 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15378 return false; 15379 } 15380 Log.i(TAG, "Succesfully renamed " + cid + 15381 " to " + newCacheId + 15382 " at new path: " + newMountPath); 15383 cid = newCacheId; 15384 15385 final File beforeCodeFile = new File(packagePath); 15386 setMountPath(newMountPath); 15387 final File afterCodeFile = new File(packagePath); 15388 15389 // Reflect the rename in scanned details 15390 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15391 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15392 afterCodeFile, pkg.baseCodePath)); 15393 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15394 afterCodeFile, pkg.splitCodePaths)); 15395 15396 // Reflect the rename in app info 15397 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15398 pkg.setApplicationInfoCodePath(pkg.codePath); 15399 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15400 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15401 pkg.setApplicationInfoResourcePath(pkg.codePath); 15402 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15403 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15404 15405 return true; 15406 } 15407 15408 private void setMountPath(String mountPath) { 15409 final File mountFile = new File(mountPath); 15410 15411 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15412 if (monolithicFile.exists()) { 15413 packagePath = monolithicFile.getAbsolutePath(); 15414 if (isFwdLocked()) { 15415 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15416 } else { 15417 resourcePath = packagePath; 15418 } 15419 } else { 15420 packagePath = mountFile.getAbsolutePath(); 15421 resourcePath = packagePath; 15422 } 15423 } 15424 15425 int doPostInstall(int status, int uid) { 15426 if (status != PackageManager.INSTALL_SUCCEEDED) { 15427 cleanUp(); 15428 } else { 15429 final int groupOwner; 15430 final String protectedFile; 15431 if (isFwdLocked()) { 15432 groupOwner = UserHandle.getSharedAppGid(uid); 15433 protectedFile = RES_FILE_NAME; 15434 } else { 15435 groupOwner = -1; 15436 protectedFile = null; 15437 } 15438 15439 if (uid < Process.FIRST_APPLICATION_UID 15440 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15441 Slog.e(TAG, "Failed to finalize " + cid); 15442 PackageHelper.destroySdDir(cid); 15443 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15444 } 15445 15446 boolean mounted = PackageHelper.isContainerMounted(cid); 15447 if (!mounted) { 15448 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15449 } 15450 } 15451 return status; 15452 } 15453 15454 private void cleanUp() { 15455 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15456 15457 // Destroy secure container 15458 PackageHelper.destroySdDir(cid); 15459 } 15460 15461 private List<String> getAllCodePaths() { 15462 final File codeFile = new File(getCodePath()); 15463 if (codeFile != null && codeFile.exists()) { 15464 try { 15465 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15466 return pkg.getAllCodePaths(); 15467 } catch (PackageParserException e) { 15468 // Ignored; we tried our best 15469 } 15470 } 15471 return Collections.EMPTY_LIST; 15472 } 15473 15474 void cleanUpResourcesLI() { 15475 // Enumerate all code paths before deleting 15476 cleanUpResourcesLI(getAllCodePaths()); 15477 } 15478 15479 private void cleanUpResourcesLI(List<String> allCodePaths) { 15480 cleanUp(); 15481 removeDexFiles(allCodePaths, instructionSets); 15482 } 15483 15484 String getPackageName() { 15485 return getAsecPackageName(cid); 15486 } 15487 15488 boolean doPostDeleteLI(boolean delete) { 15489 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15490 final List<String> allCodePaths = getAllCodePaths(); 15491 boolean mounted = PackageHelper.isContainerMounted(cid); 15492 if (mounted) { 15493 // Unmount first 15494 if (PackageHelper.unMountSdDir(cid)) { 15495 mounted = false; 15496 } 15497 } 15498 if (!mounted && delete) { 15499 cleanUpResourcesLI(allCodePaths); 15500 } 15501 return !mounted; 15502 } 15503 15504 @Override 15505 int doPreCopy() { 15506 if (isFwdLocked()) { 15507 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15508 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15509 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15510 } 15511 } 15512 15513 return PackageManager.INSTALL_SUCCEEDED; 15514 } 15515 15516 @Override 15517 int doPostCopy(int uid) { 15518 if (isFwdLocked()) { 15519 if (uid < Process.FIRST_APPLICATION_UID 15520 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15521 RES_FILE_NAME)) { 15522 Slog.e(TAG, "Failed to finalize " + cid); 15523 PackageHelper.destroySdDir(cid); 15524 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15525 } 15526 } 15527 15528 return PackageManager.INSTALL_SUCCEEDED; 15529 } 15530 } 15531 15532 /** 15533 * Logic to handle movement of existing installed applications. 15534 */ 15535 class MoveInstallArgs extends InstallArgs { 15536 private File codeFile; 15537 private File resourceFile; 15538 15539 /** New install */ 15540 MoveInstallArgs(InstallParams params) { 15541 super(params.origin, params.move, params.observer, params.installFlags, 15542 params.installerPackageName, params.volumeUuid, 15543 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15544 params.grantedRuntimePermissions, 15545 params.traceMethod, params.traceCookie, params.certificates, 15546 params.installReason); 15547 } 15548 15549 int copyApk(IMediaContainerService imcs, boolean temp) { 15550 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15551 + move.fromUuid + " to " + move.toUuid); 15552 synchronized (mInstaller) { 15553 try { 15554 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15555 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15556 } catch (InstallerException e) { 15557 Slog.w(TAG, "Failed to move app", e); 15558 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15559 } 15560 } 15561 15562 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15563 resourceFile = codeFile; 15564 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15565 15566 return PackageManager.INSTALL_SUCCEEDED; 15567 } 15568 15569 int doPreInstall(int status) { 15570 if (status != PackageManager.INSTALL_SUCCEEDED) { 15571 cleanUp(move.toUuid); 15572 } 15573 return status; 15574 } 15575 15576 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15577 if (status != PackageManager.INSTALL_SUCCEEDED) { 15578 cleanUp(move.toUuid); 15579 return false; 15580 } 15581 15582 // Reflect the move in app info 15583 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15584 pkg.setApplicationInfoCodePath(pkg.codePath); 15585 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15586 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15587 pkg.setApplicationInfoResourcePath(pkg.codePath); 15588 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15589 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15590 15591 return true; 15592 } 15593 15594 int doPostInstall(int status, int uid) { 15595 if (status == PackageManager.INSTALL_SUCCEEDED) { 15596 cleanUp(move.fromUuid); 15597 } else { 15598 cleanUp(move.toUuid); 15599 } 15600 return status; 15601 } 15602 15603 @Override 15604 String getCodePath() { 15605 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15606 } 15607 15608 @Override 15609 String getResourcePath() { 15610 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15611 } 15612 15613 private boolean cleanUp(String volumeUuid) { 15614 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15615 move.dataAppName); 15616 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15617 final int[] userIds = sUserManager.getUserIds(); 15618 synchronized (mInstallLock) { 15619 // Clean up both app data and code 15620 // All package moves are frozen until finished 15621 for (int userId : userIds) { 15622 try { 15623 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15624 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15625 } catch (InstallerException e) { 15626 Slog.w(TAG, String.valueOf(e)); 15627 } 15628 } 15629 removeCodePathLI(codeFile); 15630 } 15631 return true; 15632 } 15633 15634 void cleanUpResourcesLI() { 15635 throw new UnsupportedOperationException(); 15636 } 15637 15638 boolean doPostDeleteLI(boolean delete) { 15639 throw new UnsupportedOperationException(); 15640 } 15641 } 15642 15643 static String getAsecPackageName(String packageCid) { 15644 int idx = packageCid.lastIndexOf("-"); 15645 if (idx == -1) { 15646 return packageCid; 15647 } 15648 return packageCid.substring(0, idx); 15649 } 15650 15651 // Utility method used to create code paths based on package name and available index. 15652 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15653 String idxStr = ""; 15654 int idx = 1; 15655 // Fall back to default value of idx=1 if prefix is not 15656 // part of oldCodePath 15657 if (oldCodePath != null) { 15658 String subStr = oldCodePath; 15659 // Drop the suffix right away 15660 if (suffix != null && subStr.endsWith(suffix)) { 15661 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15662 } 15663 // If oldCodePath already contains prefix find out the 15664 // ending index to either increment or decrement. 15665 int sidx = subStr.lastIndexOf(prefix); 15666 if (sidx != -1) { 15667 subStr = subStr.substring(sidx + prefix.length()); 15668 if (subStr != null) { 15669 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15670 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15671 } 15672 try { 15673 idx = Integer.parseInt(subStr); 15674 if (idx <= 1) { 15675 idx++; 15676 } else { 15677 idx--; 15678 } 15679 } catch(NumberFormatException e) { 15680 } 15681 } 15682 } 15683 } 15684 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15685 return prefix + idxStr; 15686 } 15687 15688 private File getNextCodePath(File targetDir, String packageName) { 15689 File result; 15690 SecureRandom random = new SecureRandom(); 15691 byte[] bytes = new byte[16]; 15692 do { 15693 random.nextBytes(bytes); 15694 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15695 result = new File(targetDir, packageName + "-" + suffix); 15696 } while (result.exists()); 15697 return result; 15698 } 15699 15700 // Utility method that returns the relative package path with respect 15701 // to the installation directory. Like say for /data/data/com.test-1.apk 15702 // string com.test-1 is returned. 15703 static String deriveCodePathName(String codePath) { 15704 if (codePath == null) { 15705 return null; 15706 } 15707 final File codeFile = new File(codePath); 15708 final String name = codeFile.getName(); 15709 if (codeFile.isDirectory()) { 15710 return name; 15711 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15712 final int lastDot = name.lastIndexOf('.'); 15713 return name.substring(0, lastDot); 15714 } else { 15715 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15716 return null; 15717 } 15718 } 15719 15720 static class PackageInstalledInfo { 15721 String name; 15722 int uid; 15723 // The set of users that originally had this package installed. 15724 int[] origUsers; 15725 // The set of users that now have this package installed. 15726 int[] newUsers; 15727 PackageParser.Package pkg; 15728 int returnCode; 15729 String returnMsg; 15730 PackageRemovedInfo removedInfo; 15731 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15732 15733 public void setError(int code, String msg) { 15734 setReturnCode(code); 15735 setReturnMessage(msg); 15736 Slog.w(TAG, msg); 15737 } 15738 15739 public void setError(String msg, PackageParserException e) { 15740 setReturnCode(e.error); 15741 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15742 Slog.w(TAG, msg, e); 15743 } 15744 15745 public void setError(String msg, PackageManagerException e) { 15746 returnCode = e.error; 15747 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15748 Slog.w(TAG, msg, e); 15749 } 15750 15751 public void setReturnCode(int returnCode) { 15752 this.returnCode = returnCode; 15753 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15754 for (int i = 0; i < childCount; i++) { 15755 addedChildPackages.valueAt(i).returnCode = returnCode; 15756 } 15757 } 15758 15759 private void setReturnMessage(String returnMsg) { 15760 this.returnMsg = returnMsg; 15761 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15762 for (int i = 0; i < childCount; i++) { 15763 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15764 } 15765 } 15766 15767 // In some error cases we want to convey more info back to the observer 15768 String origPackage; 15769 String origPermission; 15770 } 15771 15772 /* 15773 * Install a non-existing package. 15774 */ 15775 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15776 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15777 PackageInstalledInfo res, int installReason) { 15778 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15779 15780 // Remember this for later, in case we need to rollback this install 15781 String pkgName = pkg.packageName; 15782 15783 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15784 15785 synchronized(mPackages) { 15786 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15787 if (renamedPackage != null) { 15788 // A package with the same name is already installed, though 15789 // it has been renamed to an older name. The package we 15790 // are trying to install should be installed as an update to 15791 // the existing one, but that has not been requested, so bail. 15792 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15793 + " without first uninstalling package running as " 15794 + renamedPackage); 15795 return; 15796 } 15797 if (mPackages.containsKey(pkgName)) { 15798 // Don't allow installation over an existing package with the same name. 15799 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15800 + " without first uninstalling."); 15801 return; 15802 } 15803 } 15804 15805 try { 15806 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15807 System.currentTimeMillis(), user); 15808 15809 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15810 15811 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15812 prepareAppDataAfterInstallLIF(newPackage); 15813 15814 } else { 15815 // Remove package from internal structures, but keep around any 15816 // data that might have already existed 15817 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15818 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15819 } 15820 } catch (PackageManagerException e) { 15821 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15822 } 15823 15824 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15825 } 15826 15827 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15828 // Can't rotate keys during boot or if sharedUser. 15829 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15830 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15831 return false; 15832 } 15833 // app is using upgradeKeySets; make sure all are valid 15834 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15835 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15836 for (int i = 0; i < upgradeKeySets.length; i++) { 15837 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15838 Slog.wtf(TAG, "Package " 15839 + (oldPs.name != null ? oldPs.name : "<null>") 15840 + " contains upgrade-key-set reference to unknown key-set: " 15841 + upgradeKeySets[i] 15842 + " reverting to signatures check."); 15843 return false; 15844 } 15845 } 15846 return true; 15847 } 15848 15849 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15850 // Upgrade keysets are being used. Determine if new package has a superset of the 15851 // required keys. 15852 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15853 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15854 for (int i = 0; i < upgradeKeySets.length; i++) { 15855 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15856 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15857 return true; 15858 } 15859 } 15860 return false; 15861 } 15862 15863 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15864 try (DigestInputStream digestStream = 15865 new DigestInputStream(new FileInputStream(file), digest)) { 15866 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15867 } 15868 } 15869 15870 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15871 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15872 int installReason) { 15873 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15874 15875 final PackageParser.Package oldPackage; 15876 final String pkgName = pkg.packageName; 15877 final int[] allUsers; 15878 final int[] installedUsers; 15879 15880 synchronized(mPackages) { 15881 oldPackage = mPackages.get(pkgName); 15882 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15883 15884 // don't allow upgrade to target a release SDK from a pre-release SDK 15885 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15886 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15887 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15888 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15889 if (oldTargetsPreRelease 15890 && !newTargetsPreRelease 15891 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15892 Slog.w(TAG, "Can't install package targeting released sdk"); 15893 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15894 return; 15895 } 15896 15897 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15898 15899 // verify signatures are valid 15900 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15901 if (!checkUpgradeKeySetLP(ps, pkg)) { 15902 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15903 "New package not signed by keys specified by upgrade-keysets: " 15904 + pkgName); 15905 return; 15906 } 15907 } else { 15908 // default to original signature matching 15909 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15910 != PackageManager.SIGNATURE_MATCH) { 15911 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15912 "New package has a different signature: " + pkgName); 15913 return; 15914 } 15915 } 15916 15917 // don't allow a system upgrade unless the upgrade hash matches 15918 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15919 byte[] digestBytes = null; 15920 try { 15921 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15922 updateDigest(digest, new File(pkg.baseCodePath)); 15923 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15924 for (String path : pkg.splitCodePaths) { 15925 updateDigest(digest, new File(path)); 15926 } 15927 } 15928 digestBytes = digest.digest(); 15929 } catch (NoSuchAlgorithmException | IOException e) { 15930 res.setError(INSTALL_FAILED_INVALID_APK, 15931 "Could not compute hash: " + pkgName); 15932 return; 15933 } 15934 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15935 res.setError(INSTALL_FAILED_INVALID_APK, 15936 "New package fails restrict-update check: " + pkgName); 15937 return; 15938 } 15939 // retain upgrade restriction 15940 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15941 } 15942 15943 // Check for shared user id changes 15944 String invalidPackageName = 15945 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15946 if (invalidPackageName != null) { 15947 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15948 "Package " + invalidPackageName + " tried to change user " 15949 + oldPackage.mSharedUserId); 15950 return; 15951 } 15952 15953 // In case of rollback, remember per-user/profile install state 15954 allUsers = sUserManager.getUserIds(); 15955 installedUsers = ps.queryInstalledUsers(allUsers, true); 15956 15957 // don't allow an upgrade from full to ephemeral 15958 if (isInstantApp) { 15959 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15960 for (int currentUser : allUsers) { 15961 if (!ps.getInstantApp(currentUser)) { 15962 // can't downgrade from full to instant 15963 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15964 + " for user: " + currentUser); 15965 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15966 return; 15967 } 15968 } 15969 } else if (!ps.getInstantApp(user.getIdentifier())) { 15970 // can't downgrade from full to instant 15971 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15972 + " for user: " + user.getIdentifier()); 15973 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15974 return; 15975 } 15976 } 15977 } 15978 15979 // Update what is removed 15980 res.removedInfo = new PackageRemovedInfo(); 15981 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15982 res.removedInfo.removedPackage = oldPackage.packageName; 15983 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15984 res.removedInfo.isUpdate = true; 15985 res.removedInfo.origUsers = installedUsers; 15986 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15987 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15988 for (int i = 0; i < installedUsers.length; i++) { 15989 final int userId = installedUsers[i]; 15990 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15991 } 15992 15993 final int childCount = (oldPackage.childPackages != null) 15994 ? oldPackage.childPackages.size() : 0; 15995 for (int i = 0; i < childCount; i++) { 15996 boolean childPackageUpdated = false; 15997 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15998 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15999 if (res.addedChildPackages != null) { 16000 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16001 if (childRes != null) { 16002 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16003 childRes.removedInfo.removedPackage = childPkg.packageName; 16004 childRes.removedInfo.isUpdate = true; 16005 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16006 childPackageUpdated = true; 16007 } 16008 } 16009 if (!childPackageUpdated) { 16010 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16011 childRemovedRes.removedPackage = childPkg.packageName; 16012 childRemovedRes.isUpdate = false; 16013 childRemovedRes.dataRemoved = true; 16014 synchronized (mPackages) { 16015 if (childPs != null) { 16016 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16017 } 16018 } 16019 if (res.removedInfo.removedChildPackages == null) { 16020 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16021 } 16022 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16023 } 16024 } 16025 16026 boolean sysPkg = (isSystemApp(oldPackage)); 16027 if (sysPkg) { 16028 // Set the system/privileged flags as needed 16029 final boolean privileged = 16030 (oldPackage.applicationInfo.privateFlags 16031 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16032 final int systemPolicyFlags = policyFlags 16033 | PackageParser.PARSE_IS_SYSTEM 16034 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16035 16036 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16037 user, allUsers, installerPackageName, res, installReason); 16038 } else { 16039 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16040 user, allUsers, installerPackageName, res, installReason); 16041 } 16042 } 16043 16044 public List<String> getPreviousCodePaths(String packageName) { 16045 final PackageSetting ps = mSettings.mPackages.get(packageName); 16046 final List<String> result = new ArrayList<String>(); 16047 if (ps != null && ps.oldCodePaths != null) { 16048 result.addAll(ps.oldCodePaths); 16049 } 16050 return result; 16051 } 16052 16053 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16054 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16055 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16056 int installReason) { 16057 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16058 + deletedPackage); 16059 16060 String pkgName = deletedPackage.packageName; 16061 boolean deletedPkg = true; 16062 boolean addedPkg = false; 16063 boolean updatedSettings = false; 16064 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16065 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16066 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16067 16068 final long origUpdateTime = (pkg.mExtras != null) 16069 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16070 16071 // First delete the existing package while retaining the data directory 16072 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16073 res.removedInfo, true, pkg)) { 16074 // If the existing package wasn't successfully deleted 16075 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16076 deletedPkg = false; 16077 } else { 16078 // Successfully deleted the old package; proceed with replace. 16079 16080 // If deleted package lived in a container, give users a chance to 16081 // relinquish resources before killing. 16082 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16083 if (DEBUG_INSTALL) { 16084 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16085 } 16086 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16087 final ArrayList<String> pkgList = new ArrayList<String>(1); 16088 pkgList.add(deletedPackage.applicationInfo.packageName); 16089 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16090 } 16091 16092 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16093 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16094 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16095 16096 try { 16097 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16098 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16099 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16100 installReason); 16101 16102 // Update the in-memory copy of the previous code paths. 16103 PackageSetting ps = mSettings.mPackages.get(pkgName); 16104 if (!killApp) { 16105 if (ps.oldCodePaths == null) { 16106 ps.oldCodePaths = new ArraySet<>(); 16107 } 16108 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16109 if (deletedPackage.splitCodePaths != null) { 16110 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16111 } 16112 } else { 16113 ps.oldCodePaths = null; 16114 } 16115 if (ps.childPackageNames != null) { 16116 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16117 final String childPkgName = ps.childPackageNames.get(i); 16118 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16119 childPs.oldCodePaths = ps.oldCodePaths; 16120 } 16121 } 16122 // set instant app status, but, only if it's explicitly specified 16123 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16124 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16125 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16126 prepareAppDataAfterInstallLIF(newPackage); 16127 addedPkg = true; 16128 mDexManager.notifyPackageUpdated(newPackage.packageName, 16129 newPackage.baseCodePath, newPackage.splitCodePaths); 16130 } catch (PackageManagerException e) { 16131 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16132 } 16133 } 16134 16135 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16136 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16137 16138 // Revert all internal state mutations and added folders for the failed install 16139 if (addedPkg) { 16140 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16141 res.removedInfo, true, null); 16142 } 16143 16144 // Restore the old package 16145 if (deletedPkg) { 16146 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16147 File restoreFile = new File(deletedPackage.codePath); 16148 // Parse old package 16149 boolean oldExternal = isExternal(deletedPackage); 16150 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16151 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16152 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16153 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16154 try { 16155 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16156 null); 16157 } catch (PackageManagerException e) { 16158 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16159 + e.getMessage()); 16160 return; 16161 } 16162 16163 synchronized (mPackages) { 16164 // Ensure the installer package name up to date 16165 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16166 16167 // Update permissions for restored package 16168 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16169 16170 mSettings.writeLPr(); 16171 } 16172 16173 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16174 } 16175 } else { 16176 synchronized (mPackages) { 16177 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16178 if (ps != null) { 16179 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16180 if (res.removedInfo.removedChildPackages != null) { 16181 final int childCount = res.removedInfo.removedChildPackages.size(); 16182 // Iterate in reverse as we may modify the collection 16183 for (int i = childCount - 1; i >= 0; i--) { 16184 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16185 if (res.addedChildPackages.containsKey(childPackageName)) { 16186 res.removedInfo.removedChildPackages.removeAt(i); 16187 } else { 16188 PackageRemovedInfo childInfo = res.removedInfo 16189 .removedChildPackages.valueAt(i); 16190 childInfo.removedForAllUsers = mPackages.get( 16191 childInfo.removedPackage) == null; 16192 } 16193 } 16194 } 16195 } 16196 } 16197 } 16198 } 16199 16200 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16201 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16202 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16203 int installReason) { 16204 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16205 + ", old=" + deletedPackage); 16206 16207 final boolean disabledSystem; 16208 16209 // Remove existing system package 16210 removePackageLI(deletedPackage, true); 16211 16212 synchronized (mPackages) { 16213 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16214 } 16215 if (!disabledSystem) { 16216 // We didn't need to disable the .apk as a current system package, 16217 // which means we are replacing another update that is already 16218 // installed. We need to make sure to delete the older one's .apk. 16219 res.removedInfo.args = createInstallArgsForExisting(0, 16220 deletedPackage.applicationInfo.getCodePath(), 16221 deletedPackage.applicationInfo.getResourcePath(), 16222 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16223 } else { 16224 res.removedInfo.args = null; 16225 } 16226 16227 // Successfully disabled the old package. Now proceed with re-installation 16228 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16229 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16230 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16231 16232 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16233 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16234 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16235 16236 PackageParser.Package newPackage = null; 16237 try { 16238 // Add the package to the internal data structures 16239 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16240 16241 // Set the update and install times 16242 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16243 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16244 System.currentTimeMillis()); 16245 16246 // Update the package dynamic state if succeeded 16247 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16248 // Now that the install succeeded make sure we remove data 16249 // directories for any child package the update removed. 16250 final int deletedChildCount = (deletedPackage.childPackages != null) 16251 ? deletedPackage.childPackages.size() : 0; 16252 final int newChildCount = (newPackage.childPackages != null) 16253 ? newPackage.childPackages.size() : 0; 16254 for (int i = 0; i < deletedChildCount; i++) { 16255 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16256 boolean childPackageDeleted = true; 16257 for (int j = 0; j < newChildCount; j++) { 16258 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16259 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16260 childPackageDeleted = false; 16261 break; 16262 } 16263 } 16264 if (childPackageDeleted) { 16265 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16266 deletedChildPkg.packageName); 16267 if (ps != null && res.removedInfo.removedChildPackages != null) { 16268 PackageRemovedInfo removedChildRes = res.removedInfo 16269 .removedChildPackages.get(deletedChildPkg.packageName); 16270 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16271 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16272 } 16273 } 16274 } 16275 16276 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16277 installReason); 16278 prepareAppDataAfterInstallLIF(newPackage); 16279 16280 mDexManager.notifyPackageUpdated(newPackage.packageName, 16281 newPackage.baseCodePath, newPackage.splitCodePaths); 16282 } 16283 } catch (PackageManagerException e) { 16284 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16285 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16286 } 16287 16288 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16289 // Re installation failed. Restore old information 16290 // Remove new pkg information 16291 if (newPackage != null) { 16292 removeInstalledPackageLI(newPackage, true); 16293 } 16294 // Add back the old system package 16295 try { 16296 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16297 } catch (PackageManagerException e) { 16298 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16299 } 16300 16301 synchronized (mPackages) { 16302 if (disabledSystem) { 16303 enableSystemPackageLPw(deletedPackage); 16304 } 16305 16306 // Ensure the installer package name up to date 16307 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16308 16309 // Update permissions for restored package 16310 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16311 16312 mSettings.writeLPr(); 16313 } 16314 16315 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16316 + " after failed upgrade"); 16317 } 16318 } 16319 16320 /** 16321 * Checks whether the parent or any of the child packages have a change shared 16322 * user. For a package to be a valid update the shred users of the parent and 16323 * the children should match. We may later support changing child shared users. 16324 * @param oldPkg The updated package. 16325 * @param newPkg The update package. 16326 * @return The shared user that change between the versions. 16327 */ 16328 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16329 PackageParser.Package newPkg) { 16330 // Check parent shared user 16331 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16332 return newPkg.packageName; 16333 } 16334 // Check child shared users 16335 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16336 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16337 for (int i = 0; i < newChildCount; i++) { 16338 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16339 // If this child was present, did it have the same shared user? 16340 for (int j = 0; j < oldChildCount; j++) { 16341 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16342 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16343 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16344 return newChildPkg.packageName; 16345 } 16346 } 16347 } 16348 return null; 16349 } 16350 16351 private void removeNativeBinariesLI(PackageSetting ps) { 16352 // Remove the lib path for the parent package 16353 if (ps != null) { 16354 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16355 // Remove the lib path for the child packages 16356 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16357 for (int i = 0; i < childCount; i++) { 16358 PackageSetting childPs = null; 16359 synchronized (mPackages) { 16360 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16361 } 16362 if (childPs != null) { 16363 NativeLibraryHelper.removeNativeBinariesLI(childPs 16364 .legacyNativeLibraryPathString); 16365 } 16366 } 16367 } 16368 } 16369 16370 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16371 // Enable the parent package 16372 mSettings.enableSystemPackageLPw(pkg.packageName); 16373 // Enable the child packages 16374 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16375 for (int i = 0; i < childCount; i++) { 16376 PackageParser.Package childPkg = pkg.childPackages.get(i); 16377 mSettings.enableSystemPackageLPw(childPkg.packageName); 16378 } 16379 } 16380 16381 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16382 PackageParser.Package newPkg) { 16383 // Disable the parent package (parent always replaced) 16384 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16385 // Disable the child packages 16386 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16387 for (int i = 0; i < childCount; i++) { 16388 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16389 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16390 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16391 } 16392 return disabled; 16393 } 16394 16395 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16396 String installerPackageName) { 16397 // Enable the parent package 16398 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16399 // Enable the child packages 16400 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16401 for (int i = 0; i < childCount; i++) { 16402 PackageParser.Package childPkg = pkg.childPackages.get(i); 16403 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16404 } 16405 } 16406 16407 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16408 // Collect all used permissions in the UID 16409 ArraySet<String> usedPermissions = new ArraySet<>(); 16410 final int packageCount = su.packages.size(); 16411 for (int i = 0; i < packageCount; i++) { 16412 PackageSetting ps = su.packages.valueAt(i); 16413 if (ps.pkg == null) { 16414 continue; 16415 } 16416 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16417 for (int j = 0; j < requestedPermCount; j++) { 16418 String permission = ps.pkg.requestedPermissions.get(j); 16419 BasePermission bp = mSettings.mPermissions.get(permission); 16420 if (bp != null) { 16421 usedPermissions.add(permission); 16422 } 16423 } 16424 } 16425 16426 PermissionsState permissionsState = su.getPermissionsState(); 16427 // Prune install permissions 16428 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16429 final int installPermCount = installPermStates.size(); 16430 for (int i = installPermCount - 1; i >= 0; i--) { 16431 PermissionState permissionState = installPermStates.get(i); 16432 if (!usedPermissions.contains(permissionState.getName())) { 16433 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16434 if (bp != null) { 16435 permissionsState.revokeInstallPermission(bp); 16436 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16437 PackageManager.MASK_PERMISSION_FLAGS, 0); 16438 } 16439 } 16440 } 16441 16442 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16443 16444 // Prune runtime permissions 16445 for (int userId : allUserIds) { 16446 List<PermissionState> runtimePermStates = permissionsState 16447 .getRuntimePermissionStates(userId); 16448 final int runtimePermCount = runtimePermStates.size(); 16449 for (int i = runtimePermCount - 1; i >= 0; i--) { 16450 PermissionState permissionState = runtimePermStates.get(i); 16451 if (!usedPermissions.contains(permissionState.getName())) { 16452 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16453 if (bp != null) { 16454 permissionsState.revokeRuntimePermission(bp, userId); 16455 permissionsState.updatePermissionFlags(bp, userId, 16456 PackageManager.MASK_PERMISSION_FLAGS, 0); 16457 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16458 runtimePermissionChangedUserIds, userId); 16459 } 16460 } 16461 } 16462 } 16463 16464 return runtimePermissionChangedUserIds; 16465 } 16466 16467 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16468 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16469 // Update the parent package setting 16470 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16471 res, user, installReason); 16472 // Update the child packages setting 16473 final int childCount = (newPackage.childPackages != null) 16474 ? newPackage.childPackages.size() : 0; 16475 for (int i = 0; i < childCount; i++) { 16476 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16477 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16478 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16479 childRes.origUsers, childRes, user, installReason); 16480 } 16481 } 16482 16483 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16484 String installerPackageName, int[] allUsers, int[] installedForUsers, 16485 PackageInstalledInfo res, UserHandle user, int installReason) { 16486 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16487 16488 String pkgName = newPackage.packageName; 16489 synchronized (mPackages) { 16490 //write settings. the installStatus will be incomplete at this stage. 16491 //note that the new package setting would have already been 16492 //added to mPackages. It hasn't been persisted yet. 16493 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16494 // TODO: Remove this write? It's also written at the end of this method 16495 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16496 mSettings.writeLPr(); 16497 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16498 } 16499 16500 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16501 synchronized (mPackages) { 16502 updatePermissionsLPw(newPackage.packageName, newPackage, 16503 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16504 ? UPDATE_PERMISSIONS_ALL : 0)); 16505 // For system-bundled packages, we assume that installing an upgraded version 16506 // of the package implies that the user actually wants to run that new code, 16507 // so we enable the package. 16508 PackageSetting ps = mSettings.mPackages.get(pkgName); 16509 final int userId = user.getIdentifier(); 16510 if (ps != null) { 16511 if (isSystemApp(newPackage)) { 16512 if (DEBUG_INSTALL) { 16513 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16514 } 16515 // Enable system package for requested users 16516 if (res.origUsers != null) { 16517 for (int origUserId : res.origUsers) { 16518 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16519 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16520 origUserId, installerPackageName); 16521 } 16522 } 16523 } 16524 // Also convey the prior install/uninstall state 16525 if (allUsers != null && installedForUsers != null) { 16526 for (int currentUserId : allUsers) { 16527 final boolean installed = ArrayUtils.contains( 16528 installedForUsers, currentUserId); 16529 if (DEBUG_INSTALL) { 16530 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16531 } 16532 ps.setInstalled(installed, currentUserId); 16533 } 16534 // these install state changes will be persisted in the 16535 // upcoming call to mSettings.writeLPr(). 16536 } 16537 } 16538 // It's implied that when a user requests installation, they want the app to be 16539 // installed and enabled. 16540 if (userId != UserHandle.USER_ALL) { 16541 ps.setInstalled(true, userId); 16542 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16543 } 16544 16545 // When replacing an existing package, preserve the original install reason for all 16546 // users that had the package installed before. 16547 final Set<Integer> previousUserIds = new ArraySet<>(); 16548 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16549 final int installReasonCount = res.removedInfo.installReasons.size(); 16550 for (int i = 0; i < installReasonCount; i++) { 16551 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16552 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16553 ps.setInstallReason(previousInstallReason, previousUserId); 16554 previousUserIds.add(previousUserId); 16555 } 16556 } 16557 16558 // Set install reason for users that are having the package newly installed. 16559 if (userId == UserHandle.USER_ALL) { 16560 for (int currentUserId : sUserManager.getUserIds()) { 16561 if (!previousUserIds.contains(currentUserId)) { 16562 ps.setInstallReason(installReason, currentUserId); 16563 } 16564 } 16565 } else if (!previousUserIds.contains(userId)) { 16566 ps.setInstallReason(installReason, userId); 16567 } 16568 mSettings.writeKernelMappingLPr(ps); 16569 } 16570 res.name = pkgName; 16571 res.uid = newPackage.applicationInfo.uid; 16572 res.pkg = newPackage; 16573 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16574 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16575 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16576 //to update install status 16577 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16578 mSettings.writeLPr(); 16579 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16580 } 16581 16582 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16583 } 16584 16585 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16586 try { 16587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16588 installPackageLI(args, res); 16589 } finally { 16590 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16591 } 16592 } 16593 16594 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16595 final int installFlags = args.installFlags; 16596 final String installerPackageName = args.installerPackageName; 16597 final String volumeUuid = args.volumeUuid; 16598 final File tmpPackageFile = new File(args.getCodePath()); 16599 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16600 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16601 || (args.volumeUuid != null)); 16602 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16603 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16604 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16605 boolean replace = false; 16606 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16607 if (args.move != null) { 16608 // moving a complete application; perform an initial scan on the new install location 16609 scanFlags |= SCAN_INITIAL; 16610 } 16611 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16612 scanFlags |= SCAN_DONT_KILL_APP; 16613 } 16614 if (instantApp) { 16615 scanFlags |= SCAN_AS_INSTANT_APP; 16616 } 16617 if (fullApp) { 16618 scanFlags |= SCAN_AS_FULL_APP; 16619 } 16620 16621 // Result object to be returned 16622 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16623 16624 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16625 16626 // Sanity check 16627 if (instantApp && (forwardLocked || onExternal)) { 16628 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16629 + " external=" + onExternal); 16630 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16631 return; 16632 } 16633 16634 // Retrieve PackageSettings and parse package 16635 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16636 | PackageParser.PARSE_ENFORCE_CODE 16637 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16638 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16639 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16640 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16641 PackageParser pp = new PackageParser(); 16642 pp.setSeparateProcesses(mSeparateProcesses); 16643 pp.setDisplayMetrics(mMetrics); 16644 pp.setCallback(mPackageParserCallback); 16645 16646 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16647 final PackageParser.Package pkg; 16648 try { 16649 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16650 } catch (PackageParserException e) { 16651 res.setError("Failed parse during installPackageLI", e); 16652 return; 16653 } finally { 16654 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16655 } 16656 16657 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16658 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16659 Slog.w(TAG, "Instant app package " + pkg.packageName 16660 + " does not target O, this will be a fatal error."); 16661 // STOPSHIP: Make this a fatal error 16662 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16663 } 16664 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16665 Slog.w(TAG, "Instant app package " + pkg.packageName 16666 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16667 // STOPSHIP: Make this a fatal error 16668 pkg.applicationInfo.targetSandboxVersion = 2; 16669 } 16670 16671 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16672 // Static shared libraries have synthetic package names 16673 renameStaticSharedLibraryPackage(pkg); 16674 16675 // No static shared libs on external storage 16676 if (onExternal) { 16677 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16678 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16679 "Packages declaring static-shared libs cannot be updated"); 16680 return; 16681 } 16682 } 16683 16684 // If we are installing a clustered package add results for the children 16685 if (pkg.childPackages != null) { 16686 synchronized (mPackages) { 16687 final int childCount = pkg.childPackages.size(); 16688 for (int i = 0; i < childCount; i++) { 16689 PackageParser.Package childPkg = pkg.childPackages.get(i); 16690 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16691 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16692 childRes.pkg = childPkg; 16693 childRes.name = childPkg.packageName; 16694 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16695 if (childPs != null) { 16696 childRes.origUsers = childPs.queryInstalledUsers( 16697 sUserManager.getUserIds(), true); 16698 } 16699 if ((mPackages.containsKey(childPkg.packageName))) { 16700 childRes.removedInfo = new PackageRemovedInfo(); 16701 childRes.removedInfo.removedPackage = childPkg.packageName; 16702 } 16703 if (res.addedChildPackages == null) { 16704 res.addedChildPackages = new ArrayMap<>(); 16705 } 16706 res.addedChildPackages.put(childPkg.packageName, childRes); 16707 } 16708 } 16709 } 16710 16711 // If package doesn't declare API override, mark that we have an install 16712 // time CPU ABI override. 16713 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16714 pkg.cpuAbiOverride = args.abiOverride; 16715 } 16716 16717 String pkgName = res.name = pkg.packageName; 16718 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16719 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16720 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16721 return; 16722 } 16723 } 16724 16725 try { 16726 // either use what we've been given or parse directly from the APK 16727 if (args.certificates != null) { 16728 try { 16729 PackageParser.populateCertificates(pkg, args.certificates); 16730 } catch (PackageParserException e) { 16731 // there was something wrong with the certificates we were given; 16732 // try to pull them from the APK 16733 PackageParser.collectCertificates(pkg, parseFlags); 16734 } 16735 } else { 16736 PackageParser.collectCertificates(pkg, parseFlags); 16737 } 16738 } catch (PackageParserException e) { 16739 res.setError("Failed collect during installPackageLI", e); 16740 return; 16741 } 16742 16743 // Get rid of all references to package scan path via parser. 16744 pp = null; 16745 String oldCodePath = null; 16746 boolean systemApp = false; 16747 synchronized (mPackages) { 16748 // Check if installing already existing package 16749 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16750 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16751 if (pkg.mOriginalPackages != null 16752 && pkg.mOriginalPackages.contains(oldName) 16753 && mPackages.containsKey(oldName)) { 16754 // This package is derived from an original package, 16755 // and this device has been updating from that original 16756 // name. We must continue using the original name, so 16757 // rename the new package here. 16758 pkg.setPackageName(oldName); 16759 pkgName = pkg.packageName; 16760 replace = true; 16761 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16762 + oldName + " pkgName=" + pkgName); 16763 } else if (mPackages.containsKey(pkgName)) { 16764 // This package, under its official name, already exists 16765 // on the device; we should replace it. 16766 replace = true; 16767 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16768 } 16769 16770 // Child packages are installed through the parent package 16771 if (pkg.parentPackage != null) { 16772 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16773 "Package " + pkg.packageName + " is child of package " 16774 + pkg.parentPackage.parentPackage + ". Child packages " 16775 + "can be updated only through the parent package."); 16776 return; 16777 } 16778 16779 if (replace) { 16780 // Prevent apps opting out from runtime permissions 16781 PackageParser.Package oldPackage = mPackages.get(pkgName); 16782 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16783 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16784 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16785 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16786 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16787 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16788 + " doesn't support runtime permissions but the old" 16789 + " target SDK " + oldTargetSdk + " does."); 16790 return; 16791 } 16792 // Prevent apps from downgrading their targetSandbox. 16793 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16794 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16795 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16796 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16797 "Package " + pkg.packageName + " new target sandbox " 16798 + newTargetSandbox + " is incompatible with the previous value of" 16799 + oldTargetSandbox + "."); 16800 return; 16801 } 16802 16803 // Prevent installing of child packages 16804 if (oldPackage.parentPackage != null) { 16805 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16806 "Package " + pkg.packageName + " is child of package " 16807 + oldPackage.parentPackage + ". Child packages " 16808 + "can be updated only through the parent package."); 16809 return; 16810 } 16811 } 16812 } 16813 16814 PackageSetting ps = mSettings.mPackages.get(pkgName); 16815 if (ps != null) { 16816 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16817 16818 // Static shared libs have same package with different versions where 16819 // we internally use a synthetic package name to allow multiple versions 16820 // of the same package, therefore we need to compare signatures against 16821 // the package setting for the latest library version. 16822 PackageSetting signatureCheckPs = ps; 16823 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16824 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16825 if (libraryEntry != null) { 16826 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16827 } 16828 } 16829 16830 // Quick sanity check that we're signed correctly if updating; 16831 // we'll check this again later when scanning, but we want to 16832 // bail early here before tripping over redefined permissions. 16833 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16834 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16835 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16836 + pkg.packageName + " upgrade keys do not match the " 16837 + "previously installed version"); 16838 return; 16839 } 16840 } else { 16841 try { 16842 verifySignaturesLP(signatureCheckPs, pkg); 16843 } catch (PackageManagerException e) { 16844 res.setError(e.error, e.getMessage()); 16845 return; 16846 } 16847 } 16848 16849 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16850 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16851 systemApp = (ps.pkg.applicationInfo.flags & 16852 ApplicationInfo.FLAG_SYSTEM) != 0; 16853 } 16854 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16855 } 16856 16857 int N = pkg.permissions.size(); 16858 for (int i = N-1; i >= 0; i--) { 16859 PackageParser.Permission perm = pkg.permissions.get(i); 16860 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16861 16862 // Don't allow anyone but the platform to define ephemeral permissions. 16863 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16864 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16865 Slog.w(TAG, "Package " + pkg.packageName 16866 + " attempting to delcare ephemeral permission " 16867 + perm.info.name + "; Removing ephemeral."); 16868 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16869 } 16870 // Check whether the newly-scanned package wants to define an already-defined perm 16871 if (bp != null) { 16872 // If the defining package is signed with our cert, it's okay. This 16873 // also includes the "updating the same package" case, of course. 16874 // "updating same package" could also involve key-rotation. 16875 final boolean sigsOk; 16876 if (bp.sourcePackage.equals(pkg.packageName) 16877 && (bp.packageSetting instanceof PackageSetting) 16878 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16879 scanFlags))) { 16880 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16881 } else { 16882 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16883 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16884 } 16885 if (!sigsOk) { 16886 // If the owning package is the system itself, we log but allow 16887 // install to proceed; we fail the install on all other permission 16888 // redefinitions. 16889 if (!bp.sourcePackage.equals("android")) { 16890 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16891 + pkg.packageName + " attempting to redeclare permission " 16892 + perm.info.name + " already owned by " + bp.sourcePackage); 16893 res.origPermission = perm.info.name; 16894 res.origPackage = bp.sourcePackage; 16895 return; 16896 } else { 16897 Slog.w(TAG, "Package " + pkg.packageName 16898 + " attempting to redeclare system permission " 16899 + perm.info.name + "; ignoring new declaration"); 16900 pkg.permissions.remove(i); 16901 } 16902 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16903 // Prevent apps to change protection level to dangerous from any other 16904 // type as this would allow a privilege escalation where an app adds a 16905 // normal/signature permission in other app's group and later redefines 16906 // it as dangerous leading to the group auto-grant. 16907 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16908 == PermissionInfo.PROTECTION_DANGEROUS) { 16909 if (bp != null && !bp.isRuntime()) { 16910 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16911 + "non-runtime permission " + perm.info.name 16912 + " to runtime; keeping old protection level"); 16913 perm.info.protectionLevel = bp.protectionLevel; 16914 } 16915 } 16916 } 16917 } 16918 } 16919 } 16920 16921 if (systemApp) { 16922 if (onExternal) { 16923 // Abort update; system app can't be replaced with app on sdcard 16924 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16925 "Cannot install updates to system apps on sdcard"); 16926 return; 16927 } else if (instantApp) { 16928 // Abort update; system app can't be replaced with an instant app 16929 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16930 "Cannot update a system app with an instant app"); 16931 return; 16932 } 16933 } 16934 16935 if (args.move != null) { 16936 // We did an in-place move, so dex is ready to roll 16937 scanFlags |= SCAN_NO_DEX; 16938 scanFlags |= SCAN_MOVE; 16939 16940 synchronized (mPackages) { 16941 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16942 if (ps == null) { 16943 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16944 "Missing settings for moved package " + pkgName); 16945 } 16946 16947 // We moved the entire application as-is, so bring over the 16948 // previously derived ABI information. 16949 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16950 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16951 } 16952 16953 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16954 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16955 scanFlags |= SCAN_NO_DEX; 16956 16957 try { 16958 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16959 args.abiOverride : pkg.cpuAbiOverride); 16960 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16961 true /*extractLibs*/, mAppLib32InstallDir); 16962 } catch (PackageManagerException pme) { 16963 Slog.e(TAG, "Error deriving application ABI", pme); 16964 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16965 return; 16966 } 16967 16968 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16969 // Do not run PackageDexOptimizer through the local performDexOpt 16970 // method because `pkg` may not be in `mPackages` yet. 16971 // 16972 // Also, don't fail application installs if the dexopt step fails. 16973 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16974 null /* instructionSets */, false /* checkProfiles */, 16975 getCompilerFilterForReason(REASON_INSTALL), 16976 getOrCreateCompilerPackageStats(pkg), 16977 mDexManager.isUsedByOtherApps(pkg.packageName)); 16978 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16979 16980 // Notify BackgroundDexOptService that the package has been changed. 16981 // If this is an update of a package which used to fail to compile, 16982 // BDOS will remove it from its blacklist. 16983 // TODO: Layering violation 16984 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16985 } 16986 16987 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16988 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16989 return; 16990 } 16991 16992 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16993 16994 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16995 "installPackageLI")) { 16996 if (replace) { 16997 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16998 // Static libs have a synthetic package name containing the version 16999 // and cannot be updated as an update would get a new package name, 17000 // unless this is the exact same version code which is useful for 17001 // development. 17002 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17003 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17004 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17005 + "static-shared libs cannot be updated"); 17006 return; 17007 } 17008 } 17009 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17010 installerPackageName, res, args.installReason); 17011 } else { 17012 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17013 args.user, installerPackageName, volumeUuid, res, args.installReason); 17014 } 17015 } 17016 synchronized (mPackages) { 17017 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17018 if (ps != null) { 17019 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17020 ps.setUpdateAvailable(false /*updateAvailable*/); 17021 } 17022 17023 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17024 for (int i = 0; i < childCount; i++) { 17025 PackageParser.Package childPkg = pkg.childPackages.get(i); 17026 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17027 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17028 if (childPs != null) { 17029 childRes.newUsers = childPs.queryInstalledUsers( 17030 sUserManager.getUserIds(), true); 17031 } 17032 } 17033 17034 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17035 updateSequenceNumberLP(pkgName, res.newUsers); 17036 updateInstantAppInstallerLocked(); 17037 } 17038 } 17039 } 17040 17041 private void startIntentFilterVerifications(int userId, boolean replacing, 17042 PackageParser.Package pkg) { 17043 if (mIntentFilterVerifierComponent == null) { 17044 Slog.w(TAG, "No IntentFilter verification will not be done as " 17045 + "there is no IntentFilterVerifier available!"); 17046 return; 17047 } 17048 17049 final int verifierUid = getPackageUid( 17050 mIntentFilterVerifierComponent.getPackageName(), 17051 MATCH_DEBUG_TRIAGED_MISSING, 17052 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17053 17054 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17055 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17056 mHandler.sendMessage(msg); 17057 17058 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17059 for (int i = 0; i < childCount; i++) { 17060 PackageParser.Package childPkg = pkg.childPackages.get(i); 17061 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17062 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17063 mHandler.sendMessage(msg); 17064 } 17065 } 17066 17067 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17068 PackageParser.Package pkg) { 17069 int size = pkg.activities.size(); 17070 if (size == 0) { 17071 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17072 "No activity, so no need to verify any IntentFilter!"); 17073 return; 17074 } 17075 17076 final boolean hasDomainURLs = hasDomainURLs(pkg); 17077 if (!hasDomainURLs) { 17078 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17079 "No domain URLs, so no need to verify any IntentFilter!"); 17080 return; 17081 } 17082 17083 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17084 + " if any IntentFilter from the " + size 17085 + " Activities needs verification ..."); 17086 17087 int count = 0; 17088 final String packageName = pkg.packageName; 17089 17090 synchronized (mPackages) { 17091 // If this is a new install and we see that we've already run verification for this 17092 // package, we have nothing to do: it means the state was restored from backup. 17093 if (!replacing) { 17094 IntentFilterVerificationInfo ivi = 17095 mSettings.getIntentFilterVerificationLPr(packageName); 17096 if (ivi != null) { 17097 if (DEBUG_DOMAIN_VERIFICATION) { 17098 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17099 + ivi.getStatusString()); 17100 } 17101 return; 17102 } 17103 } 17104 17105 // If any filters need to be verified, then all need to be. 17106 boolean needToVerify = false; 17107 for (PackageParser.Activity a : pkg.activities) { 17108 for (ActivityIntentInfo filter : a.intents) { 17109 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17110 if (DEBUG_DOMAIN_VERIFICATION) { 17111 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17112 } 17113 needToVerify = true; 17114 break; 17115 } 17116 } 17117 } 17118 17119 if (needToVerify) { 17120 final int verificationId = mIntentFilterVerificationToken++; 17121 for (PackageParser.Activity a : pkg.activities) { 17122 for (ActivityIntentInfo filter : a.intents) { 17123 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17124 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17125 "Verification needed for IntentFilter:" + filter.toString()); 17126 mIntentFilterVerifier.addOneIntentFilterVerification( 17127 verifierUid, userId, verificationId, filter, packageName); 17128 count++; 17129 } 17130 } 17131 } 17132 } 17133 } 17134 17135 if (count > 0) { 17136 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17137 + " IntentFilter verification" + (count > 1 ? "s" : "") 17138 + " for userId:" + userId); 17139 mIntentFilterVerifier.startVerifications(userId); 17140 } else { 17141 if (DEBUG_DOMAIN_VERIFICATION) { 17142 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17143 } 17144 } 17145 } 17146 17147 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17148 final ComponentName cn = filter.activity.getComponentName(); 17149 final String packageName = cn.getPackageName(); 17150 17151 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17152 packageName); 17153 if (ivi == null) { 17154 return true; 17155 } 17156 int status = ivi.getStatus(); 17157 switch (status) { 17158 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17159 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17160 return true; 17161 17162 default: 17163 // Nothing to do 17164 return false; 17165 } 17166 } 17167 17168 private static boolean isMultiArch(ApplicationInfo info) { 17169 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17170 } 17171 17172 private static boolean isExternal(PackageParser.Package pkg) { 17173 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17174 } 17175 17176 private static boolean isExternal(PackageSetting ps) { 17177 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17178 } 17179 17180 private static boolean isSystemApp(PackageParser.Package pkg) { 17181 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17182 } 17183 17184 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17185 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17186 } 17187 17188 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17189 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17190 } 17191 17192 private static boolean isSystemApp(PackageSetting ps) { 17193 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17194 } 17195 17196 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17197 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17198 } 17199 17200 private int packageFlagsToInstallFlags(PackageSetting ps) { 17201 int installFlags = 0; 17202 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17203 // This existing package was an external ASEC install when we have 17204 // the external flag without a UUID 17205 installFlags |= PackageManager.INSTALL_EXTERNAL; 17206 } 17207 if (ps.isForwardLocked()) { 17208 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17209 } 17210 return installFlags; 17211 } 17212 17213 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17214 if (isExternal(pkg)) { 17215 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17216 return StorageManager.UUID_PRIMARY_PHYSICAL; 17217 } else { 17218 return pkg.volumeUuid; 17219 } 17220 } else { 17221 return StorageManager.UUID_PRIVATE_INTERNAL; 17222 } 17223 } 17224 17225 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17226 if (isExternal(pkg)) { 17227 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17228 return mSettings.getExternalVersion(); 17229 } else { 17230 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17231 } 17232 } else { 17233 return mSettings.getInternalVersion(); 17234 } 17235 } 17236 17237 private void deleteTempPackageFiles() { 17238 final FilenameFilter filter = new FilenameFilter() { 17239 public boolean accept(File dir, String name) { 17240 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17241 } 17242 }; 17243 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17244 file.delete(); 17245 } 17246 } 17247 17248 @Override 17249 public void deletePackageAsUser(String packageName, int versionCode, 17250 IPackageDeleteObserver observer, int userId, int flags) { 17251 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17252 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17253 } 17254 17255 @Override 17256 public void deletePackageVersioned(VersionedPackage versionedPackage, 17257 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17258 mContext.enforceCallingOrSelfPermission( 17259 android.Manifest.permission.DELETE_PACKAGES, null); 17260 Preconditions.checkNotNull(versionedPackage); 17261 Preconditions.checkNotNull(observer); 17262 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17263 PackageManager.VERSION_CODE_HIGHEST, 17264 Integer.MAX_VALUE, "versionCode must be >= -1"); 17265 17266 final String packageName = versionedPackage.getPackageName(); 17267 // TODO: We will change version code to long, so in the new API it is long 17268 final int versionCode = (int) versionedPackage.getVersionCode(); 17269 final String internalPackageName; 17270 synchronized (mPackages) { 17271 // Normalize package name to handle renamed packages and static libs 17272 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17273 // TODO: We will change version code to long, so in the new API it is long 17274 (int) versionedPackage.getVersionCode()); 17275 } 17276 17277 final int uid = Binder.getCallingUid(); 17278 if (!isOrphaned(internalPackageName) 17279 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17280 try { 17281 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17282 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17283 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17284 observer.onUserActionRequired(intent); 17285 } catch (RemoteException re) { 17286 } 17287 return; 17288 } 17289 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17290 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17291 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17292 mContext.enforceCallingOrSelfPermission( 17293 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17294 "deletePackage for user " + userId); 17295 } 17296 17297 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17298 try { 17299 observer.onPackageDeleted(packageName, 17300 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17301 } catch (RemoteException re) { 17302 } 17303 return; 17304 } 17305 17306 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17307 try { 17308 observer.onPackageDeleted(packageName, 17309 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17310 } catch (RemoteException re) { 17311 } 17312 return; 17313 } 17314 17315 if (DEBUG_REMOVE) { 17316 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17317 + " deleteAllUsers: " + deleteAllUsers + " version=" 17318 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17319 ? "VERSION_CODE_HIGHEST" : versionCode)); 17320 } 17321 // Queue up an async operation since the package deletion may take a little while. 17322 mHandler.post(new Runnable() { 17323 public void run() { 17324 mHandler.removeCallbacks(this); 17325 int returnCode; 17326 if (!deleteAllUsers) { 17327 returnCode = deletePackageX(internalPackageName, versionCode, 17328 userId, deleteFlags); 17329 } else { 17330 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17331 internalPackageName, users); 17332 // If nobody is blocking uninstall, proceed with delete for all users 17333 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17334 returnCode = deletePackageX(internalPackageName, versionCode, 17335 userId, deleteFlags); 17336 } else { 17337 // Otherwise uninstall individually for users with blockUninstalls=false 17338 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17339 for (int userId : users) { 17340 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17341 returnCode = deletePackageX(internalPackageName, versionCode, 17342 userId, userFlags); 17343 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17344 Slog.w(TAG, "Package delete failed for user " + userId 17345 + ", returnCode " + returnCode); 17346 } 17347 } 17348 } 17349 // The app has only been marked uninstalled for certain users. 17350 // We still need to report that delete was blocked 17351 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17352 } 17353 } 17354 try { 17355 observer.onPackageDeleted(packageName, returnCode, null); 17356 } catch (RemoteException e) { 17357 Log.i(TAG, "Observer no longer exists."); 17358 } //end catch 17359 } //end run 17360 }); 17361 } 17362 17363 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17364 if (pkg.staticSharedLibName != null) { 17365 return pkg.manifestPackageName; 17366 } 17367 return pkg.packageName; 17368 } 17369 17370 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17371 // Handle renamed packages 17372 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17373 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17374 17375 // Is this a static library? 17376 SparseArray<SharedLibraryEntry> versionedLib = 17377 mStaticLibsByDeclaringPackage.get(packageName); 17378 if (versionedLib == null || versionedLib.size() <= 0) { 17379 return packageName; 17380 } 17381 17382 // Figure out which lib versions the caller can see 17383 SparseIntArray versionsCallerCanSee = null; 17384 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17385 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17386 && callingAppId != Process.ROOT_UID) { 17387 versionsCallerCanSee = new SparseIntArray(); 17388 String libName = versionedLib.valueAt(0).info.getName(); 17389 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17390 if (uidPackages != null) { 17391 for (String uidPackage : uidPackages) { 17392 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17393 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17394 if (libIdx >= 0) { 17395 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17396 versionsCallerCanSee.append(libVersion, libVersion); 17397 } 17398 } 17399 } 17400 } 17401 17402 // Caller can see nothing - done 17403 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17404 return packageName; 17405 } 17406 17407 // Find the version the caller can see and the app version code 17408 SharedLibraryEntry highestVersion = null; 17409 final int versionCount = versionedLib.size(); 17410 for (int i = 0; i < versionCount; i++) { 17411 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17412 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17413 libEntry.info.getVersion()) < 0) { 17414 continue; 17415 } 17416 // TODO: We will change version code to long, so in the new API it is long 17417 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17418 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17419 if (libVersionCode == versionCode) { 17420 return libEntry.apk; 17421 } 17422 } else if (highestVersion == null) { 17423 highestVersion = libEntry; 17424 } else if (libVersionCode > highestVersion.info 17425 .getDeclaringPackage().getVersionCode()) { 17426 highestVersion = libEntry; 17427 } 17428 } 17429 17430 if (highestVersion != null) { 17431 return highestVersion.apk; 17432 } 17433 17434 return packageName; 17435 } 17436 17437 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17438 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17439 || callingUid == Process.SYSTEM_UID) { 17440 return true; 17441 } 17442 final int callingUserId = UserHandle.getUserId(callingUid); 17443 // If the caller installed the pkgName, then allow it to silently uninstall. 17444 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17445 return true; 17446 } 17447 17448 // Allow package verifier to silently uninstall. 17449 if (mRequiredVerifierPackage != null && 17450 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17451 return true; 17452 } 17453 17454 // Allow package uninstaller to silently uninstall. 17455 if (mRequiredUninstallerPackage != null && 17456 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17457 return true; 17458 } 17459 17460 // Allow storage manager to silently uninstall. 17461 if (mStorageManagerPackage != null && 17462 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17463 return true; 17464 } 17465 return false; 17466 } 17467 17468 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17469 int[] result = EMPTY_INT_ARRAY; 17470 for (int userId : userIds) { 17471 if (getBlockUninstallForUser(packageName, userId)) { 17472 result = ArrayUtils.appendInt(result, userId); 17473 } 17474 } 17475 return result; 17476 } 17477 17478 @Override 17479 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17480 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17481 } 17482 17483 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17484 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17485 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17486 try { 17487 if (dpm != null) { 17488 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17489 /* callingUserOnly =*/ false); 17490 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17491 : deviceOwnerComponentName.getPackageName(); 17492 // Does the package contains the device owner? 17493 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17494 // this check is probably not needed, since DO should be registered as a device 17495 // admin on some user too. (Original bug for this: b/17657954) 17496 if (packageName.equals(deviceOwnerPackageName)) { 17497 return true; 17498 } 17499 // Does it contain a device admin for any user? 17500 int[] users; 17501 if (userId == UserHandle.USER_ALL) { 17502 users = sUserManager.getUserIds(); 17503 } else { 17504 users = new int[]{userId}; 17505 } 17506 for (int i = 0; i < users.length; ++i) { 17507 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17508 return true; 17509 } 17510 } 17511 } 17512 } catch (RemoteException e) { 17513 } 17514 return false; 17515 } 17516 17517 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17518 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17519 } 17520 17521 /** 17522 * This method is an internal method that could be get invoked either 17523 * to delete an installed package or to clean up a failed installation. 17524 * After deleting an installed package, a broadcast is sent to notify any 17525 * listeners that the package has been removed. For cleaning up a failed 17526 * installation, the broadcast is not necessary since the package's 17527 * installation wouldn't have sent the initial broadcast either 17528 * The key steps in deleting a package are 17529 * deleting the package information in internal structures like mPackages, 17530 * deleting the packages base directories through installd 17531 * updating mSettings to reflect current status 17532 * persisting settings for later use 17533 * sending a broadcast if necessary 17534 */ 17535 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17536 final PackageRemovedInfo info = new PackageRemovedInfo(); 17537 final boolean res; 17538 17539 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17540 ? UserHandle.USER_ALL : userId; 17541 17542 if (isPackageDeviceAdmin(packageName, removeUser)) { 17543 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17544 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17545 } 17546 17547 PackageSetting uninstalledPs = null; 17548 PackageParser.Package pkg = null; 17549 17550 // for the uninstall-updates case and restricted profiles, remember the per- 17551 // user handle installed state 17552 int[] allUsers; 17553 synchronized (mPackages) { 17554 uninstalledPs = mSettings.mPackages.get(packageName); 17555 if (uninstalledPs == null) { 17556 Slog.w(TAG, "Not removing non-existent package " + packageName); 17557 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17558 } 17559 17560 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17561 && uninstalledPs.versionCode != versionCode) { 17562 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17563 + uninstalledPs.versionCode + " != " + versionCode); 17564 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17565 } 17566 17567 // Static shared libs can be declared by any package, so let us not 17568 // allow removing a package if it provides a lib others depend on. 17569 pkg = mPackages.get(packageName); 17570 if (pkg != null && pkg.staticSharedLibName != null) { 17571 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17572 pkg.staticSharedLibVersion); 17573 if (libEntry != null) { 17574 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17575 libEntry.info, 0, userId); 17576 if (!ArrayUtils.isEmpty(libClientPackages)) { 17577 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17578 + " hosting lib " + libEntry.info.getName() + " version " 17579 + libEntry.info.getVersion() + " used by " + libClientPackages); 17580 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17581 } 17582 } 17583 } 17584 17585 allUsers = sUserManager.getUserIds(); 17586 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17587 } 17588 17589 final int freezeUser; 17590 if (isUpdatedSystemApp(uninstalledPs) 17591 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17592 // We're downgrading a system app, which will apply to all users, so 17593 // freeze them all during the downgrade 17594 freezeUser = UserHandle.USER_ALL; 17595 } else { 17596 freezeUser = removeUser; 17597 } 17598 17599 synchronized (mInstallLock) { 17600 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17601 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17602 deleteFlags, "deletePackageX")) { 17603 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17604 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17605 } 17606 synchronized (mPackages) { 17607 if (res) { 17608 if (pkg != null) { 17609 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17610 } 17611 updateSequenceNumberLP(packageName, info.removedUsers); 17612 updateInstantAppInstallerLocked(); 17613 } 17614 } 17615 } 17616 17617 if (res) { 17618 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17619 info.sendPackageRemovedBroadcasts(killApp); 17620 info.sendSystemPackageUpdatedBroadcasts(); 17621 info.sendSystemPackageAppearedBroadcasts(); 17622 } 17623 // Force a gc here. 17624 Runtime.getRuntime().gc(); 17625 // Delete the resources here after sending the broadcast to let 17626 // other processes clean up before deleting resources. 17627 if (info.args != null) { 17628 synchronized (mInstallLock) { 17629 info.args.doPostDeleteLI(true); 17630 } 17631 } 17632 17633 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17634 } 17635 17636 class PackageRemovedInfo { 17637 String removedPackage; 17638 int uid = -1; 17639 int removedAppId = -1; 17640 int[] origUsers; 17641 int[] removedUsers = null; 17642 SparseArray<Integer> installReasons; 17643 boolean isRemovedPackageSystemUpdate = false; 17644 boolean isUpdate; 17645 boolean dataRemoved; 17646 boolean removedForAllUsers; 17647 boolean isStaticSharedLib; 17648 // Clean up resources deleted packages. 17649 InstallArgs args = null; 17650 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17651 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17652 17653 void sendPackageRemovedBroadcasts(boolean killApp) { 17654 sendPackageRemovedBroadcastInternal(killApp); 17655 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17656 for (int i = 0; i < childCount; i++) { 17657 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17658 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17659 } 17660 } 17661 17662 void sendSystemPackageUpdatedBroadcasts() { 17663 if (isRemovedPackageSystemUpdate) { 17664 sendSystemPackageUpdatedBroadcastsInternal(); 17665 final int childCount = (removedChildPackages != null) 17666 ? removedChildPackages.size() : 0; 17667 for (int i = 0; i < childCount; i++) { 17668 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17669 if (childInfo.isRemovedPackageSystemUpdate) { 17670 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17671 } 17672 } 17673 } 17674 } 17675 17676 void sendSystemPackageAppearedBroadcasts() { 17677 final int packageCount = (appearedChildPackages != null) 17678 ? appearedChildPackages.size() : 0; 17679 for (int i = 0; i < packageCount; i++) { 17680 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17681 sendPackageAddedForNewUsers(installedInfo.name, true, 17682 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17683 } 17684 } 17685 17686 private void sendSystemPackageUpdatedBroadcastsInternal() { 17687 Bundle extras = new Bundle(2); 17688 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17689 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17690 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17691 extras, 0, null, null, null); 17692 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17693 extras, 0, null, null, null); 17694 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17695 null, 0, removedPackage, null, null); 17696 } 17697 17698 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17699 // Don't send static shared library removal broadcasts as these 17700 // libs are visible only the the apps that depend on them an one 17701 // cannot remove the library if it has a dependency. 17702 if (isStaticSharedLib) { 17703 return; 17704 } 17705 Bundle extras = new Bundle(2); 17706 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17707 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17708 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17709 if (isUpdate || isRemovedPackageSystemUpdate) { 17710 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17711 } 17712 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17713 if (removedPackage != null) { 17714 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17715 extras, 0, null, null, removedUsers); 17716 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17717 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17718 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17719 null, null, removedUsers); 17720 } 17721 } 17722 if (removedAppId >= 0) { 17723 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17724 removedUsers); 17725 } 17726 } 17727 } 17728 17729 /* 17730 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17731 * flag is not set, the data directory is removed as well. 17732 * make sure this flag is set for partially installed apps. If not its meaningless to 17733 * delete a partially installed application. 17734 */ 17735 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17736 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17737 String packageName = ps.name; 17738 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17739 // Retrieve object to delete permissions for shared user later on 17740 final PackageParser.Package deletedPkg; 17741 final PackageSetting deletedPs; 17742 // reader 17743 synchronized (mPackages) { 17744 deletedPkg = mPackages.get(packageName); 17745 deletedPs = mSettings.mPackages.get(packageName); 17746 if (outInfo != null) { 17747 outInfo.removedPackage = packageName; 17748 outInfo.isStaticSharedLib = deletedPkg != null 17749 && deletedPkg.staticSharedLibName != null; 17750 outInfo.removedUsers = deletedPs != null 17751 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17752 : null; 17753 } 17754 } 17755 17756 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17757 17758 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17759 final PackageParser.Package resolvedPkg; 17760 if (deletedPkg != null) { 17761 resolvedPkg = deletedPkg; 17762 } else { 17763 // We don't have a parsed package when it lives on an ejected 17764 // adopted storage device, so fake something together 17765 resolvedPkg = new PackageParser.Package(ps.name); 17766 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17767 } 17768 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17769 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17770 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17771 if (outInfo != null) { 17772 outInfo.dataRemoved = true; 17773 } 17774 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17775 } 17776 17777 int removedAppId = -1; 17778 17779 // writer 17780 synchronized (mPackages) { 17781 boolean installedStateChanged = false; 17782 if (deletedPs != null) { 17783 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17784 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17785 clearDefaultBrowserIfNeeded(packageName); 17786 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17787 removedAppId = mSettings.removePackageLPw(packageName); 17788 if (outInfo != null) { 17789 outInfo.removedAppId = removedAppId; 17790 } 17791 updatePermissionsLPw(deletedPs.name, null, 0); 17792 if (deletedPs.sharedUser != null) { 17793 // Remove permissions associated with package. Since runtime 17794 // permissions are per user we have to kill the removed package 17795 // or packages running under the shared user of the removed 17796 // package if revoking the permissions requested only by the removed 17797 // package is successful and this causes a change in gids. 17798 for (int userId : UserManagerService.getInstance().getUserIds()) { 17799 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17800 userId); 17801 if (userIdToKill == UserHandle.USER_ALL 17802 || userIdToKill >= UserHandle.USER_SYSTEM) { 17803 // If gids changed for this user, kill all affected packages. 17804 mHandler.post(new Runnable() { 17805 @Override 17806 public void run() { 17807 // This has to happen with no lock held. 17808 killApplication(deletedPs.name, deletedPs.appId, 17809 KILL_APP_REASON_GIDS_CHANGED); 17810 } 17811 }); 17812 break; 17813 } 17814 } 17815 } 17816 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17817 } 17818 // make sure to preserve per-user disabled state if this removal was just 17819 // a downgrade of a system app to the factory package 17820 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17821 if (DEBUG_REMOVE) { 17822 Slog.d(TAG, "Propagating install state across downgrade"); 17823 } 17824 for (int userId : allUserHandles) { 17825 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17826 if (DEBUG_REMOVE) { 17827 Slog.d(TAG, " user " + userId + " => " + installed); 17828 } 17829 if (installed != ps.getInstalled(userId)) { 17830 installedStateChanged = true; 17831 } 17832 ps.setInstalled(installed, userId); 17833 } 17834 } 17835 } 17836 // can downgrade to reader 17837 if (writeSettings) { 17838 // Save settings now 17839 mSettings.writeLPr(); 17840 } 17841 if (installedStateChanged) { 17842 mSettings.writeKernelMappingLPr(ps); 17843 } 17844 } 17845 if (removedAppId != -1) { 17846 // A user ID was deleted here. Go through all users and remove it 17847 // from KeyStore. 17848 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17849 } 17850 } 17851 17852 static boolean locationIsPrivileged(File path) { 17853 try { 17854 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17855 .getCanonicalPath(); 17856 return path.getCanonicalPath().startsWith(privilegedAppDir); 17857 } catch (IOException e) { 17858 Slog.e(TAG, "Unable to access code path " + path); 17859 } 17860 return false; 17861 } 17862 17863 /* 17864 * Tries to delete system package. 17865 */ 17866 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17867 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17868 boolean writeSettings) { 17869 if (deletedPs.parentPackageName != null) { 17870 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17871 return false; 17872 } 17873 17874 final boolean applyUserRestrictions 17875 = (allUserHandles != null) && (outInfo.origUsers != null); 17876 final PackageSetting disabledPs; 17877 // Confirm if the system package has been updated 17878 // An updated system app can be deleted. This will also have to restore 17879 // the system pkg from system partition 17880 // reader 17881 synchronized (mPackages) { 17882 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17883 } 17884 17885 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17886 + " disabledPs=" + disabledPs); 17887 17888 if (disabledPs == null) { 17889 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17890 return false; 17891 } else if (DEBUG_REMOVE) { 17892 Slog.d(TAG, "Deleting system pkg from data partition"); 17893 } 17894 17895 if (DEBUG_REMOVE) { 17896 if (applyUserRestrictions) { 17897 Slog.d(TAG, "Remembering install states:"); 17898 for (int userId : allUserHandles) { 17899 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17900 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17901 } 17902 } 17903 } 17904 17905 // Delete the updated package 17906 outInfo.isRemovedPackageSystemUpdate = true; 17907 if (outInfo.removedChildPackages != null) { 17908 final int childCount = (deletedPs.childPackageNames != null) 17909 ? deletedPs.childPackageNames.size() : 0; 17910 for (int i = 0; i < childCount; i++) { 17911 String childPackageName = deletedPs.childPackageNames.get(i); 17912 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17913 .contains(childPackageName)) { 17914 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17915 childPackageName); 17916 if (childInfo != null) { 17917 childInfo.isRemovedPackageSystemUpdate = true; 17918 } 17919 } 17920 } 17921 } 17922 17923 if (disabledPs.versionCode < deletedPs.versionCode) { 17924 // Delete data for downgrades 17925 flags &= ~PackageManager.DELETE_KEEP_DATA; 17926 } else { 17927 // Preserve data by setting flag 17928 flags |= PackageManager.DELETE_KEEP_DATA; 17929 } 17930 17931 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17932 outInfo, writeSettings, disabledPs.pkg); 17933 if (!ret) { 17934 return false; 17935 } 17936 17937 // writer 17938 synchronized (mPackages) { 17939 // Reinstate the old system package 17940 enableSystemPackageLPw(disabledPs.pkg); 17941 // Remove any native libraries from the upgraded package. 17942 removeNativeBinariesLI(deletedPs); 17943 } 17944 17945 // Install the system package 17946 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17947 int parseFlags = mDefParseFlags 17948 | PackageParser.PARSE_MUST_BE_APK 17949 | PackageParser.PARSE_IS_SYSTEM 17950 | PackageParser.PARSE_IS_SYSTEM_DIR; 17951 if (locationIsPrivileged(disabledPs.codePath)) { 17952 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17953 } 17954 17955 final PackageParser.Package newPkg; 17956 try { 17957 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17958 0 /* currentTime */, null); 17959 } catch (PackageManagerException e) { 17960 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17961 + e.getMessage()); 17962 return false; 17963 } 17964 17965 try { 17966 // update shared libraries for the newly re-installed system package 17967 updateSharedLibrariesLPr(newPkg, null); 17968 } catch (PackageManagerException e) { 17969 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17970 } 17971 17972 prepareAppDataAfterInstallLIF(newPkg); 17973 17974 // writer 17975 synchronized (mPackages) { 17976 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17977 17978 // Propagate the permissions state as we do not want to drop on the floor 17979 // runtime permissions. The update permissions method below will take 17980 // care of removing obsolete permissions and grant install permissions. 17981 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17982 updatePermissionsLPw(newPkg.packageName, newPkg, 17983 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17984 17985 if (applyUserRestrictions) { 17986 boolean installedStateChanged = false; 17987 if (DEBUG_REMOVE) { 17988 Slog.d(TAG, "Propagating install state across reinstall"); 17989 } 17990 for (int userId : allUserHandles) { 17991 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17992 if (DEBUG_REMOVE) { 17993 Slog.d(TAG, " user " + userId + " => " + installed); 17994 } 17995 if (installed != ps.getInstalled(userId)) { 17996 installedStateChanged = true; 17997 } 17998 ps.setInstalled(installed, userId); 17999 18000 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18001 } 18002 // Regardless of writeSettings we need to ensure that this restriction 18003 // state propagation is persisted 18004 mSettings.writeAllUsersPackageRestrictionsLPr(); 18005 if (installedStateChanged) { 18006 mSettings.writeKernelMappingLPr(ps); 18007 } 18008 } 18009 // can downgrade to reader here 18010 if (writeSettings) { 18011 mSettings.writeLPr(); 18012 } 18013 } 18014 return true; 18015 } 18016 18017 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18018 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18019 PackageRemovedInfo outInfo, boolean writeSettings, 18020 PackageParser.Package replacingPackage) { 18021 synchronized (mPackages) { 18022 if (outInfo != null) { 18023 outInfo.uid = ps.appId; 18024 } 18025 18026 if (outInfo != null && outInfo.removedChildPackages != null) { 18027 final int childCount = (ps.childPackageNames != null) 18028 ? ps.childPackageNames.size() : 0; 18029 for (int i = 0; i < childCount; i++) { 18030 String childPackageName = ps.childPackageNames.get(i); 18031 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18032 if (childPs == null) { 18033 return false; 18034 } 18035 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18036 childPackageName); 18037 if (childInfo != null) { 18038 childInfo.uid = childPs.appId; 18039 } 18040 } 18041 } 18042 } 18043 18044 // Delete package data from internal structures and also remove data if flag is set 18045 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18046 18047 // Delete the child packages data 18048 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18049 for (int i = 0; i < childCount; i++) { 18050 PackageSetting childPs; 18051 synchronized (mPackages) { 18052 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18053 } 18054 if (childPs != null) { 18055 PackageRemovedInfo childOutInfo = (outInfo != null 18056 && outInfo.removedChildPackages != null) 18057 ? outInfo.removedChildPackages.get(childPs.name) : null; 18058 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18059 && (replacingPackage != null 18060 && !replacingPackage.hasChildPackage(childPs.name)) 18061 ? flags & ~DELETE_KEEP_DATA : flags; 18062 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18063 deleteFlags, writeSettings); 18064 } 18065 } 18066 18067 // Delete application code and resources only for parent packages 18068 if (ps.parentPackageName == null) { 18069 if (deleteCodeAndResources && (outInfo != null)) { 18070 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18071 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18072 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18073 } 18074 } 18075 18076 return true; 18077 } 18078 18079 @Override 18080 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18081 int userId) { 18082 mContext.enforceCallingOrSelfPermission( 18083 android.Manifest.permission.DELETE_PACKAGES, null); 18084 synchronized (mPackages) { 18085 PackageSetting ps = mSettings.mPackages.get(packageName); 18086 if (ps == null) { 18087 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18088 return false; 18089 } 18090 // Cannot block uninstall of static shared libs as they are 18091 // considered a part of the using app (emulating static linking). 18092 // Also static libs are installed always on internal storage. 18093 PackageParser.Package pkg = mPackages.get(packageName); 18094 if (pkg != null && pkg.staticSharedLibName != null) { 18095 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18096 + " providing static shared library: " + pkg.staticSharedLibName); 18097 return false; 18098 } 18099 if (!ps.getInstalled(userId)) { 18100 // Can't block uninstall for an app that is not installed or enabled. 18101 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18102 return false; 18103 } 18104 ps.setBlockUninstall(blockUninstall, userId); 18105 mSettings.writePackageRestrictionsLPr(userId); 18106 } 18107 return true; 18108 } 18109 18110 @Override 18111 public boolean getBlockUninstallForUser(String packageName, int userId) { 18112 synchronized (mPackages) { 18113 PackageSetting ps = mSettings.mPackages.get(packageName); 18114 if (ps == null) { 18115 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18116 return false; 18117 } 18118 return ps.getBlockUninstall(userId); 18119 } 18120 } 18121 18122 @Override 18123 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18124 int callingUid = Binder.getCallingUid(); 18125 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18126 throw new SecurityException( 18127 "setRequiredForSystemUser can only be run by the system or root"); 18128 } 18129 synchronized (mPackages) { 18130 PackageSetting ps = mSettings.mPackages.get(packageName); 18131 if (ps == null) { 18132 Log.w(TAG, "Package doesn't exist: " + packageName); 18133 return false; 18134 } 18135 if (systemUserApp) { 18136 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18137 } else { 18138 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18139 } 18140 mSettings.writeLPr(); 18141 } 18142 return true; 18143 } 18144 18145 /* 18146 * This method handles package deletion in general 18147 */ 18148 private boolean deletePackageLIF(String packageName, UserHandle user, 18149 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18150 PackageRemovedInfo outInfo, boolean writeSettings, 18151 PackageParser.Package replacingPackage) { 18152 if (packageName == null) { 18153 Slog.w(TAG, "Attempt to delete null packageName."); 18154 return false; 18155 } 18156 18157 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18158 18159 PackageSetting ps; 18160 synchronized (mPackages) { 18161 ps = mSettings.mPackages.get(packageName); 18162 if (ps == null) { 18163 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18164 return false; 18165 } 18166 18167 if (ps.parentPackageName != null && (!isSystemApp(ps) 18168 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18169 if (DEBUG_REMOVE) { 18170 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18171 + ((user == null) ? UserHandle.USER_ALL : user)); 18172 } 18173 final int removedUserId = (user != null) ? user.getIdentifier() 18174 : UserHandle.USER_ALL; 18175 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18176 return false; 18177 } 18178 markPackageUninstalledForUserLPw(ps, user); 18179 scheduleWritePackageRestrictionsLocked(user); 18180 return true; 18181 } 18182 } 18183 18184 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18185 && user.getIdentifier() != UserHandle.USER_ALL)) { 18186 // The caller is asking that the package only be deleted for a single 18187 // user. To do this, we just mark its uninstalled state and delete 18188 // its data. If this is a system app, we only allow this to happen if 18189 // they have set the special DELETE_SYSTEM_APP which requests different 18190 // semantics than normal for uninstalling system apps. 18191 markPackageUninstalledForUserLPw(ps, user); 18192 18193 if (!isSystemApp(ps)) { 18194 // Do not uninstall the APK if an app should be cached 18195 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18196 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18197 // Other user still have this package installed, so all 18198 // we need to do is clear this user's data and save that 18199 // it is uninstalled. 18200 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18201 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18202 return false; 18203 } 18204 scheduleWritePackageRestrictionsLocked(user); 18205 return true; 18206 } else { 18207 // We need to set it back to 'installed' so the uninstall 18208 // broadcasts will be sent correctly. 18209 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18210 ps.setInstalled(true, user.getIdentifier()); 18211 mSettings.writeKernelMappingLPr(ps); 18212 } 18213 } else { 18214 // This is a system app, so we assume that the 18215 // other users still have this package installed, so all 18216 // we need to do is clear this user's data and save that 18217 // it is uninstalled. 18218 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18219 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18220 return false; 18221 } 18222 scheduleWritePackageRestrictionsLocked(user); 18223 return true; 18224 } 18225 } 18226 18227 // If we are deleting a composite package for all users, keep track 18228 // of result for each child. 18229 if (ps.childPackageNames != null && outInfo != null) { 18230 synchronized (mPackages) { 18231 final int childCount = ps.childPackageNames.size(); 18232 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18233 for (int i = 0; i < childCount; i++) { 18234 String childPackageName = ps.childPackageNames.get(i); 18235 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18236 childInfo.removedPackage = childPackageName; 18237 outInfo.removedChildPackages.put(childPackageName, childInfo); 18238 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18239 if (childPs != null) { 18240 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18241 } 18242 } 18243 } 18244 } 18245 18246 boolean ret = false; 18247 if (isSystemApp(ps)) { 18248 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18249 // When an updated system application is deleted we delete the existing resources 18250 // as well and fall back to existing code in system partition 18251 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18252 } else { 18253 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18254 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18255 outInfo, writeSettings, replacingPackage); 18256 } 18257 18258 // Take a note whether we deleted the package for all users 18259 if (outInfo != null) { 18260 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18261 if (outInfo.removedChildPackages != null) { 18262 synchronized (mPackages) { 18263 final int childCount = outInfo.removedChildPackages.size(); 18264 for (int i = 0; i < childCount; i++) { 18265 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18266 if (childInfo != null) { 18267 childInfo.removedForAllUsers = mPackages.get( 18268 childInfo.removedPackage) == null; 18269 } 18270 } 18271 } 18272 } 18273 // If we uninstalled an update to a system app there may be some 18274 // child packages that appeared as they are declared in the system 18275 // app but were not declared in the update. 18276 if (isSystemApp(ps)) { 18277 synchronized (mPackages) { 18278 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18279 final int childCount = (updatedPs.childPackageNames != null) 18280 ? updatedPs.childPackageNames.size() : 0; 18281 for (int i = 0; i < childCount; i++) { 18282 String childPackageName = updatedPs.childPackageNames.get(i); 18283 if (outInfo.removedChildPackages == null 18284 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18285 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18286 if (childPs == null) { 18287 continue; 18288 } 18289 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18290 installRes.name = childPackageName; 18291 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18292 installRes.pkg = mPackages.get(childPackageName); 18293 installRes.uid = childPs.pkg.applicationInfo.uid; 18294 if (outInfo.appearedChildPackages == null) { 18295 outInfo.appearedChildPackages = new ArrayMap<>(); 18296 } 18297 outInfo.appearedChildPackages.put(childPackageName, installRes); 18298 } 18299 } 18300 } 18301 } 18302 } 18303 18304 return ret; 18305 } 18306 18307 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18308 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18309 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18310 for (int nextUserId : userIds) { 18311 if (DEBUG_REMOVE) { 18312 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18313 } 18314 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18315 false /*installed*/, 18316 true /*stopped*/, 18317 true /*notLaunched*/, 18318 false /*hidden*/, 18319 false /*suspended*/, 18320 false /*instantApp*/, 18321 null /*lastDisableAppCaller*/, 18322 null /*enabledComponents*/, 18323 null /*disabledComponents*/, 18324 false /*blockUninstall*/, 18325 ps.readUserState(nextUserId).domainVerificationStatus, 18326 0, PackageManager.INSTALL_REASON_UNKNOWN); 18327 } 18328 mSettings.writeKernelMappingLPr(ps); 18329 } 18330 18331 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18332 PackageRemovedInfo outInfo) { 18333 final PackageParser.Package pkg; 18334 synchronized (mPackages) { 18335 pkg = mPackages.get(ps.name); 18336 } 18337 18338 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18339 : new int[] {userId}; 18340 for (int nextUserId : userIds) { 18341 if (DEBUG_REMOVE) { 18342 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18343 + nextUserId); 18344 } 18345 18346 destroyAppDataLIF(pkg, userId, 18347 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18348 destroyAppProfilesLIF(pkg, userId); 18349 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18350 schedulePackageCleaning(ps.name, nextUserId, false); 18351 synchronized (mPackages) { 18352 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18353 scheduleWritePackageRestrictionsLocked(nextUserId); 18354 } 18355 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18356 } 18357 } 18358 18359 if (outInfo != null) { 18360 outInfo.removedPackage = ps.name; 18361 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18362 outInfo.removedAppId = ps.appId; 18363 outInfo.removedUsers = userIds; 18364 } 18365 18366 return true; 18367 } 18368 18369 private final class ClearStorageConnection implements ServiceConnection { 18370 IMediaContainerService mContainerService; 18371 18372 @Override 18373 public void onServiceConnected(ComponentName name, IBinder service) { 18374 synchronized (this) { 18375 mContainerService = IMediaContainerService.Stub 18376 .asInterface(Binder.allowBlocking(service)); 18377 notifyAll(); 18378 } 18379 } 18380 18381 @Override 18382 public void onServiceDisconnected(ComponentName name) { 18383 } 18384 } 18385 18386 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18387 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18388 18389 final boolean mounted; 18390 if (Environment.isExternalStorageEmulated()) { 18391 mounted = true; 18392 } else { 18393 final String status = Environment.getExternalStorageState(); 18394 18395 mounted = status.equals(Environment.MEDIA_MOUNTED) 18396 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18397 } 18398 18399 if (!mounted) { 18400 return; 18401 } 18402 18403 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18404 int[] users; 18405 if (userId == UserHandle.USER_ALL) { 18406 users = sUserManager.getUserIds(); 18407 } else { 18408 users = new int[] { userId }; 18409 } 18410 final ClearStorageConnection conn = new ClearStorageConnection(); 18411 if (mContext.bindServiceAsUser( 18412 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18413 try { 18414 for (int curUser : users) { 18415 long timeout = SystemClock.uptimeMillis() + 5000; 18416 synchronized (conn) { 18417 long now; 18418 while (conn.mContainerService == null && 18419 (now = SystemClock.uptimeMillis()) < timeout) { 18420 try { 18421 conn.wait(timeout - now); 18422 } catch (InterruptedException e) { 18423 } 18424 } 18425 } 18426 if (conn.mContainerService == null) { 18427 return; 18428 } 18429 18430 final UserEnvironment userEnv = new UserEnvironment(curUser); 18431 clearDirectory(conn.mContainerService, 18432 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18433 if (allData) { 18434 clearDirectory(conn.mContainerService, 18435 userEnv.buildExternalStorageAppDataDirs(packageName)); 18436 clearDirectory(conn.mContainerService, 18437 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18438 } 18439 } 18440 } finally { 18441 mContext.unbindService(conn); 18442 } 18443 } 18444 } 18445 18446 @Override 18447 public void clearApplicationProfileData(String packageName) { 18448 enforceSystemOrRoot("Only the system can clear all profile data"); 18449 18450 final PackageParser.Package pkg; 18451 synchronized (mPackages) { 18452 pkg = mPackages.get(packageName); 18453 } 18454 18455 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18456 synchronized (mInstallLock) { 18457 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18458 } 18459 } 18460 } 18461 18462 @Override 18463 public void clearApplicationUserData(final String packageName, 18464 final IPackageDataObserver observer, final int userId) { 18465 mContext.enforceCallingOrSelfPermission( 18466 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18467 18468 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18469 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18470 18471 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18472 throw new SecurityException("Cannot clear data for a protected package: " 18473 + packageName); 18474 } 18475 // Queue up an async operation since the package deletion may take a little while. 18476 mHandler.post(new Runnable() { 18477 public void run() { 18478 mHandler.removeCallbacks(this); 18479 final boolean succeeded; 18480 try (PackageFreezer freezer = freezePackage(packageName, 18481 "clearApplicationUserData")) { 18482 synchronized (mInstallLock) { 18483 succeeded = clearApplicationUserDataLIF(packageName, userId); 18484 } 18485 clearExternalStorageDataSync(packageName, userId, true); 18486 synchronized (mPackages) { 18487 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18488 packageName, userId); 18489 } 18490 } 18491 if (succeeded) { 18492 // invoke DeviceStorageMonitor's update method to clear any notifications 18493 DeviceStorageMonitorInternal dsm = LocalServices 18494 .getService(DeviceStorageMonitorInternal.class); 18495 if (dsm != null) { 18496 dsm.checkMemory(); 18497 } 18498 } 18499 if(observer != null) { 18500 try { 18501 observer.onRemoveCompleted(packageName, succeeded); 18502 } catch (RemoteException e) { 18503 Log.i(TAG, "Observer no longer exists."); 18504 } 18505 } //end if observer 18506 } //end run 18507 }); 18508 } 18509 18510 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18511 if (packageName == null) { 18512 Slog.w(TAG, "Attempt to delete null packageName."); 18513 return false; 18514 } 18515 18516 // Try finding details about the requested package 18517 PackageParser.Package pkg; 18518 synchronized (mPackages) { 18519 pkg = mPackages.get(packageName); 18520 if (pkg == null) { 18521 final PackageSetting ps = mSettings.mPackages.get(packageName); 18522 if (ps != null) { 18523 pkg = ps.pkg; 18524 } 18525 } 18526 18527 if (pkg == null) { 18528 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18529 return false; 18530 } 18531 18532 PackageSetting ps = (PackageSetting) pkg.mExtras; 18533 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18534 } 18535 18536 clearAppDataLIF(pkg, userId, 18537 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18538 18539 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18540 removeKeystoreDataIfNeeded(userId, appId); 18541 18542 UserManagerInternal umInternal = getUserManagerInternal(); 18543 final int flags; 18544 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18545 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18546 } else if (umInternal.isUserRunning(userId)) { 18547 flags = StorageManager.FLAG_STORAGE_DE; 18548 } else { 18549 flags = 0; 18550 } 18551 prepareAppDataContentsLIF(pkg, userId, flags); 18552 18553 return true; 18554 } 18555 18556 /** 18557 * Reverts user permission state changes (permissions and flags) in 18558 * all packages for a given user. 18559 * 18560 * @param userId The device user for which to do a reset. 18561 */ 18562 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18563 final int packageCount = mPackages.size(); 18564 for (int i = 0; i < packageCount; i++) { 18565 PackageParser.Package pkg = mPackages.valueAt(i); 18566 PackageSetting ps = (PackageSetting) pkg.mExtras; 18567 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18568 } 18569 } 18570 18571 private void resetNetworkPolicies(int userId) { 18572 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18573 } 18574 18575 /** 18576 * Reverts user permission state changes (permissions and flags). 18577 * 18578 * @param ps The package for which to reset. 18579 * @param userId The device user for which to do a reset. 18580 */ 18581 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18582 final PackageSetting ps, final int userId) { 18583 if (ps.pkg == null) { 18584 return; 18585 } 18586 18587 // These are flags that can change base on user actions. 18588 final int userSettableMask = FLAG_PERMISSION_USER_SET 18589 | FLAG_PERMISSION_USER_FIXED 18590 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18591 | FLAG_PERMISSION_REVIEW_REQUIRED; 18592 18593 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18594 | FLAG_PERMISSION_POLICY_FIXED; 18595 18596 boolean writeInstallPermissions = false; 18597 boolean writeRuntimePermissions = false; 18598 18599 final int permissionCount = ps.pkg.requestedPermissions.size(); 18600 for (int i = 0; i < permissionCount; i++) { 18601 String permission = ps.pkg.requestedPermissions.get(i); 18602 18603 BasePermission bp = mSettings.mPermissions.get(permission); 18604 if (bp == null) { 18605 continue; 18606 } 18607 18608 // If shared user we just reset the state to which only this app contributed. 18609 if (ps.sharedUser != null) { 18610 boolean used = false; 18611 final int packageCount = ps.sharedUser.packages.size(); 18612 for (int j = 0; j < packageCount; j++) { 18613 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18614 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18615 && pkg.pkg.requestedPermissions.contains(permission)) { 18616 used = true; 18617 break; 18618 } 18619 } 18620 if (used) { 18621 continue; 18622 } 18623 } 18624 18625 PermissionsState permissionsState = ps.getPermissionsState(); 18626 18627 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18628 18629 // Always clear the user settable flags. 18630 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18631 bp.name) != null; 18632 // If permission review is enabled and this is a legacy app, mark the 18633 // permission as requiring a review as this is the initial state. 18634 int flags = 0; 18635 if (mPermissionReviewRequired 18636 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18637 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18638 } 18639 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18640 if (hasInstallState) { 18641 writeInstallPermissions = true; 18642 } else { 18643 writeRuntimePermissions = true; 18644 } 18645 } 18646 18647 // Below is only runtime permission handling. 18648 if (!bp.isRuntime()) { 18649 continue; 18650 } 18651 18652 // Never clobber system or policy. 18653 if ((oldFlags & policyOrSystemFlags) != 0) { 18654 continue; 18655 } 18656 18657 // If this permission was granted by default, make sure it is. 18658 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18659 if (permissionsState.grantRuntimePermission(bp, userId) 18660 != PERMISSION_OPERATION_FAILURE) { 18661 writeRuntimePermissions = true; 18662 } 18663 // If permission review is enabled the permissions for a legacy apps 18664 // are represented as constantly granted runtime ones, so don't revoke. 18665 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18666 // Otherwise, reset the permission. 18667 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18668 switch (revokeResult) { 18669 case PERMISSION_OPERATION_SUCCESS: 18670 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18671 writeRuntimePermissions = true; 18672 final int appId = ps.appId; 18673 mHandler.post(new Runnable() { 18674 @Override 18675 public void run() { 18676 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18677 } 18678 }); 18679 } break; 18680 } 18681 } 18682 } 18683 18684 // Synchronously write as we are taking permissions away. 18685 if (writeRuntimePermissions) { 18686 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18687 } 18688 18689 // Synchronously write as we are taking permissions away. 18690 if (writeInstallPermissions) { 18691 mSettings.writeLPr(); 18692 } 18693 } 18694 18695 /** 18696 * Remove entries from the keystore daemon. Will only remove it if the 18697 * {@code appId} is valid. 18698 */ 18699 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18700 if (appId < 0) { 18701 return; 18702 } 18703 18704 final KeyStore keyStore = KeyStore.getInstance(); 18705 if (keyStore != null) { 18706 if (userId == UserHandle.USER_ALL) { 18707 for (final int individual : sUserManager.getUserIds()) { 18708 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18709 } 18710 } else { 18711 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18712 } 18713 } else { 18714 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18715 } 18716 } 18717 18718 @Override 18719 public void deleteApplicationCacheFiles(final String packageName, 18720 final IPackageDataObserver observer) { 18721 final int userId = UserHandle.getCallingUserId(); 18722 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18723 } 18724 18725 @Override 18726 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18727 final IPackageDataObserver observer) { 18728 mContext.enforceCallingOrSelfPermission( 18729 android.Manifest.permission.DELETE_CACHE_FILES, null); 18730 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18731 /* requireFullPermission= */ true, /* checkShell= */ false, 18732 "delete application cache files"); 18733 18734 final PackageParser.Package pkg; 18735 synchronized (mPackages) { 18736 pkg = mPackages.get(packageName); 18737 } 18738 18739 // Queue up an async operation since the package deletion may take a little while. 18740 mHandler.post(new Runnable() { 18741 public void run() { 18742 synchronized (mInstallLock) { 18743 final int flags = StorageManager.FLAG_STORAGE_DE 18744 | StorageManager.FLAG_STORAGE_CE; 18745 // We're only clearing cache files, so we don't care if the 18746 // app is unfrozen and still able to run 18747 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18748 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18749 } 18750 clearExternalStorageDataSync(packageName, userId, false); 18751 if (observer != null) { 18752 try { 18753 observer.onRemoveCompleted(packageName, true); 18754 } catch (RemoteException e) { 18755 Log.i(TAG, "Observer no longer exists."); 18756 } 18757 } 18758 } 18759 }); 18760 } 18761 18762 @Override 18763 public void getPackageSizeInfo(final String packageName, int userHandle, 18764 final IPackageStatsObserver observer) { 18765 throw new UnsupportedOperationException( 18766 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18767 } 18768 18769 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18770 final PackageSetting ps; 18771 synchronized (mPackages) { 18772 ps = mSettings.mPackages.get(packageName); 18773 if (ps == null) { 18774 Slog.w(TAG, "Failed to find settings for " + packageName); 18775 return false; 18776 } 18777 } 18778 18779 final String[] packageNames = { packageName }; 18780 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18781 final String[] codePaths = { ps.codePathString }; 18782 18783 try { 18784 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18785 ps.appId, ceDataInodes, codePaths, stats); 18786 18787 // For now, ignore code size of packages on system partition 18788 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18789 stats.codeSize = 0; 18790 } 18791 18792 // External clients expect these to be tracked separately 18793 stats.dataSize -= stats.cacheSize; 18794 18795 } catch (InstallerException e) { 18796 Slog.w(TAG, String.valueOf(e)); 18797 return false; 18798 } 18799 18800 return true; 18801 } 18802 18803 private int getUidTargetSdkVersionLockedLPr(int uid) { 18804 Object obj = mSettings.getUserIdLPr(uid); 18805 if (obj instanceof SharedUserSetting) { 18806 final SharedUserSetting sus = (SharedUserSetting) obj; 18807 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18808 final Iterator<PackageSetting> it = sus.packages.iterator(); 18809 while (it.hasNext()) { 18810 final PackageSetting ps = it.next(); 18811 if (ps.pkg != null) { 18812 int v = ps.pkg.applicationInfo.targetSdkVersion; 18813 if (v < vers) vers = v; 18814 } 18815 } 18816 return vers; 18817 } else if (obj instanceof PackageSetting) { 18818 final PackageSetting ps = (PackageSetting) obj; 18819 if (ps.pkg != null) { 18820 return ps.pkg.applicationInfo.targetSdkVersion; 18821 } 18822 } 18823 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18824 } 18825 18826 @Override 18827 public void addPreferredActivity(IntentFilter filter, int match, 18828 ComponentName[] set, ComponentName activity, int userId) { 18829 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18830 "Adding preferred"); 18831 } 18832 18833 private void addPreferredActivityInternal(IntentFilter filter, int match, 18834 ComponentName[] set, ComponentName activity, boolean always, int userId, 18835 String opname) { 18836 // writer 18837 int callingUid = Binder.getCallingUid(); 18838 enforceCrossUserPermission(callingUid, userId, 18839 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18840 if (filter.countActions() == 0) { 18841 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18842 return; 18843 } 18844 synchronized (mPackages) { 18845 if (mContext.checkCallingOrSelfPermission( 18846 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18847 != PackageManager.PERMISSION_GRANTED) { 18848 if (getUidTargetSdkVersionLockedLPr(callingUid) 18849 < Build.VERSION_CODES.FROYO) { 18850 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18851 + callingUid); 18852 return; 18853 } 18854 mContext.enforceCallingOrSelfPermission( 18855 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18856 } 18857 18858 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18859 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18860 + userId + ":"); 18861 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18862 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18863 scheduleWritePackageRestrictionsLocked(userId); 18864 postPreferredActivityChangedBroadcast(userId); 18865 } 18866 } 18867 18868 private void postPreferredActivityChangedBroadcast(int userId) { 18869 mHandler.post(() -> { 18870 final IActivityManager am = ActivityManager.getService(); 18871 if (am == null) { 18872 return; 18873 } 18874 18875 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18876 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18877 try { 18878 am.broadcastIntent(null, intent, null, null, 18879 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18880 null, false, false, userId); 18881 } catch (RemoteException e) { 18882 } 18883 }); 18884 } 18885 18886 @Override 18887 public void replacePreferredActivity(IntentFilter filter, int match, 18888 ComponentName[] set, ComponentName activity, int userId) { 18889 if (filter.countActions() != 1) { 18890 throw new IllegalArgumentException( 18891 "replacePreferredActivity expects filter to have only 1 action."); 18892 } 18893 if (filter.countDataAuthorities() != 0 18894 || filter.countDataPaths() != 0 18895 || filter.countDataSchemes() > 1 18896 || filter.countDataTypes() != 0) { 18897 throw new IllegalArgumentException( 18898 "replacePreferredActivity expects filter to have no data authorities, " + 18899 "paths, or types; and at most one scheme."); 18900 } 18901 18902 final int callingUid = Binder.getCallingUid(); 18903 enforceCrossUserPermission(callingUid, userId, 18904 true /* requireFullPermission */, false /* checkShell */, 18905 "replace preferred activity"); 18906 synchronized (mPackages) { 18907 if (mContext.checkCallingOrSelfPermission( 18908 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18909 != PackageManager.PERMISSION_GRANTED) { 18910 if (getUidTargetSdkVersionLockedLPr(callingUid) 18911 < Build.VERSION_CODES.FROYO) { 18912 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18913 + Binder.getCallingUid()); 18914 return; 18915 } 18916 mContext.enforceCallingOrSelfPermission( 18917 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18918 } 18919 18920 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18921 if (pir != null) { 18922 // Get all of the existing entries that exactly match this filter. 18923 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18924 if (existing != null && existing.size() == 1) { 18925 PreferredActivity cur = existing.get(0); 18926 if (DEBUG_PREFERRED) { 18927 Slog.i(TAG, "Checking replace of preferred:"); 18928 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18929 if (!cur.mPref.mAlways) { 18930 Slog.i(TAG, " -- CUR; not mAlways!"); 18931 } else { 18932 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18933 Slog.i(TAG, " -- CUR: mSet=" 18934 + Arrays.toString(cur.mPref.mSetComponents)); 18935 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18936 Slog.i(TAG, " -- NEW: mMatch=" 18937 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18938 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18939 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18940 } 18941 } 18942 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18943 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18944 && cur.mPref.sameSet(set)) { 18945 // Setting the preferred activity to what it happens to be already 18946 if (DEBUG_PREFERRED) { 18947 Slog.i(TAG, "Replacing with same preferred activity " 18948 + cur.mPref.mShortComponent + " for user " 18949 + userId + ":"); 18950 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18951 } 18952 return; 18953 } 18954 } 18955 18956 if (existing != null) { 18957 if (DEBUG_PREFERRED) { 18958 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18959 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18960 } 18961 for (int i = 0; i < existing.size(); i++) { 18962 PreferredActivity pa = existing.get(i); 18963 if (DEBUG_PREFERRED) { 18964 Slog.i(TAG, "Removing existing preferred activity " 18965 + pa.mPref.mComponent + ":"); 18966 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18967 } 18968 pir.removeFilter(pa); 18969 } 18970 } 18971 } 18972 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18973 "Replacing preferred"); 18974 } 18975 } 18976 18977 @Override 18978 public void clearPackagePreferredActivities(String packageName) { 18979 final int uid = Binder.getCallingUid(); 18980 // writer 18981 synchronized (mPackages) { 18982 PackageParser.Package pkg = mPackages.get(packageName); 18983 if (pkg == null || pkg.applicationInfo.uid != uid) { 18984 if (mContext.checkCallingOrSelfPermission( 18985 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18986 != PackageManager.PERMISSION_GRANTED) { 18987 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18988 < Build.VERSION_CODES.FROYO) { 18989 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18990 + Binder.getCallingUid()); 18991 return; 18992 } 18993 mContext.enforceCallingOrSelfPermission( 18994 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18995 } 18996 } 18997 18998 int user = UserHandle.getCallingUserId(); 18999 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19000 scheduleWritePackageRestrictionsLocked(user); 19001 } 19002 } 19003 } 19004 19005 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19006 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19007 ArrayList<PreferredActivity> removed = null; 19008 boolean changed = false; 19009 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19010 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19011 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19012 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19013 continue; 19014 } 19015 Iterator<PreferredActivity> it = pir.filterIterator(); 19016 while (it.hasNext()) { 19017 PreferredActivity pa = it.next(); 19018 // Mark entry for removal only if it matches the package name 19019 // and the entry is of type "always". 19020 if (packageName == null || 19021 (pa.mPref.mComponent.getPackageName().equals(packageName) 19022 && pa.mPref.mAlways)) { 19023 if (removed == null) { 19024 removed = new ArrayList<PreferredActivity>(); 19025 } 19026 removed.add(pa); 19027 } 19028 } 19029 if (removed != null) { 19030 for (int j=0; j<removed.size(); j++) { 19031 PreferredActivity pa = removed.get(j); 19032 pir.removeFilter(pa); 19033 } 19034 changed = true; 19035 } 19036 } 19037 if (changed) { 19038 postPreferredActivityChangedBroadcast(userId); 19039 } 19040 return changed; 19041 } 19042 19043 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19044 private void clearIntentFilterVerificationsLPw(int userId) { 19045 final int packageCount = mPackages.size(); 19046 for (int i = 0; i < packageCount; i++) { 19047 PackageParser.Package pkg = mPackages.valueAt(i); 19048 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19049 } 19050 } 19051 19052 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19053 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19054 if (userId == UserHandle.USER_ALL) { 19055 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19056 sUserManager.getUserIds())) { 19057 for (int oneUserId : sUserManager.getUserIds()) { 19058 scheduleWritePackageRestrictionsLocked(oneUserId); 19059 } 19060 } 19061 } else { 19062 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19063 scheduleWritePackageRestrictionsLocked(userId); 19064 } 19065 } 19066 } 19067 19068 void clearDefaultBrowserIfNeeded(String packageName) { 19069 for (int oneUserId : sUserManager.getUserIds()) { 19070 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19071 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19072 if (packageName.equals(defaultBrowserPackageName)) { 19073 setDefaultBrowserPackageName(null, oneUserId); 19074 } 19075 } 19076 } 19077 19078 @Override 19079 public void resetApplicationPreferences(int userId) { 19080 mContext.enforceCallingOrSelfPermission( 19081 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19082 final long identity = Binder.clearCallingIdentity(); 19083 // writer 19084 try { 19085 synchronized (mPackages) { 19086 clearPackagePreferredActivitiesLPw(null, userId); 19087 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19088 // TODO: We have to reset the default SMS and Phone. This requires 19089 // significant refactoring to keep all default apps in the package 19090 // manager (cleaner but more work) or have the services provide 19091 // callbacks to the package manager to request a default app reset. 19092 applyFactoryDefaultBrowserLPw(userId); 19093 clearIntentFilterVerificationsLPw(userId); 19094 primeDomainVerificationsLPw(userId); 19095 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19096 scheduleWritePackageRestrictionsLocked(userId); 19097 } 19098 resetNetworkPolicies(userId); 19099 } finally { 19100 Binder.restoreCallingIdentity(identity); 19101 } 19102 } 19103 19104 @Override 19105 public int getPreferredActivities(List<IntentFilter> outFilters, 19106 List<ComponentName> outActivities, String packageName) { 19107 19108 int num = 0; 19109 final int userId = UserHandle.getCallingUserId(); 19110 // reader 19111 synchronized (mPackages) { 19112 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19113 if (pir != null) { 19114 final Iterator<PreferredActivity> it = pir.filterIterator(); 19115 while (it.hasNext()) { 19116 final PreferredActivity pa = it.next(); 19117 if (packageName == null 19118 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19119 && pa.mPref.mAlways)) { 19120 if (outFilters != null) { 19121 outFilters.add(new IntentFilter(pa)); 19122 } 19123 if (outActivities != null) { 19124 outActivities.add(pa.mPref.mComponent); 19125 } 19126 } 19127 } 19128 } 19129 } 19130 19131 return num; 19132 } 19133 19134 @Override 19135 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19136 int userId) { 19137 int callingUid = Binder.getCallingUid(); 19138 if (callingUid != Process.SYSTEM_UID) { 19139 throw new SecurityException( 19140 "addPersistentPreferredActivity can only be run by the system"); 19141 } 19142 if (filter.countActions() == 0) { 19143 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19144 return; 19145 } 19146 synchronized (mPackages) { 19147 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19148 ":"); 19149 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19150 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19151 new PersistentPreferredActivity(filter, activity)); 19152 scheduleWritePackageRestrictionsLocked(userId); 19153 postPreferredActivityChangedBroadcast(userId); 19154 } 19155 } 19156 19157 @Override 19158 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19159 int callingUid = Binder.getCallingUid(); 19160 if (callingUid != Process.SYSTEM_UID) { 19161 throw new SecurityException( 19162 "clearPackagePersistentPreferredActivities can only be run by the system"); 19163 } 19164 ArrayList<PersistentPreferredActivity> removed = null; 19165 boolean changed = false; 19166 synchronized (mPackages) { 19167 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19168 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19169 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19170 .valueAt(i); 19171 if (userId != thisUserId) { 19172 continue; 19173 } 19174 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19175 while (it.hasNext()) { 19176 PersistentPreferredActivity ppa = it.next(); 19177 // Mark entry for removal only if it matches the package name. 19178 if (ppa.mComponent.getPackageName().equals(packageName)) { 19179 if (removed == null) { 19180 removed = new ArrayList<PersistentPreferredActivity>(); 19181 } 19182 removed.add(ppa); 19183 } 19184 } 19185 if (removed != null) { 19186 for (int j=0; j<removed.size(); j++) { 19187 PersistentPreferredActivity ppa = removed.get(j); 19188 ppir.removeFilter(ppa); 19189 } 19190 changed = true; 19191 } 19192 } 19193 19194 if (changed) { 19195 scheduleWritePackageRestrictionsLocked(userId); 19196 postPreferredActivityChangedBroadcast(userId); 19197 } 19198 } 19199 } 19200 19201 /** 19202 * Common machinery for picking apart a restored XML blob and passing 19203 * it to a caller-supplied functor to be applied to the running system. 19204 */ 19205 private void restoreFromXml(XmlPullParser parser, int userId, 19206 String expectedStartTag, BlobXmlRestorer functor) 19207 throws IOException, XmlPullParserException { 19208 int type; 19209 while ((type = parser.next()) != XmlPullParser.START_TAG 19210 && type != XmlPullParser.END_DOCUMENT) { 19211 } 19212 if (type != XmlPullParser.START_TAG) { 19213 // oops didn't find a start tag?! 19214 if (DEBUG_BACKUP) { 19215 Slog.e(TAG, "Didn't find start tag during restore"); 19216 } 19217 return; 19218 } 19219Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19220 // this is supposed to be TAG_PREFERRED_BACKUP 19221 if (!expectedStartTag.equals(parser.getName())) { 19222 if (DEBUG_BACKUP) { 19223 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19224 } 19225 return; 19226 } 19227 19228 // skip interfering stuff, then we're aligned with the backing implementation 19229 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19230Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19231 functor.apply(parser, userId); 19232 } 19233 19234 private interface BlobXmlRestorer { 19235 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19236 } 19237 19238 /** 19239 * Non-Binder method, support for the backup/restore mechanism: write the 19240 * full set of preferred activities in its canonical XML format. Returns the 19241 * XML output as a byte array, or null if there is none. 19242 */ 19243 @Override 19244 public byte[] getPreferredActivityBackup(int userId) { 19245 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19246 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19247 } 19248 19249 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19250 try { 19251 final XmlSerializer serializer = new FastXmlSerializer(); 19252 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19253 serializer.startDocument(null, true); 19254 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19255 19256 synchronized (mPackages) { 19257 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19258 } 19259 19260 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19261 serializer.endDocument(); 19262 serializer.flush(); 19263 } catch (Exception e) { 19264 if (DEBUG_BACKUP) { 19265 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19266 } 19267 return null; 19268 } 19269 19270 return dataStream.toByteArray(); 19271 } 19272 19273 @Override 19274 public void restorePreferredActivities(byte[] backup, int userId) { 19275 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19276 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19277 } 19278 19279 try { 19280 final XmlPullParser parser = Xml.newPullParser(); 19281 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19282 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19283 new BlobXmlRestorer() { 19284 @Override 19285 public void apply(XmlPullParser parser, int userId) 19286 throws XmlPullParserException, IOException { 19287 synchronized (mPackages) { 19288 mSettings.readPreferredActivitiesLPw(parser, userId); 19289 } 19290 } 19291 } ); 19292 } catch (Exception e) { 19293 if (DEBUG_BACKUP) { 19294 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19295 } 19296 } 19297 } 19298 19299 /** 19300 * Non-Binder method, support for the backup/restore mechanism: write the 19301 * default browser (etc) settings in its canonical XML format. Returns the default 19302 * browser XML representation as a byte array, or null if there is none. 19303 */ 19304 @Override 19305 public byte[] getDefaultAppsBackup(int userId) { 19306 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19307 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19308 } 19309 19310 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19311 try { 19312 final XmlSerializer serializer = new FastXmlSerializer(); 19313 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19314 serializer.startDocument(null, true); 19315 serializer.startTag(null, TAG_DEFAULT_APPS); 19316 19317 synchronized (mPackages) { 19318 mSettings.writeDefaultAppsLPr(serializer, userId); 19319 } 19320 19321 serializer.endTag(null, TAG_DEFAULT_APPS); 19322 serializer.endDocument(); 19323 serializer.flush(); 19324 } catch (Exception e) { 19325 if (DEBUG_BACKUP) { 19326 Slog.e(TAG, "Unable to write default apps for backup", e); 19327 } 19328 return null; 19329 } 19330 19331 return dataStream.toByteArray(); 19332 } 19333 19334 @Override 19335 public void restoreDefaultApps(byte[] backup, int userId) { 19336 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19337 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19338 } 19339 19340 try { 19341 final XmlPullParser parser = Xml.newPullParser(); 19342 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19343 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19344 new BlobXmlRestorer() { 19345 @Override 19346 public void apply(XmlPullParser parser, int userId) 19347 throws XmlPullParserException, IOException { 19348 synchronized (mPackages) { 19349 mSettings.readDefaultAppsLPw(parser, userId); 19350 } 19351 } 19352 } ); 19353 } catch (Exception e) { 19354 if (DEBUG_BACKUP) { 19355 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19356 } 19357 } 19358 } 19359 19360 @Override 19361 public byte[] getIntentFilterVerificationBackup(int userId) { 19362 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19363 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19364 } 19365 19366 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19367 try { 19368 final XmlSerializer serializer = new FastXmlSerializer(); 19369 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19370 serializer.startDocument(null, true); 19371 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19372 19373 synchronized (mPackages) { 19374 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19375 } 19376 19377 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19378 serializer.endDocument(); 19379 serializer.flush(); 19380 } catch (Exception e) { 19381 if (DEBUG_BACKUP) { 19382 Slog.e(TAG, "Unable to write default apps for backup", e); 19383 } 19384 return null; 19385 } 19386 19387 return dataStream.toByteArray(); 19388 } 19389 19390 @Override 19391 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19392 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19393 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19394 } 19395 19396 try { 19397 final XmlPullParser parser = Xml.newPullParser(); 19398 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19399 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19400 new BlobXmlRestorer() { 19401 @Override 19402 public void apply(XmlPullParser parser, int userId) 19403 throws XmlPullParserException, IOException { 19404 synchronized (mPackages) { 19405 mSettings.readAllDomainVerificationsLPr(parser, userId); 19406 mSettings.writeLPr(); 19407 } 19408 } 19409 } ); 19410 } catch (Exception e) { 19411 if (DEBUG_BACKUP) { 19412 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19413 } 19414 } 19415 } 19416 19417 @Override 19418 public byte[] getPermissionGrantBackup(int userId) { 19419 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19420 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19421 } 19422 19423 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19424 try { 19425 final XmlSerializer serializer = new FastXmlSerializer(); 19426 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19427 serializer.startDocument(null, true); 19428 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19429 19430 synchronized (mPackages) { 19431 serializeRuntimePermissionGrantsLPr(serializer, userId); 19432 } 19433 19434 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19435 serializer.endDocument(); 19436 serializer.flush(); 19437 } catch (Exception e) { 19438 if (DEBUG_BACKUP) { 19439 Slog.e(TAG, "Unable to write default apps for backup", e); 19440 } 19441 return null; 19442 } 19443 19444 return dataStream.toByteArray(); 19445 } 19446 19447 @Override 19448 public void restorePermissionGrants(byte[] backup, int userId) { 19449 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19450 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19451 } 19452 19453 try { 19454 final XmlPullParser parser = Xml.newPullParser(); 19455 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19456 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19457 new BlobXmlRestorer() { 19458 @Override 19459 public void apply(XmlPullParser parser, int userId) 19460 throws XmlPullParserException, IOException { 19461 synchronized (mPackages) { 19462 processRestoredPermissionGrantsLPr(parser, userId); 19463 } 19464 } 19465 } ); 19466 } catch (Exception e) { 19467 if (DEBUG_BACKUP) { 19468 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19469 } 19470 } 19471 } 19472 19473 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19474 throws IOException { 19475 serializer.startTag(null, TAG_ALL_GRANTS); 19476 19477 final int N = mSettings.mPackages.size(); 19478 for (int i = 0; i < N; i++) { 19479 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19480 boolean pkgGrantsKnown = false; 19481 19482 PermissionsState packagePerms = ps.getPermissionsState(); 19483 19484 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19485 final int grantFlags = state.getFlags(); 19486 // only look at grants that are not system/policy fixed 19487 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19488 final boolean isGranted = state.isGranted(); 19489 // And only back up the user-twiddled state bits 19490 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19491 final String packageName = mSettings.mPackages.keyAt(i); 19492 if (!pkgGrantsKnown) { 19493 serializer.startTag(null, TAG_GRANT); 19494 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19495 pkgGrantsKnown = true; 19496 } 19497 19498 final boolean userSet = 19499 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19500 final boolean userFixed = 19501 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19502 final boolean revoke = 19503 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19504 19505 serializer.startTag(null, TAG_PERMISSION); 19506 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19507 if (isGranted) { 19508 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19509 } 19510 if (userSet) { 19511 serializer.attribute(null, ATTR_USER_SET, "true"); 19512 } 19513 if (userFixed) { 19514 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19515 } 19516 if (revoke) { 19517 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19518 } 19519 serializer.endTag(null, TAG_PERMISSION); 19520 } 19521 } 19522 } 19523 19524 if (pkgGrantsKnown) { 19525 serializer.endTag(null, TAG_GRANT); 19526 } 19527 } 19528 19529 serializer.endTag(null, TAG_ALL_GRANTS); 19530 } 19531 19532 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19533 throws XmlPullParserException, IOException { 19534 String pkgName = null; 19535 int outerDepth = parser.getDepth(); 19536 int type; 19537 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19538 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19539 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19540 continue; 19541 } 19542 19543 final String tagName = parser.getName(); 19544 if (tagName.equals(TAG_GRANT)) { 19545 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19546 if (DEBUG_BACKUP) { 19547 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19548 } 19549 } else if (tagName.equals(TAG_PERMISSION)) { 19550 19551 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19552 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19553 19554 int newFlagSet = 0; 19555 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19556 newFlagSet |= FLAG_PERMISSION_USER_SET; 19557 } 19558 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19559 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19560 } 19561 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19562 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19563 } 19564 if (DEBUG_BACKUP) { 19565 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19566 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19567 } 19568 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19569 if (ps != null) { 19570 // Already installed so we apply the grant immediately 19571 if (DEBUG_BACKUP) { 19572 Slog.v(TAG, " + already installed; applying"); 19573 } 19574 PermissionsState perms = ps.getPermissionsState(); 19575 BasePermission bp = mSettings.mPermissions.get(permName); 19576 if (bp != null) { 19577 if (isGranted) { 19578 perms.grantRuntimePermission(bp, userId); 19579 } 19580 if (newFlagSet != 0) { 19581 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19582 } 19583 } 19584 } else { 19585 // Need to wait for post-restore install to apply the grant 19586 if (DEBUG_BACKUP) { 19587 Slog.v(TAG, " - not yet installed; saving for later"); 19588 } 19589 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19590 isGranted, newFlagSet, userId); 19591 } 19592 } else { 19593 PackageManagerService.reportSettingsProblem(Log.WARN, 19594 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19595 XmlUtils.skipCurrentTag(parser); 19596 } 19597 } 19598 19599 scheduleWriteSettingsLocked(); 19600 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19601 } 19602 19603 @Override 19604 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19605 int sourceUserId, int targetUserId, int flags) { 19606 mContext.enforceCallingOrSelfPermission( 19607 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19608 int callingUid = Binder.getCallingUid(); 19609 enforceOwnerRights(ownerPackage, callingUid); 19610 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19611 if (intentFilter.countActions() == 0) { 19612 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19613 return; 19614 } 19615 synchronized (mPackages) { 19616 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19617 ownerPackage, targetUserId, flags); 19618 CrossProfileIntentResolver resolver = 19619 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19620 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19621 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19622 if (existing != null) { 19623 int size = existing.size(); 19624 for (int i = 0; i < size; i++) { 19625 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19626 return; 19627 } 19628 } 19629 } 19630 resolver.addFilter(newFilter); 19631 scheduleWritePackageRestrictionsLocked(sourceUserId); 19632 } 19633 } 19634 19635 @Override 19636 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19637 mContext.enforceCallingOrSelfPermission( 19638 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19639 int callingUid = Binder.getCallingUid(); 19640 enforceOwnerRights(ownerPackage, callingUid); 19641 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19642 synchronized (mPackages) { 19643 CrossProfileIntentResolver resolver = 19644 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19645 ArraySet<CrossProfileIntentFilter> set = 19646 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19647 for (CrossProfileIntentFilter filter : set) { 19648 if (filter.getOwnerPackage().equals(ownerPackage)) { 19649 resolver.removeFilter(filter); 19650 } 19651 } 19652 scheduleWritePackageRestrictionsLocked(sourceUserId); 19653 } 19654 } 19655 19656 // Enforcing that callingUid is owning pkg on userId 19657 private void enforceOwnerRights(String pkg, int callingUid) { 19658 // The system owns everything. 19659 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19660 return; 19661 } 19662 int callingUserId = UserHandle.getUserId(callingUid); 19663 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19664 if (pi == null) { 19665 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19666 + callingUserId); 19667 } 19668 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19669 throw new SecurityException("Calling uid " + callingUid 19670 + " does not own package " + pkg); 19671 } 19672 } 19673 19674 @Override 19675 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19676 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19677 } 19678 19679 /** 19680 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19681 * then reports the most likely home activity or null if there are more than one. 19682 */ 19683 public ComponentName getDefaultHomeActivity(int userId) { 19684 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19685 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19686 if (cn != null) { 19687 return cn; 19688 } 19689 19690 // Find the launcher with the highest priority and return that component if there are no 19691 // other home activity with the same priority. 19692 int lastPriority = Integer.MIN_VALUE; 19693 ComponentName lastComponent = null; 19694 final int size = allHomeCandidates.size(); 19695 for (int i = 0; i < size; i++) { 19696 final ResolveInfo ri = allHomeCandidates.get(i); 19697 if (ri.priority > lastPriority) { 19698 lastComponent = ri.activityInfo.getComponentName(); 19699 lastPriority = ri.priority; 19700 } else if (ri.priority == lastPriority) { 19701 // Two components found with same priority. 19702 lastComponent = null; 19703 } 19704 } 19705 return lastComponent; 19706 } 19707 19708 private Intent getHomeIntent() { 19709 Intent intent = new Intent(Intent.ACTION_MAIN); 19710 intent.addCategory(Intent.CATEGORY_HOME); 19711 intent.addCategory(Intent.CATEGORY_DEFAULT); 19712 return intent; 19713 } 19714 19715 private IntentFilter getHomeFilter() { 19716 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19717 filter.addCategory(Intent.CATEGORY_HOME); 19718 filter.addCategory(Intent.CATEGORY_DEFAULT); 19719 return filter; 19720 } 19721 19722 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19723 int userId) { 19724 Intent intent = getHomeIntent(); 19725 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19726 PackageManager.GET_META_DATA, userId); 19727 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19728 true, false, false, userId); 19729 19730 allHomeCandidates.clear(); 19731 if (list != null) { 19732 for (ResolveInfo ri : list) { 19733 allHomeCandidates.add(ri); 19734 } 19735 } 19736 return (preferred == null || preferred.activityInfo == null) 19737 ? null 19738 : new ComponentName(preferred.activityInfo.packageName, 19739 preferred.activityInfo.name); 19740 } 19741 19742 @Override 19743 public void setHomeActivity(ComponentName comp, int userId) { 19744 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19745 getHomeActivitiesAsUser(homeActivities, userId); 19746 19747 boolean found = false; 19748 19749 final int size = homeActivities.size(); 19750 final ComponentName[] set = new ComponentName[size]; 19751 for (int i = 0; i < size; i++) { 19752 final ResolveInfo candidate = homeActivities.get(i); 19753 final ActivityInfo info = candidate.activityInfo; 19754 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19755 set[i] = activityName; 19756 if (!found && activityName.equals(comp)) { 19757 found = true; 19758 } 19759 } 19760 if (!found) { 19761 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19762 + userId); 19763 } 19764 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19765 set, comp, userId); 19766 } 19767 19768 private @Nullable String getSetupWizardPackageName() { 19769 final Intent intent = new Intent(Intent.ACTION_MAIN); 19770 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19771 19772 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19773 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19774 | MATCH_DISABLED_COMPONENTS, 19775 UserHandle.myUserId()); 19776 if (matches.size() == 1) { 19777 return matches.get(0).getComponentInfo().packageName; 19778 } else { 19779 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19780 + ": matches=" + matches); 19781 return null; 19782 } 19783 } 19784 19785 private @Nullable String getStorageManagerPackageName() { 19786 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19787 19788 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19789 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19790 | MATCH_DISABLED_COMPONENTS, 19791 UserHandle.myUserId()); 19792 if (matches.size() == 1) { 19793 return matches.get(0).getComponentInfo().packageName; 19794 } else { 19795 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19796 + matches.size() + ": matches=" + matches); 19797 return null; 19798 } 19799 } 19800 19801 @Override 19802 public void setApplicationEnabledSetting(String appPackageName, 19803 int newState, int flags, int userId, String callingPackage) { 19804 if (!sUserManager.exists(userId)) return; 19805 if (callingPackage == null) { 19806 callingPackage = Integer.toString(Binder.getCallingUid()); 19807 } 19808 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19809 } 19810 19811 @Override 19812 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19813 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19814 synchronized (mPackages) { 19815 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19816 if (pkgSetting != null) { 19817 pkgSetting.setUpdateAvailable(updateAvailable); 19818 } 19819 } 19820 } 19821 19822 @Override 19823 public void setComponentEnabledSetting(ComponentName componentName, 19824 int newState, int flags, int userId) { 19825 if (!sUserManager.exists(userId)) return; 19826 setEnabledSetting(componentName.getPackageName(), 19827 componentName.getClassName(), newState, flags, userId, null); 19828 } 19829 19830 private void setEnabledSetting(final String packageName, String className, int newState, 19831 final int flags, int userId, String callingPackage) { 19832 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19833 || newState == COMPONENT_ENABLED_STATE_ENABLED 19834 || newState == COMPONENT_ENABLED_STATE_DISABLED 19835 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19836 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19837 throw new IllegalArgumentException("Invalid new component state: " 19838 + newState); 19839 } 19840 PackageSetting pkgSetting; 19841 final int uid = Binder.getCallingUid(); 19842 final int permission; 19843 if (uid == Process.SYSTEM_UID) { 19844 permission = PackageManager.PERMISSION_GRANTED; 19845 } else { 19846 permission = mContext.checkCallingOrSelfPermission( 19847 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19848 } 19849 enforceCrossUserPermission(uid, userId, 19850 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19851 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19852 boolean sendNow = false; 19853 boolean isApp = (className == null); 19854 String componentName = isApp ? packageName : className; 19855 int packageUid = -1; 19856 ArrayList<String> components; 19857 19858 // writer 19859 synchronized (mPackages) { 19860 pkgSetting = mSettings.mPackages.get(packageName); 19861 if (pkgSetting == null) { 19862 if (className == null) { 19863 throw new IllegalArgumentException("Unknown package: " + packageName); 19864 } 19865 throw new IllegalArgumentException( 19866 "Unknown component: " + packageName + "/" + className); 19867 } 19868 } 19869 19870 // Limit who can change which apps 19871 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19872 // Don't allow apps that don't have permission to modify other apps 19873 if (!allowedByPermission) { 19874 throw new SecurityException( 19875 "Permission Denial: attempt to change component state from pid=" 19876 + Binder.getCallingPid() 19877 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19878 } 19879 // Don't allow changing protected packages. 19880 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19881 throw new SecurityException("Cannot disable a protected package: " + packageName); 19882 } 19883 } 19884 19885 synchronized (mPackages) { 19886 if (uid == Process.SHELL_UID 19887 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19888 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19889 // unless it is a test package. 19890 int oldState = pkgSetting.getEnabled(userId); 19891 if (className == null 19892 && 19893 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19894 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19895 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19896 && 19897 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19898 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19899 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19900 // ok 19901 } else { 19902 throw new SecurityException( 19903 "Shell cannot change component state for " + packageName + "/" 19904 + className + " to " + newState); 19905 } 19906 } 19907 if (className == null) { 19908 // We're dealing with an application/package level state change 19909 if (pkgSetting.getEnabled(userId) == newState) { 19910 // Nothing to do 19911 return; 19912 } 19913 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19914 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19915 // Don't care about who enables an app. 19916 callingPackage = null; 19917 } 19918 pkgSetting.setEnabled(newState, userId, callingPackage); 19919 // pkgSetting.pkg.mSetEnabled = newState; 19920 } else { 19921 // We're dealing with a component level state change 19922 // First, verify that this is a valid class name. 19923 PackageParser.Package pkg = pkgSetting.pkg; 19924 if (pkg == null || !pkg.hasComponentClassName(className)) { 19925 if (pkg != null && 19926 pkg.applicationInfo.targetSdkVersion >= 19927 Build.VERSION_CODES.JELLY_BEAN) { 19928 throw new IllegalArgumentException("Component class " + className 19929 + " does not exist in " + packageName); 19930 } else { 19931 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19932 + className + " does not exist in " + packageName); 19933 } 19934 } 19935 switch (newState) { 19936 case COMPONENT_ENABLED_STATE_ENABLED: 19937 if (!pkgSetting.enableComponentLPw(className, userId)) { 19938 return; 19939 } 19940 break; 19941 case COMPONENT_ENABLED_STATE_DISABLED: 19942 if (!pkgSetting.disableComponentLPw(className, userId)) { 19943 return; 19944 } 19945 break; 19946 case COMPONENT_ENABLED_STATE_DEFAULT: 19947 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19948 return; 19949 } 19950 break; 19951 default: 19952 Slog.e(TAG, "Invalid new component state: " + newState); 19953 return; 19954 } 19955 } 19956 scheduleWritePackageRestrictionsLocked(userId); 19957 updateSequenceNumberLP(packageName, new int[] { userId }); 19958 final long callingId = Binder.clearCallingIdentity(); 19959 try { 19960 updateInstantAppInstallerLocked(); 19961 } finally { 19962 Binder.restoreCallingIdentity(callingId); 19963 } 19964 components = mPendingBroadcasts.get(userId, packageName); 19965 final boolean newPackage = components == null; 19966 if (newPackage) { 19967 components = new ArrayList<String>(); 19968 } 19969 if (!components.contains(componentName)) { 19970 components.add(componentName); 19971 } 19972 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19973 sendNow = true; 19974 // Purge entry from pending broadcast list if another one exists already 19975 // since we are sending one right away. 19976 mPendingBroadcasts.remove(userId, packageName); 19977 } else { 19978 if (newPackage) { 19979 mPendingBroadcasts.put(userId, packageName, components); 19980 } 19981 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19982 // Schedule a message 19983 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19984 } 19985 } 19986 } 19987 19988 long callingId = Binder.clearCallingIdentity(); 19989 try { 19990 if (sendNow) { 19991 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19992 sendPackageChangedBroadcast(packageName, 19993 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19994 } 19995 } finally { 19996 Binder.restoreCallingIdentity(callingId); 19997 } 19998 } 19999 20000 @Override 20001 public void flushPackageRestrictionsAsUser(int userId) { 20002 if (!sUserManager.exists(userId)) { 20003 return; 20004 } 20005 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20006 false /* checkShell */, "flushPackageRestrictions"); 20007 synchronized (mPackages) { 20008 mSettings.writePackageRestrictionsLPr(userId); 20009 mDirtyUsers.remove(userId); 20010 if (mDirtyUsers.isEmpty()) { 20011 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20012 } 20013 } 20014 } 20015 20016 private void sendPackageChangedBroadcast(String packageName, 20017 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20018 if (DEBUG_INSTALL) 20019 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20020 + componentNames); 20021 Bundle extras = new Bundle(4); 20022 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20023 String nameList[] = new String[componentNames.size()]; 20024 componentNames.toArray(nameList); 20025 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20026 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20027 extras.putInt(Intent.EXTRA_UID, packageUid); 20028 // If this is not reporting a change of the overall package, then only send it 20029 // to registered receivers. We don't want to launch a swath of apps for every 20030 // little component state change. 20031 final int flags = !componentNames.contains(packageName) 20032 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20033 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20034 new int[] {UserHandle.getUserId(packageUid)}); 20035 } 20036 20037 @Override 20038 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20039 if (!sUserManager.exists(userId)) return; 20040 final int uid = Binder.getCallingUid(); 20041 final int permission = mContext.checkCallingOrSelfPermission( 20042 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20043 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20044 enforceCrossUserPermission(uid, userId, 20045 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20046 // writer 20047 synchronized (mPackages) { 20048 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20049 allowedByPermission, uid, userId)) { 20050 scheduleWritePackageRestrictionsLocked(userId); 20051 } 20052 } 20053 } 20054 20055 @Override 20056 public String getInstallerPackageName(String packageName) { 20057 // reader 20058 synchronized (mPackages) { 20059 return mSettings.getInstallerPackageNameLPr(packageName); 20060 } 20061 } 20062 20063 public boolean isOrphaned(String packageName) { 20064 // reader 20065 synchronized (mPackages) { 20066 return mSettings.isOrphaned(packageName); 20067 } 20068 } 20069 20070 @Override 20071 public int getApplicationEnabledSetting(String packageName, int userId) { 20072 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20073 int uid = Binder.getCallingUid(); 20074 enforceCrossUserPermission(uid, userId, 20075 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20076 // reader 20077 synchronized (mPackages) { 20078 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20079 } 20080 } 20081 20082 @Override 20083 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20084 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20085 int uid = Binder.getCallingUid(); 20086 enforceCrossUserPermission(uid, userId, 20087 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20088 // reader 20089 synchronized (mPackages) { 20090 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20091 } 20092 } 20093 20094 @Override 20095 public void enterSafeMode() { 20096 enforceSystemOrRoot("Only the system can request entering safe mode"); 20097 20098 if (!mSystemReady) { 20099 mSafeMode = true; 20100 } 20101 } 20102 20103 @Override 20104 public void systemReady() { 20105 mSystemReady = true; 20106 20107 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20108 // disabled after already being started. 20109 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20110 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20111 20112 // Read the compatibilty setting when the system is ready. 20113 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20114 mContext.getContentResolver(), 20115 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20116 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20117 if (DEBUG_SETTINGS) { 20118 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20119 } 20120 20121 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20122 20123 synchronized (mPackages) { 20124 // Verify that all of the preferred activity components actually 20125 // exist. It is possible for applications to be updated and at 20126 // that point remove a previously declared activity component that 20127 // had been set as a preferred activity. We try to clean this up 20128 // the next time we encounter that preferred activity, but it is 20129 // possible for the user flow to never be able to return to that 20130 // situation so here we do a sanity check to make sure we haven't 20131 // left any junk around. 20132 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20133 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20134 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20135 removed.clear(); 20136 for (PreferredActivity pa : pir.filterSet()) { 20137 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20138 removed.add(pa); 20139 } 20140 } 20141 if (removed.size() > 0) { 20142 for (int r=0; r<removed.size(); r++) { 20143 PreferredActivity pa = removed.get(r); 20144 Slog.w(TAG, "Removing dangling preferred activity: " 20145 + pa.mPref.mComponent); 20146 pir.removeFilter(pa); 20147 } 20148 mSettings.writePackageRestrictionsLPr( 20149 mSettings.mPreferredActivities.keyAt(i)); 20150 } 20151 } 20152 20153 for (int userId : UserManagerService.getInstance().getUserIds()) { 20154 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20155 grantPermissionsUserIds = ArrayUtils.appendInt( 20156 grantPermissionsUserIds, userId); 20157 } 20158 } 20159 } 20160 sUserManager.systemReady(); 20161 20162 // If we upgraded grant all default permissions before kicking off. 20163 for (int userId : grantPermissionsUserIds) { 20164 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20165 } 20166 20167 // If we did not grant default permissions, we preload from this the 20168 // default permission exceptions lazily to ensure we don't hit the 20169 // disk on a new user creation. 20170 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20171 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20172 } 20173 20174 // Kick off any messages waiting for system ready 20175 if (mPostSystemReadyMessages != null) { 20176 for (Message msg : mPostSystemReadyMessages) { 20177 msg.sendToTarget(); 20178 } 20179 mPostSystemReadyMessages = null; 20180 } 20181 20182 // Watch for external volumes that come and go over time 20183 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20184 storage.registerListener(mStorageListener); 20185 20186 mInstallerService.systemReady(); 20187 mPackageDexOptimizer.systemReady(); 20188 20189 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20190 StorageManagerInternal.class); 20191 StorageManagerInternal.addExternalStoragePolicy( 20192 new StorageManagerInternal.ExternalStorageMountPolicy() { 20193 @Override 20194 public int getMountMode(int uid, String packageName) { 20195 if (Process.isIsolated(uid)) { 20196 return Zygote.MOUNT_EXTERNAL_NONE; 20197 } 20198 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20199 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20200 } 20201 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20202 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20203 } 20204 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20205 return Zygote.MOUNT_EXTERNAL_READ; 20206 } 20207 return Zygote.MOUNT_EXTERNAL_WRITE; 20208 } 20209 20210 @Override 20211 public boolean hasExternalStorage(int uid, String packageName) { 20212 return true; 20213 } 20214 }); 20215 20216 // Now that we're mostly running, clean up stale users and apps 20217 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20218 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20219 20220 if (mPrivappPermissionsViolations != null) { 20221 Slog.wtf(TAG,"Signature|privileged permissions not in " 20222 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20223 mPrivappPermissionsViolations = null; 20224 } 20225 } 20226 20227 public void waitForAppDataPrepared() { 20228 if (mPrepareAppDataFuture == null) { 20229 return; 20230 } 20231 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20232 mPrepareAppDataFuture = null; 20233 } 20234 20235 @Override 20236 public boolean isSafeMode() { 20237 return mSafeMode; 20238 } 20239 20240 @Override 20241 public boolean hasSystemUidErrors() { 20242 return mHasSystemUidErrors; 20243 } 20244 20245 static String arrayToString(int[] array) { 20246 StringBuffer buf = new StringBuffer(128); 20247 buf.append('['); 20248 if (array != null) { 20249 for (int i=0; i<array.length; i++) { 20250 if (i > 0) buf.append(", "); 20251 buf.append(array[i]); 20252 } 20253 } 20254 buf.append(']'); 20255 return buf.toString(); 20256 } 20257 20258 static class DumpState { 20259 public static final int DUMP_LIBS = 1 << 0; 20260 public static final int DUMP_FEATURES = 1 << 1; 20261 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20262 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20263 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20264 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20265 public static final int DUMP_PERMISSIONS = 1 << 6; 20266 public static final int DUMP_PACKAGES = 1 << 7; 20267 public static final int DUMP_SHARED_USERS = 1 << 8; 20268 public static final int DUMP_MESSAGES = 1 << 9; 20269 public static final int DUMP_PROVIDERS = 1 << 10; 20270 public static final int DUMP_VERIFIERS = 1 << 11; 20271 public static final int DUMP_PREFERRED = 1 << 12; 20272 public static final int DUMP_PREFERRED_XML = 1 << 13; 20273 public static final int DUMP_KEYSETS = 1 << 14; 20274 public static final int DUMP_VERSION = 1 << 15; 20275 public static final int DUMP_INSTALLS = 1 << 16; 20276 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20277 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20278 public static final int DUMP_FROZEN = 1 << 19; 20279 public static final int DUMP_DEXOPT = 1 << 20; 20280 public static final int DUMP_COMPILER_STATS = 1 << 21; 20281 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20282 20283 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20284 20285 private int mTypes; 20286 20287 private int mOptions; 20288 20289 private boolean mTitlePrinted; 20290 20291 private SharedUserSetting mSharedUser; 20292 20293 public boolean isDumping(int type) { 20294 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20295 return true; 20296 } 20297 20298 return (mTypes & type) != 0; 20299 } 20300 20301 public void setDump(int type) { 20302 mTypes |= type; 20303 } 20304 20305 public boolean isOptionEnabled(int option) { 20306 return (mOptions & option) != 0; 20307 } 20308 20309 public void setOptionEnabled(int option) { 20310 mOptions |= option; 20311 } 20312 20313 public boolean onTitlePrinted() { 20314 final boolean printed = mTitlePrinted; 20315 mTitlePrinted = true; 20316 return printed; 20317 } 20318 20319 public boolean getTitlePrinted() { 20320 return mTitlePrinted; 20321 } 20322 20323 public void setTitlePrinted(boolean enabled) { 20324 mTitlePrinted = enabled; 20325 } 20326 20327 public SharedUserSetting getSharedUser() { 20328 return mSharedUser; 20329 } 20330 20331 public void setSharedUser(SharedUserSetting user) { 20332 mSharedUser = user; 20333 } 20334 } 20335 20336 @Override 20337 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20338 FileDescriptor err, String[] args, ShellCallback callback, 20339 ResultReceiver resultReceiver) { 20340 (new PackageManagerShellCommand(this)).exec( 20341 this, in, out, err, args, callback, resultReceiver); 20342 } 20343 20344 @Override 20345 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20346 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20347 20348 DumpState dumpState = new DumpState(); 20349 boolean fullPreferred = false; 20350 boolean checkin = false; 20351 20352 String packageName = null; 20353 ArraySet<String> permissionNames = null; 20354 20355 int opti = 0; 20356 while (opti < args.length) { 20357 String opt = args[opti]; 20358 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20359 break; 20360 } 20361 opti++; 20362 20363 if ("-a".equals(opt)) { 20364 // Right now we only know how to print all. 20365 } else if ("-h".equals(opt)) { 20366 pw.println("Package manager dump options:"); 20367 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20368 pw.println(" --checkin: dump for a checkin"); 20369 pw.println(" -f: print details of intent filters"); 20370 pw.println(" -h: print this help"); 20371 pw.println(" cmd may be one of:"); 20372 pw.println(" l[ibraries]: list known shared libraries"); 20373 pw.println(" f[eatures]: list device features"); 20374 pw.println(" k[eysets]: print known keysets"); 20375 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20376 pw.println(" perm[issions]: dump permissions"); 20377 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20378 pw.println(" pref[erred]: print preferred package settings"); 20379 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20380 pw.println(" prov[iders]: dump content providers"); 20381 pw.println(" p[ackages]: dump installed packages"); 20382 pw.println(" s[hared-users]: dump shared user IDs"); 20383 pw.println(" m[essages]: print collected runtime messages"); 20384 pw.println(" v[erifiers]: print package verifier info"); 20385 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20386 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20387 pw.println(" version: print database version info"); 20388 pw.println(" write: write current settings now"); 20389 pw.println(" installs: details about install sessions"); 20390 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20391 pw.println(" dexopt: dump dexopt state"); 20392 pw.println(" compiler-stats: dump compiler statistics"); 20393 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20394 pw.println(" <package.name>: info about given package"); 20395 return; 20396 } else if ("--checkin".equals(opt)) { 20397 checkin = true; 20398 } else if ("-f".equals(opt)) { 20399 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20400 } else if ("--proto".equals(opt)) { 20401 dumpProto(fd); 20402 return; 20403 } else { 20404 pw.println("Unknown argument: " + opt + "; use -h for help"); 20405 } 20406 } 20407 20408 // Is the caller requesting to dump a particular piece of data? 20409 if (opti < args.length) { 20410 String cmd = args[opti]; 20411 opti++; 20412 // Is this a package name? 20413 if ("android".equals(cmd) || cmd.contains(".")) { 20414 packageName = cmd; 20415 // When dumping a single package, we always dump all of its 20416 // filter information since the amount of data will be reasonable. 20417 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20418 } else if ("check-permission".equals(cmd)) { 20419 if (opti >= args.length) { 20420 pw.println("Error: check-permission missing permission argument"); 20421 return; 20422 } 20423 String perm = args[opti]; 20424 opti++; 20425 if (opti >= args.length) { 20426 pw.println("Error: check-permission missing package argument"); 20427 return; 20428 } 20429 20430 String pkg = args[opti]; 20431 opti++; 20432 int user = UserHandle.getUserId(Binder.getCallingUid()); 20433 if (opti < args.length) { 20434 try { 20435 user = Integer.parseInt(args[opti]); 20436 } catch (NumberFormatException e) { 20437 pw.println("Error: check-permission user argument is not a number: " 20438 + args[opti]); 20439 return; 20440 } 20441 } 20442 20443 // Normalize package name to handle renamed packages and static libs 20444 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20445 20446 pw.println(checkPermission(perm, pkg, user)); 20447 return; 20448 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20449 dumpState.setDump(DumpState.DUMP_LIBS); 20450 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20451 dumpState.setDump(DumpState.DUMP_FEATURES); 20452 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20453 if (opti >= args.length) { 20454 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20455 | DumpState.DUMP_SERVICE_RESOLVERS 20456 | DumpState.DUMP_RECEIVER_RESOLVERS 20457 | DumpState.DUMP_CONTENT_RESOLVERS); 20458 } else { 20459 while (opti < args.length) { 20460 String name = args[opti]; 20461 if ("a".equals(name) || "activity".equals(name)) { 20462 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20463 } else if ("s".equals(name) || "service".equals(name)) { 20464 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20465 } else if ("r".equals(name) || "receiver".equals(name)) { 20466 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20467 } else if ("c".equals(name) || "content".equals(name)) { 20468 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20469 } else { 20470 pw.println("Error: unknown resolver table type: " + name); 20471 return; 20472 } 20473 opti++; 20474 } 20475 } 20476 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20477 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20478 } else if ("permission".equals(cmd)) { 20479 if (opti >= args.length) { 20480 pw.println("Error: permission requires permission name"); 20481 return; 20482 } 20483 permissionNames = new ArraySet<>(); 20484 while (opti < args.length) { 20485 permissionNames.add(args[opti]); 20486 opti++; 20487 } 20488 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20489 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20490 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20491 dumpState.setDump(DumpState.DUMP_PREFERRED); 20492 } else if ("preferred-xml".equals(cmd)) { 20493 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20494 if (opti < args.length && "--full".equals(args[opti])) { 20495 fullPreferred = true; 20496 opti++; 20497 } 20498 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20499 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20500 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20501 dumpState.setDump(DumpState.DUMP_PACKAGES); 20502 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20503 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20504 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20505 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20506 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20507 dumpState.setDump(DumpState.DUMP_MESSAGES); 20508 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20509 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20510 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20511 || "intent-filter-verifiers".equals(cmd)) { 20512 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20513 } else if ("version".equals(cmd)) { 20514 dumpState.setDump(DumpState.DUMP_VERSION); 20515 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20516 dumpState.setDump(DumpState.DUMP_KEYSETS); 20517 } else if ("installs".equals(cmd)) { 20518 dumpState.setDump(DumpState.DUMP_INSTALLS); 20519 } else if ("frozen".equals(cmd)) { 20520 dumpState.setDump(DumpState.DUMP_FROZEN); 20521 } else if ("dexopt".equals(cmd)) { 20522 dumpState.setDump(DumpState.DUMP_DEXOPT); 20523 } else if ("compiler-stats".equals(cmd)) { 20524 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20525 } else if ("enabled-overlays".equals(cmd)) { 20526 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20527 } else if ("write".equals(cmd)) { 20528 synchronized (mPackages) { 20529 mSettings.writeLPr(); 20530 pw.println("Settings written."); 20531 return; 20532 } 20533 } 20534 } 20535 20536 if (checkin) { 20537 pw.println("vers,1"); 20538 } 20539 20540 // reader 20541 synchronized (mPackages) { 20542 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20543 if (!checkin) { 20544 if (dumpState.onTitlePrinted()) 20545 pw.println(); 20546 pw.println("Database versions:"); 20547 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20548 } 20549 } 20550 20551 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20552 if (!checkin) { 20553 if (dumpState.onTitlePrinted()) 20554 pw.println(); 20555 pw.println("Verifiers:"); 20556 pw.print(" Required: "); 20557 pw.print(mRequiredVerifierPackage); 20558 pw.print(" (uid="); 20559 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20560 UserHandle.USER_SYSTEM)); 20561 pw.println(")"); 20562 } else if (mRequiredVerifierPackage != null) { 20563 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20564 pw.print(","); 20565 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20566 UserHandle.USER_SYSTEM)); 20567 } 20568 } 20569 20570 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20571 packageName == null) { 20572 if (mIntentFilterVerifierComponent != null) { 20573 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20574 if (!checkin) { 20575 if (dumpState.onTitlePrinted()) 20576 pw.println(); 20577 pw.println("Intent Filter Verifier:"); 20578 pw.print(" Using: "); 20579 pw.print(verifierPackageName); 20580 pw.print(" (uid="); 20581 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20582 UserHandle.USER_SYSTEM)); 20583 pw.println(")"); 20584 } else if (verifierPackageName != null) { 20585 pw.print("ifv,"); pw.print(verifierPackageName); 20586 pw.print(","); 20587 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20588 UserHandle.USER_SYSTEM)); 20589 } 20590 } else { 20591 pw.println(); 20592 pw.println("No Intent Filter Verifier available!"); 20593 } 20594 } 20595 20596 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20597 boolean printedHeader = false; 20598 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20599 while (it.hasNext()) { 20600 String libName = it.next(); 20601 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20602 if (versionedLib == null) { 20603 continue; 20604 } 20605 final int versionCount = versionedLib.size(); 20606 for (int i = 0; i < versionCount; i++) { 20607 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20608 if (!checkin) { 20609 if (!printedHeader) { 20610 if (dumpState.onTitlePrinted()) 20611 pw.println(); 20612 pw.println("Libraries:"); 20613 printedHeader = true; 20614 } 20615 pw.print(" "); 20616 } else { 20617 pw.print("lib,"); 20618 } 20619 pw.print(libEntry.info.getName()); 20620 if (libEntry.info.isStatic()) { 20621 pw.print(" version=" + libEntry.info.getVersion()); 20622 } 20623 if (!checkin) { 20624 pw.print(" -> "); 20625 } 20626 if (libEntry.path != null) { 20627 pw.print(" (jar) "); 20628 pw.print(libEntry.path); 20629 } else { 20630 pw.print(" (apk) "); 20631 pw.print(libEntry.apk); 20632 } 20633 pw.println(); 20634 } 20635 } 20636 } 20637 20638 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20639 if (dumpState.onTitlePrinted()) 20640 pw.println(); 20641 if (!checkin) { 20642 pw.println("Features:"); 20643 } 20644 20645 synchronized (mAvailableFeatures) { 20646 for (FeatureInfo feat : mAvailableFeatures.values()) { 20647 if (checkin) { 20648 pw.print("feat,"); 20649 pw.print(feat.name); 20650 pw.print(","); 20651 pw.println(feat.version); 20652 } else { 20653 pw.print(" "); 20654 pw.print(feat.name); 20655 if (feat.version > 0) { 20656 pw.print(" version="); 20657 pw.print(feat.version); 20658 } 20659 pw.println(); 20660 } 20661 } 20662 } 20663 } 20664 20665 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20666 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20667 : "Activity Resolver Table:", " ", packageName, 20668 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20669 dumpState.setTitlePrinted(true); 20670 } 20671 } 20672 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20673 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20674 : "Receiver Resolver Table:", " ", packageName, 20675 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20676 dumpState.setTitlePrinted(true); 20677 } 20678 } 20679 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20680 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20681 : "Service Resolver Table:", " ", packageName, 20682 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20683 dumpState.setTitlePrinted(true); 20684 } 20685 } 20686 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20687 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20688 : "Provider Resolver Table:", " ", packageName, 20689 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20690 dumpState.setTitlePrinted(true); 20691 } 20692 } 20693 20694 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20695 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20696 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20697 int user = mSettings.mPreferredActivities.keyAt(i); 20698 if (pir.dump(pw, 20699 dumpState.getTitlePrinted() 20700 ? "\nPreferred Activities User " + user + ":" 20701 : "Preferred Activities User " + user + ":", " ", 20702 packageName, true, false)) { 20703 dumpState.setTitlePrinted(true); 20704 } 20705 } 20706 } 20707 20708 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20709 pw.flush(); 20710 FileOutputStream fout = new FileOutputStream(fd); 20711 BufferedOutputStream str = new BufferedOutputStream(fout); 20712 XmlSerializer serializer = new FastXmlSerializer(); 20713 try { 20714 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20715 serializer.startDocument(null, true); 20716 serializer.setFeature( 20717 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20718 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20719 serializer.endDocument(); 20720 serializer.flush(); 20721 } catch (IllegalArgumentException e) { 20722 pw.println("Failed writing: " + e); 20723 } catch (IllegalStateException e) { 20724 pw.println("Failed writing: " + e); 20725 } catch (IOException e) { 20726 pw.println("Failed writing: " + e); 20727 } 20728 } 20729 20730 if (!checkin 20731 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20732 && packageName == null) { 20733 pw.println(); 20734 int count = mSettings.mPackages.size(); 20735 if (count == 0) { 20736 pw.println("No applications!"); 20737 pw.println(); 20738 } else { 20739 final String prefix = " "; 20740 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20741 if (allPackageSettings.size() == 0) { 20742 pw.println("No domain preferred apps!"); 20743 pw.println(); 20744 } else { 20745 pw.println("App verification status:"); 20746 pw.println(); 20747 count = 0; 20748 for (PackageSetting ps : allPackageSettings) { 20749 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20750 if (ivi == null || ivi.getPackageName() == null) continue; 20751 pw.println(prefix + "Package: " + ivi.getPackageName()); 20752 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20753 pw.println(prefix + "Status: " + ivi.getStatusString()); 20754 pw.println(); 20755 count++; 20756 } 20757 if (count == 0) { 20758 pw.println(prefix + "No app verification established."); 20759 pw.println(); 20760 } 20761 for (int userId : sUserManager.getUserIds()) { 20762 pw.println("App linkages for user " + userId + ":"); 20763 pw.println(); 20764 count = 0; 20765 for (PackageSetting ps : allPackageSettings) { 20766 final long status = ps.getDomainVerificationStatusForUser(userId); 20767 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20768 && !DEBUG_DOMAIN_VERIFICATION) { 20769 continue; 20770 } 20771 pw.println(prefix + "Package: " + ps.name); 20772 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20773 String statusStr = IntentFilterVerificationInfo. 20774 getStatusStringFromValue(status); 20775 pw.println(prefix + "Status: " + statusStr); 20776 pw.println(); 20777 count++; 20778 } 20779 if (count == 0) { 20780 pw.println(prefix + "No configured app linkages."); 20781 pw.println(); 20782 } 20783 } 20784 } 20785 } 20786 } 20787 20788 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20789 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20790 if (packageName == null && permissionNames == null) { 20791 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20792 if (iperm == 0) { 20793 if (dumpState.onTitlePrinted()) 20794 pw.println(); 20795 pw.println("AppOp Permissions:"); 20796 } 20797 pw.print(" AppOp Permission "); 20798 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20799 pw.println(":"); 20800 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20801 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20802 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20803 } 20804 } 20805 } 20806 } 20807 20808 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20809 boolean printedSomething = false; 20810 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20811 if (packageName != null && !packageName.equals(p.info.packageName)) { 20812 continue; 20813 } 20814 if (!printedSomething) { 20815 if (dumpState.onTitlePrinted()) 20816 pw.println(); 20817 pw.println("Registered ContentProviders:"); 20818 printedSomething = true; 20819 } 20820 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20821 pw.print(" "); pw.println(p.toString()); 20822 } 20823 printedSomething = false; 20824 for (Map.Entry<String, PackageParser.Provider> entry : 20825 mProvidersByAuthority.entrySet()) { 20826 PackageParser.Provider p = entry.getValue(); 20827 if (packageName != null && !packageName.equals(p.info.packageName)) { 20828 continue; 20829 } 20830 if (!printedSomething) { 20831 if (dumpState.onTitlePrinted()) 20832 pw.println(); 20833 pw.println("ContentProvider Authorities:"); 20834 printedSomething = true; 20835 } 20836 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20837 pw.print(" "); pw.println(p.toString()); 20838 if (p.info != null && p.info.applicationInfo != null) { 20839 final String appInfo = p.info.applicationInfo.toString(); 20840 pw.print(" applicationInfo="); pw.println(appInfo); 20841 } 20842 } 20843 } 20844 20845 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20846 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20847 } 20848 20849 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20850 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20851 } 20852 20853 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20854 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20855 } 20856 20857 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20858 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20859 } 20860 20861 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20862 // XXX should handle packageName != null by dumping only install data that 20863 // the given package is involved with. 20864 if (dumpState.onTitlePrinted()) pw.println(); 20865 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20866 } 20867 20868 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20869 // XXX should handle packageName != null by dumping only install data that 20870 // the given package is involved with. 20871 if (dumpState.onTitlePrinted()) pw.println(); 20872 20873 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20874 ipw.println(); 20875 ipw.println("Frozen packages:"); 20876 ipw.increaseIndent(); 20877 if (mFrozenPackages.size() == 0) { 20878 ipw.println("(none)"); 20879 } else { 20880 for (int i = 0; i < mFrozenPackages.size(); i++) { 20881 ipw.println(mFrozenPackages.valueAt(i)); 20882 } 20883 } 20884 ipw.decreaseIndent(); 20885 } 20886 20887 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20888 if (dumpState.onTitlePrinted()) pw.println(); 20889 dumpDexoptStateLPr(pw, packageName); 20890 } 20891 20892 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20893 if (dumpState.onTitlePrinted()) pw.println(); 20894 dumpCompilerStatsLPr(pw, packageName); 20895 } 20896 20897 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20898 if (dumpState.onTitlePrinted()) pw.println(); 20899 dumpEnabledOverlaysLPr(pw); 20900 } 20901 20902 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20903 if (dumpState.onTitlePrinted()) pw.println(); 20904 mSettings.dumpReadMessagesLPr(pw, dumpState); 20905 20906 pw.println(); 20907 pw.println("Package warning messages:"); 20908 BufferedReader in = null; 20909 String line = null; 20910 try { 20911 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20912 while ((line = in.readLine()) != null) { 20913 if (line.contains("ignored: updated version")) continue; 20914 pw.println(line); 20915 } 20916 } catch (IOException ignored) { 20917 } finally { 20918 IoUtils.closeQuietly(in); 20919 } 20920 } 20921 20922 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20923 BufferedReader in = null; 20924 String line = null; 20925 try { 20926 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20927 while ((line = in.readLine()) != null) { 20928 if (line.contains("ignored: updated version")) continue; 20929 pw.print("msg,"); 20930 pw.println(line); 20931 } 20932 } catch (IOException ignored) { 20933 } finally { 20934 IoUtils.closeQuietly(in); 20935 } 20936 } 20937 } 20938 } 20939 20940 private void dumpProto(FileDescriptor fd) { 20941 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20942 20943 synchronized (mPackages) { 20944 final long requiredVerifierPackageToken = 20945 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20946 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20947 proto.write( 20948 PackageServiceDumpProto.PackageShortProto.UID, 20949 getPackageUid( 20950 mRequiredVerifierPackage, 20951 MATCH_DEBUG_TRIAGED_MISSING, 20952 UserHandle.USER_SYSTEM)); 20953 proto.end(requiredVerifierPackageToken); 20954 20955 if (mIntentFilterVerifierComponent != null) { 20956 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20957 final long verifierPackageToken = 20958 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20959 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20960 proto.write( 20961 PackageServiceDumpProto.PackageShortProto.UID, 20962 getPackageUid( 20963 verifierPackageName, 20964 MATCH_DEBUG_TRIAGED_MISSING, 20965 UserHandle.USER_SYSTEM)); 20966 proto.end(verifierPackageToken); 20967 } 20968 20969 dumpSharedLibrariesProto(proto); 20970 dumpFeaturesProto(proto); 20971 mSettings.dumpPackagesProto(proto); 20972 mSettings.dumpSharedUsersProto(proto); 20973 dumpMessagesProto(proto); 20974 } 20975 proto.flush(); 20976 } 20977 20978 private void dumpMessagesProto(ProtoOutputStream proto) { 20979 BufferedReader in = null; 20980 String line = null; 20981 try { 20982 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20983 while ((line = in.readLine()) != null) { 20984 if (line.contains("ignored: updated version")) continue; 20985 proto.write(PackageServiceDumpProto.MESSAGES, line); 20986 } 20987 } catch (IOException ignored) { 20988 } finally { 20989 IoUtils.closeQuietly(in); 20990 } 20991 } 20992 20993 private void dumpFeaturesProto(ProtoOutputStream proto) { 20994 synchronized (mAvailableFeatures) { 20995 final int count = mAvailableFeatures.size(); 20996 for (int i = 0; i < count; i++) { 20997 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20998 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20999 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21000 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21001 proto.end(featureToken); 21002 } 21003 } 21004 } 21005 21006 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21007 final int count = mSharedLibraries.size(); 21008 for (int i = 0; i < count; i++) { 21009 final String libName = mSharedLibraries.keyAt(i); 21010 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21011 if (versionedLib == null) { 21012 continue; 21013 } 21014 final int versionCount = versionedLib.size(); 21015 for (int j = 0; j < versionCount; j++) { 21016 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21017 final long sharedLibraryToken = 21018 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21019 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21020 final boolean isJar = (libEntry.path != null); 21021 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21022 if (isJar) { 21023 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21024 } else { 21025 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21026 } 21027 proto.end(sharedLibraryToken); 21028 } 21029 } 21030 } 21031 21032 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21033 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21034 ipw.println(); 21035 ipw.println("Dexopt state:"); 21036 ipw.increaseIndent(); 21037 Collection<PackageParser.Package> packages = null; 21038 if (packageName != null) { 21039 PackageParser.Package targetPackage = mPackages.get(packageName); 21040 if (targetPackage != null) { 21041 packages = Collections.singletonList(targetPackage); 21042 } else { 21043 ipw.println("Unable to find package: " + packageName); 21044 return; 21045 } 21046 } else { 21047 packages = mPackages.values(); 21048 } 21049 21050 for (PackageParser.Package pkg : packages) { 21051 ipw.println("[" + pkg.packageName + "]"); 21052 ipw.increaseIndent(); 21053 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21054 ipw.decreaseIndent(); 21055 } 21056 } 21057 21058 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21059 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21060 ipw.println(); 21061 ipw.println("Compiler stats:"); 21062 ipw.increaseIndent(); 21063 Collection<PackageParser.Package> packages = null; 21064 if (packageName != null) { 21065 PackageParser.Package targetPackage = mPackages.get(packageName); 21066 if (targetPackage != null) { 21067 packages = Collections.singletonList(targetPackage); 21068 } else { 21069 ipw.println("Unable to find package: " + packageName); 21070 return; 21071 } 21072 } else { 21073 packages = mPackages.values(); 21074 } 21075 21076 for (PackageParser.Package pkg : packages) { 21077 ipw.println("[" + pkg.packageName + "]"); 21078 ipw.increaseIndent(); 21079 21080 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21081 if (stats == null) { 21082 ipw.println("(No recorded stats)"); 21083 } else { 21084 stats.dump(ipw); 21085 } 21086 ipw.decreaseIndent(); 21087 } 21088 } 21089 21090 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21091 pw.println("Enabled overlay paths:"); 21092 final int N = mEnabledOverlayPaths.size(); 21093 for (int i = 0; i < N; i++) { 21094 final int userId = mEnabledOverlayPaths.keyAt(i); 21095 pw.println(String.format(" User %d:", userId)); 21096 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21097 mEnabledOverlayPaths.valueAt(i); 21098 final int M = userSpecificOverlays.size(); 21099 for (int j = 0; j < M; j++) { 21100 final String targetPackageName = userSpecificOverlays.keyAt(j); 21101 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21102 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21103 } 21104 } 21105 } 21106 21107 private String dumpDomainString(String packageName) { 21108 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21109 .getList(); 21110 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21111 21112 ArraySet<String> result = new ArraySet<>(); 21113 if (iviList.size() > 0) { 21114 for (IntentFilterVerificationInfo ivi : iviList) { 21115 for (String host : ivi.getDomains()) { 21116 result.add(host); 21117 } 21118 } 21119 } 21120 if (filters != null && filters.size() > 0) { 21121 for (IntentFilter filter : filters) { 21122 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21123 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21124 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21125 result.addAll(filter.getHostsList()); 21126 } 21127 } 21128 } 21129 21130 StringBuilder sb = new StringBuilder(result.size() * 16); 21131 for (String domain : result) { 21132 if (sb.length() > 0) sb.append(" "); 21133 sb.append(domain); 21134 } 21135 return sb.toString(); 21136 } 21137 21138 // ------- apps on sdcard specific code ------- 21139 static final boolean DEBUG_SD_INSTALL = false; 21140 21141 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21142 21143 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21144 21145 private boolean mMediaMounted = false; 21146 21147 static String getEncryptKey() { 21148 try { 21149 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21150 SD_ENCRYPTION_KEYSTORE_NAME); 21151 if (sdEncKey == null) { 21152 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21153 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21154 if (sdEncKey == null) { 21155 Slog.e(TAG, "Failed to create encryption keys"); 21156 return null; 21157 } 21158 } 21159 return sdEncKey; 21160 } catch (NoSuchAlgorithmException nsae) { 21161 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21162 return null; 21163 } catch (IOException ioe) { 21164 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21165 return null; 21166 } 21167 } 21168 21169 /* 21170 * Update media status on PackageManager. 21171 */ 21172 @Override 21173 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21174 int callingUid = Binder.getCallingUid(); 21175 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21176 throw new SecurityException("Media status can only be updated by the system"); 21177 } 21178 // reader; this apparently protects mMediaMounted, but should probably 21179 // be a different lock in that case. 21180 synchronized (mPackages) { 21181 Log.i(TAG, "Updating external media status from " 21182 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21183 + (mediaStatus ? "mounted" : "unmounted")); 21184 if (DEBUG_SD_INSTALL) 21185 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21186 + ", mMediaMounted=" + mMediaMounted); 21187 if (mediaStatus == mMediaMounted) { 21188 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21189 : 0, -1); 21190 mHandler.sendMessage(msg); 21191 return; 21192 } 21193 mMediaMounted = mediaStatus; 21194 } 21195 // Queue up an async operation since the package installation may take a 21196 // little while. 21197 mHandler.post(new Runnable() { 21198 public void run() { 21199 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21200 } 21201 }); 21202 } 21203 21204 /** 21205 * Called by StorageManagerService when the initial ASECs to scan are available. 21206 * Should block until all the ASEC containers are finished being scanned. 21207 */ 21208 public void scanAvailableAsecs() { 21209 updateExternalMediaStatusInner(true, false, false); 21210 } 21211 21212 /* 21213 * Collect information of applications on external media, map them against 21214 * existing containers and update information based on current mount status. 21215 * Please note that we always have to report status if reportStatus has been 21216 * set to true especially when unloading packages. 21217 */ 21218 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21219 boolean externalStorage) { 21220 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21221 int[] uidArr = EmptyArray.INT; 21222 21223 final String[] list = PackageHelper.getSecureContainerList(); 21224 if (ArrayUtils.isEmpty(list)) { 21225 Log.i(TAG, "No secure containers found"); 21226 } else { 21227 // Process list of secure containers and categorize them 21228 // as active or stale based on their package internal state. 21229 21230 // reader 21231 synchronized (mPackages) { 21232 for (String cid : list) { 21233 // Leave stages untouched for now; installer service owns them 21234 if (PackageInstallerService.isStageName(cid)) continue; 21235 21236 if (DEBUG_SD_INSTALL) 21237 Log.i(TAG, "Processing container " + cid); 21238 String pkgName = getAsecPackageName(cid); 21239 if (pkgName == null) { 21240 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21241 continue; 21242 } 21243 if (DEBUG_SD_INSTALL) 21244 Log.i(TAG, "Looking for pkg : " + pkgName); 21245 21246 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21247 if (ps == null) { 21248 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21249 continue; 21250 } 21251 21252 /* 21253 * Skip packages that are not external if we're unmounting 21254 * external storage. 21255 */ 21256 if (externalStorage && !isMounted && !isExternal(ps)) { 21257 continue; 21258 } 21259 21260 final AsecInstallArgs args = new AsecInstallArgs(cid, 21261 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21262 // The package status is changed only if the code path 21263 // matches between settings and the container id. 21264 if (ps.codePathString != null 21265 && ps.codePathString.startsWith(args.getCodePath())) { 21266 if (DEBUG_SD_INSTALL) { 21267 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21268 + " at code path: " + ps.codePathString); 21269 } 21270 21271 // We do have a valid package installed on sdcard 21272 processCids.put(args, ps.codePathString); 21273 final int uid = ps.appId; 21274 if (uid != -1) { 21275 uidArr = ArrayUtils.appendInt(uidArr, uid); 21276 } 21277 } else { 21278 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21279 + ps.codePathString); 21280 } 21281 } 21282 } 21283 21284 Arrays.sort(uidArr); 21285 } 21286 21287 // Process packages with valid entries. 21288 if (isMounted) { 21289 if (DEBUG_SD_INSTALL) 21290 Log.i(TAG, "Loading packages"); 21291 loadMediaPackages(processCids, uidArr, externalStorage); 21292 startCleaningPackages(); 21293 mInstallerService.onSecureContainersAvailable(); 21294 } else { 21295 if (DEBUG_SD_INSTALL) 21296 Log.i(TAG, "Unloading packages"); 21297 unloadMediaPackages(processCids, uidArr, reportStatus); 21298 } 21299 } 21300 21301 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21302 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21303 final int size = infos.size(); 21304 final String[] packageNames = new String[size]; 21305 final int[] packageUids = new int[size]; 21306 for (int i = 0; i < size; i++) { 21307 final ApplicationInfo info = infos.get(i); 21308 packageNames[i] = info.packageName; 21309 packageUids[i] = info.uid; 21310 } 21311 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21312 finishedReceiver); 21313 } 21314 21315 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21316 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21317 sendResourcesChangedBroadcast(mediaStatus, replacing, 21318 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21319 } 21320 21321 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21322 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21323 int size = pkgList.length; 21324 if (size > 0) { 21325 // Send broadcasts here 21326 Bundle extras = new Bundle(); 21327 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21328 if (uidArr != null) { 21329 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21330 } 21331 if (replacing) { 21332 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21333 } 21334 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21335 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21336 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21337 } 21338 } 21339 21340 /* 21341 * Look at potentially valid container ids from processCids If package 21342 * information doesn't match the one on record or package scanning fails, 21343 * the cid is added to list of removeCids. We currently don't delete stale 21344 * containers. 21345 */ 21346 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21347 boolean externalStorage) { 21348 ArrayList<String> pkgList = new ArrayList<String>(); 21349 Set<AsecInstallArgs> keys = processCids.keySet(); 21350 21351 for (AsecInstallArgs args : keys) { 21352 String codePath = processCids.get(args); 21353 if (DEBUG_SD_INSTALL) 21354 Log.i(TAG, "Loading container : " + args.cid); 21355 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21356 try { 21357 // Make sure there are no container errors first. 21358 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21359 Slog.e(TAG, "Failed to mount cid : " + args.cid 21360 + " when installing from sdcard"); 21361 continue; 21362 } 21363 // Check code path here. 21364 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21365 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21366 + " does not match one in settings " + codePath); 21367 continue; 21368 } 21369 // Parse package 21370 int parseFlags = mDefParseFlags; 21371 if (args.isExternalAsec()) { 21372 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21373 } 21374 if (args.isFwdLocked()) { 21375 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21376 } 21377 21378 synchronized (mInstallLock) { 21379 PackageParser.Package pkg = null; 21380 try { 21381 // Sadly we don't know the package name yet to freeze it 21382 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21383 SCAN_IGNORE_FROZEN, 0, null); 21384 } catch (PackageManagerException e) { 21385 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21386 } 21387 // Scan the package 21388 if (pkg != null) { 21389 /* 21390 * TODO why is the lock being held? doPostInstall is 21391 * called in other places without the lock. This needs 21392 * to be straightened out. 21393 */ 21394 // writer 21395 synchronized (mPackages) { 21396 retCode = PackageManager.INSTALL_SUCCEEDED; 21397 pkgList.add(pkg.packageName); 21398 // Post process args 21399 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21400 pkg.applicationInfo.uid); 21401 } 21402 } else { 21403 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21404 } 21405 } 21406 21407 } finally { 21408 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21409 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21410 } 21411 } 21412 } 21413 // writer 21414 synchronized (mPackages) { 21415 // If the platform SDK has changed since the last time we booted, 21416 // we need to re-grant app permission to catch any new ones that 21417 // appear. This is really a hack, and means that apps can in some 21418 // cases get permissions that the user didn't initially explicitly 21419 // allow... it would be nice to have some better way to handle 21420 // this situation. 21421 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21422 : mSettings.getInternalVersion(); 21423 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21424 : StorageManager.UUID_PRIVATE_INTERNAL; 21425 21426 int updateFlags = UPDATE_PERMISSIONS_ALL; 21427 if (ver.sdkVersion != mSdkVersion) { 21428 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21429 + mSdkVersion + "; regranting permissions for external"); 21430 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21431 } 21432 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21433 21434 // Yay, everything is now upgraded 21435 ver.forceCurrent(); 21436 21437 // can downgrade to reader 21438 // Persist settings 21439 mSettings.writeLPr(); 21440 } 21441 // Send a broadcast to let everyone know we are done processing 21442 if (pkgList.size() > 0) { 21443 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21444 } 21445 } 21446 21447 /* 21448 * Utility method to unload a list of specified containers 21449 */ 21450 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21451 // Just unmount all valid containers. 21452 for (AsecInstallArgs arg : cidArgs) { 21453 synchronized (mInstallLock) { 21454 arg.doPostDeleteLI(false); 21455 } 21456 } 21457 } 21458 21459 /* 21460 * Unload packages mounted on external media. This involves deleting package 21461 * data from internal structures, sending broadcasts about disabled packages, 21462 * gc'ing to free up references, unmounting all secure containers 21463 * corresponding to packages on external media, and posting a 21464 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21465 * that we always have to post this message if status has been requested no 21466 * matter what. 21467 */ 21468 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21469 final boolean reportStatus) { 21470 if (DEBUG_SD_INSTALL) 21471 Log.i(TAG, "unloading media packages"); 21472 ArrayList<String> pkgList = new ArrayList<String>(); 21473 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21474 final Set<AsecInstallArgs> keys = processCids.keySet(); 21475 for (AsecInstallArgs args : keys) { 21476 String pkgName = args.getPackageName(); 21477 if (DEBUG_SD_INSTALL) 21478 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21479 // Delete package internally 21480 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21481 synchronized (mInstallLock) { 21482 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21483 final boolean res; 21484 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21485 "unloadMediaPackages")) { 21486 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21487 null); 21488 } 21489 if (res) { 21490 pkgList.add(pkgName); 21491 } else { 21492 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21493 failedList.add(args); 21494 } 21495 } 21496 } 21497 21498 // reader 21499 synchronized (mPackages) { 21500 // We didn't update the settings after removing each package; 21501 // write them now for all packages. 21502 mSettings.writeLPr(); 21503 } 21504 21505 // We have to absolutely send UPDATED_MEDIA_STATUS only 21506 // after confirming that all the receivers processed the ordered 21507 // broadcast when packages get disabled, force a gc to clean things up. 21508 // and unload all the containers. 21509 if (pkgList.size() > 0) { 21510 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21511 new IIntentReceiver.Stub() { 21512 public void performReceive(Intent intent, int resultCode, String data, 21513 Bundle extras, boolean ordered, boolean sticky, 21514 int sendingUser) throws RemoteException { 21515 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21516 reportStatus ? 1 : 0, 1, keys); 21517 mHandler.sendMessage(msg); 21518 } 21519 }); 21520 } else { 21521 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21522 keys); 21523 mHandler.sendMessage(msg); 21524 } 21525 } 21526 21527 private void loadPrivatePackages(final VolumeInfo vol) { 21528 mHandler.post(new Runnable() { 21529 @Override 21530 public void run() { 21531 loadPrivatePackagesInner(vol); 21532 } 21533 }); 21534 } 21535 21536 private void loadPrivatePackagesInner(VolumeInfo vol) { 21537 final String volumeUuid = vol.fsUuid; 21538 if (TextUtils.isEmpty(volumeUuid)) { 21539 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21540 return; 21541 } 21542 21543 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21544 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21545 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21546 21547 final VersionInfo ver; 21548 final List<PackageSetting> packages; 21549 synchronized (mPackages) { 21550 ver = mSettings.findOrCreateVersion(volumeUuid); 21551 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21552 } 21553 21554 for (PackageSetting ps : packages) { 21555 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21556 synchronized (mInstallLock) { 21557 final PackageParser.Package pkg; 21558 try { 21559 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21560 loaded.add(pkg.applicationInfo); 21561 21562 } catch (PackageManagerException e) { 21563 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21564 } 21565 21566 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21567 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21568 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21569 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21570 } 21571 } 21572 } 21573 21574 // Reconcile app data for all started/unlocked users 21575 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21576 final UserManager um = mContext.getSystemService(UserManager.class); 21577 UserManagerInternal umInternal = getUserManagerInternal(); 21578 for (UserInfo user : um.getUsers()) { 21579 final int flags; 21580 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21581 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21582 } else if (umInternal.isUserRunning(user.id)) { 21583 flags = StorageManager.FLAG_STORAGE_DE; 21584 } else { 21585 continue; 21586 } 21587 21588 try { 21589 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21590 synchronized (mInstallLock) { 21591 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21592 } 21593 } catch (IllegalStateException e) { 21594 // Device was probably ejected, and we'll process that event momentarily 21595 Slog.w(TAG, "Failed to prepare storage: " + e); 21596 } 21597 } 21598 21599 synchronized (mPackages) { 21600 int updateFlags = UPDATE_PERMISSIONS_ALL; 21601 if (ver.sdkVersion != mSdkVersion) { 21602 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21603 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21604 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21605 } 21606 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21607 21608 // Yay, everything is now upgraded 21609 ver.forceCurrent(); 21610 21611 mSettings.writeLPr(); 21612 } 21613 21614 for (PackageFreezer freezer : freezers) { 21615 freezer.close(); 21616 } 21617 21618 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21619 sendResourcesChangedBroadcast(true, false, loaded, null); 21620 } 21621 21622 private void unloadPrivatePackages(final VolumeInfo vol) { 21623 mHandler.post(new Runnable() { 21624 @Override 21625 public void run() { 21626 unloadPrivatePackagesInner(vol); 21627 } 21628 }); 21629 } 21630 21631 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21632 final String volumeUuid = vol.fsUuid; 21633 if (TextUtils.isEmpty(volumeUuid)) { 21634 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21635 return; 21636 } 21637 21638 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21639 synchronized (mInstallLock) { 21640 synchronized (mPackages) { 21641 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21642 for (PackageSetting ps : packages) { 21643 if (ps.pkg == null) continue; 21644 21645 final ApplicationInfo info = ps.pkg.applicationInfo; 21646 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21647 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21648 21649 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21650 "unloadPrivatePackagesInner")) { 21651 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21652 false, null)) { 21653 unloaded.add(info); 21654 } else { 21655 Slog.w(TAG, "Failed to unload " + ps.codePath); 21656 } 21657 } 21658 21659 // Try very hard to release any references to this package 21660 // so we don't risk the system server being killed due to 21661 // open FDs 21662 AttributeCache.instance().removePackage(ps.name); 21663 } 21664 21665 mSettings.writeLPr(); 21666 } 21667 } 21668 21669 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21670 sendResourcesChangedBroadcast(false, false, unloaded, null); 21671 21672 // Try very hard to release any references to this path so we don't risk 21673 // the system server being killed due to open FDs 21674 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21675 21676 for (int i = 0; i < 3; i++) { 21677 System.gc(); 21678 System.runFinalization(); 21679 } 21680 } 21681 21682 private void assertPackageKnown(String volumeUuid, String packageName) 21683 throws PackageManagerException { 21684 synchronized (mPackages) { 21685 // Normalize package name to handle renamed packages 21686 packageName = normalizePackageNameLPr(packageName); 21687 21688 final PackageSetting ps = mSettings.mPackages.get(packageName); 21689 if (ps == null) { 21690 throw new PackageManagerException("Package " + packageName + " is unknown"); 21691 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21692 throw new PackageManagerException( 21693 "Package " + packageName + " found on unknown volume " + volumeUuid 21694 + "; expected volume " + ps.volumeUuid); 21695 } 21696 } 21697 } 21698 21699 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21700 throws PackageManagerException { 21701 synchronized (mPackages) { 21702 // Normalize package name to handle renamed packages 21703 packageName = normalizePackageNameLPr(packageName); 21704 21705 final PackageSetting ps = mSettings.mPackages.get(packageName); 21706 if (ps == null) { 21707 throw new PackageManagerException("Package " + packageName + " is unknown"); 21708 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21709 throw new PackageManagerException( 21710 "Package " + packageName + " found on unknown volume " + volumeUuid 21711 + "; expected volume " + ps.volumeUuid); 21712 } else if (!ps.getInstalled(userId)) { 21713 throw new PackageManagerException( 21714 "Package " + packageName + " not installed for user " + userId); 21715 } 21716 } 21717 } 21718 21719 private List<String> collectAbsoluteCodePaths() { 21720 synchronized (mPackages) { 21721 List<String> codePaths = new ArrayList<>(); 21722 final int packageCount = mSettings.mPackages.size(); 21723 for (int i = 0; i < packageCount; i++) { 21724 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21725 codePaths.add(ps.codePath.getAbsolutePath()); 21726 } 21727 return codePaths; 21728 } 21729 } 21730 21731 /** 21732 * Examine all apps present on given mounted volume, and destroy apps that 21733 * aren't expected, either due to uninstallation or reinstallation on 21734 * another volume. 21735 */ 21736 private void reconcileApps(String volumeUuid) { 21737 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21738 List<File> filesToDelete = null; 21739 21740 final File[] files = FileUtils.listFilesOrEmpty( 21741 Environment.getDataAppDirectory(volumeUuid)); 21742 for (File file : files) { 21743 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21744 && !PackageInstallerService.isStageName(file.getName()); 21745 if (!isPackage) { 21746 // Ignore entries which are not packages 21747 continue; 21748 } 21749 21750 String absolutePath = file.getAbsolutePath(); 21751 21752 boolean pathValid = false; 21753 final int absoluteCodePathCount = absoluteCodePaths.size(); 21754 for (int i = 0; i < absoluteCodePathCount; i++) { 21755 String absoluteCodePath = absoluteCodePaths.get(i); 21756 if (absolutePath.startsWith(absoluteCodePath)) { 21757 pathValid = true; 21758 break; 21759 } 21760 } 21761 21762 if (!pathValid) { 21763 if (filesToDelete == null) { 21764 filesToDelete = new ArrayList<>(); 21765 } 21766 filesToDelete.add(file); 21767 } 21768 } 21769 21770 if (filesToDelete != null) { 21771 final int fileToDeleteCount = filesToDelete.size(); 21772 for (int i = 0; i < fileToDeleteCount; i++) { 21773 File fileToDelete = filesToDelete.get(i); 21774 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21775 synchronized (mInstallLock) { 21776 removeCodePathLI(fileToDelete); 21777 } 21778 } 21779 } 21780 } 21781 21782 /** 21783 * Reconcile all app data for the given user. 21784 * <p> 21785 * Verifies that directories exist and that ownership and labeling is 21786 * correct for all installed apps on all mounted volumes. 21787 */ 21788 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21789 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21790 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21791 final String volumeUuid = vol.getFsUuid(); 21792 synchronized (mInstallLock) { 21793 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21794 } 21795 } 21796 } 21797 21798 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21799 boolean migrateAppData) { 21800 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21801 } 21802 21803 /** 21804 * Reconcile all app data on given mounted volume. 21805 * <p> 21806 * Destroys app data that isn't expected, either due to uninstallation or 21807 * reinstallation on another volume. 21808 * <p> 21809 * Verifies that directories exist and that ownership and labeling is 21810 * correct for all installed apps. 21811 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21812 */ 21813 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21814 boolean migrateAppData, boolean onlyCoreApps) { 21815 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21816 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21817 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21818 21819 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21820 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21821 21822 // First look for stale data that doesn't belong, and check if things 21823 // have changed since we did our last restorecon 21824 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21825 if (StorageManager.isFileEncryptedNativeOrEmulated() 21826 && !StorageManager.isUserKeyUnlocked(userId)) { 21827 throw new RuntimeException( 21828 "Yikes, someone asked us to reconcile CE storage while " + userId 21829 + " was still locked; this would have caused massive data loss!"); 21830 } 21831 21832 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21833 for (File file : files) { 21834 final String packageName = file.getName(); 21835 try { 21836 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21837 } catch (PackageManagerException e) { 21838 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21839 try { 21840 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21841 StorageManager.FLAG_STORAGE_CE, 0); 21842 } catch (InstallerException e2) { 21843 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21844 } 21845 } 21846 } 21847 } 21848 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21849 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21850 for (File file : files) { 21851 final String packageName = file.getName(); 21852 try { 21853 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21854 } catch (PackageManagerException e) { 21855 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21856 try { 21857 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21858 StorageManager.FLAG_STORAGE_DE, 0); 21859 } catch (InstallerException e2) { 21860 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21861 } 21862 } 21863 } 21864 } 21865 21866 // Ensure that data directories are ready to roll for all packages 21867 // installed for this volume and user 21868 final List<PackageSetting> packages; 21869 synchronized (mPackages) { 21870 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21871 } 21872 int preparedCount = 0; 21873 for (PackageSetting ps : packages) { 21874 final String packageName = ps.name; 21875 if (ps.pkg == null) { 21876 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21877 // TODO: might be due to legacy ASEC apps; we should circle back 21878 // and reconcile again once they're scanned 21879 continue; 21880 } 21881 // Skip non-core apps if requested 21882 if (onlyCoreApps && !ps.pkg.coreApp) { 21883 result.add(packageName); 21884 continue; 21885 } 21886 21887 if (ps.getInstalled(userId)) { 21888 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21889 preparedCount++; 21890 } 21891 } 21892 21893 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21894 return result; 21895 } 21896 21897 /** 21898 * Prepare app data for the given app just after it was installed or 21899 * upgraded. This method carefully only touches users that it's installed 21900 * for, and it forces a restorecon to handle any seinfo changes. 21901 * <p> 21902 * Verifies that directories exist and that ownership and labeling is 21903 * correct for all installed apps. If there is an ownership mismatch, it 21904 * will try recovering system apps by wiping data; third-party app data is 21905 * left intact. 21906 * <p> 21907 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21908 */ 21909 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21910 final PackageSetting ps; 21911 synchronized (mPackages) { 21912 ps = mSettings.mPackages.get(pkg.packageName); 21913 mSettings.writeKernelMappingLPr(ps); 21914 } 21915 21916 final UserManager um = mContext.getSystemService(UserManager.class); 21917 UserManagerInternal umInternal = getUserManagerInternal(); 21918 for (UserInfo user : um.getUsers()) { 21919 final int flags; 21920 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21921 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21922 } else if (umInternal.isUserRunning(user.id)) { 21923 flags = StorageManager.FLAG_STORAGE_DE; 21924 } else { 21925 continue; 21926 } 21927 21928 if (ps.getInstalled(user.id)) { 21929 // TODO: when user data is locked, mark that we're still dirty 21930 prepareAppDataLIF(pkg, user.id, flags); 21931 } 21932 } 21933 } 21934 21935 /** 21936 * Prepare app data for the given app. 21937 * <p> 21938 * Verifies that directories exist and that ownership and labeling is 21939 * correct for all installed apps. If there is an ownership mismatch, this 21940 * will try recovering system apps by wiping data; third-party app data is 21941 * left intact. 21942 */ 21943 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21944 if (pkg == null) { 21945 Slog.wtf(TAG, "Package was null!", new Throwable()); 21946 return; 21947 } 21948 prepareAppDataLeafLIF(pkg, userId, flags); 21949 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21950 for (int i = 0; i < childCount; i++) { 21951 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21952 } 21953 } 21954 21955 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21956 boolean maybeMigrateAppData) { 21957 prepareAppDataLIF(pkg, userId, flags); 21958 21959 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21960 // We may have just shuffled around app data directories, so 21961 // prepare them one more time 21962 prepareAppDataLIF(pkg, userId, flags); 21963 } 21964 } 21965 21966 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21967 if (DEBUG_APP_DATA) { 21968 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21969 + Integer.toHexString(flags)); 21970 } 21971 21972 final String volumeUuid = pkg.volumeUuid; 21973 final String packageName = pkg.packageName; 21974 final ApplicationInfo app = pkg.applicationInfo; 21975 final int appId = UserHandle.getAppId(app.uid); 21976 21977 Preconditions.checkNotNull(app.seInfo); 21978 21979 long ceDataInode = -1; 21980 try { 21981 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21982 appId, app.seInfo, app.targetSdkVersion); 21983 } catch (InstallerException e) { 21984 if (app.isSystemApp()) { 21985 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21986 + ", but trying to recover: " + e); 21987 destroyAppDataLeafLIF(pkg, userId, flags); 21988 try { 21989 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21990 appId, app.seInfo, app.targetSdkVersion); 21991 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21992 } catch (InstallerException e2) { 21993 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21994 } 21995 } else { 21996 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21997 } 21998 } 21999 22000 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22001 // TODO: mark this structure as dirty so we persist it! 22002 synchronized (mPackages) { 22003 final PackageSetting ps = mSettings.mPackages.get(packageName); 22004 if (ps != null) { 22005 ps.setCeDataInode(ceDataInode, userId); 22006 } 22007 } 22008 } 22009 22010 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22011 } 22012 22013 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22014 if (pkg == null) { 22015 Slog.wtf(TAG, "Package was null!", new Throwable()); 22016 return; 22017 } 22018 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22019 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22020 for (int i = 0; i < childCount; i++) { 22021 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22022 } 22023 } 22024 22025 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22026 final String volumeUuid = pkg.volumeUuid; 22027 final String packageName = pkg.packageName; 22028 final ApplicationInfo app = pkg.applicationInfo; 22029 22030 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22031 // Create a native library symlink only if we have native libraries 22032 // and if the native libraries are 32 bit libraries. We do not provide 22033 // this symlink for 64 bit libraries. 22034 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22035 final String nativeLibPath = app.nativeLibraryDir; 22036 try { 22037 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22038 nativeLibPath, userId); 22039 } catch (InstallerException e) { 22040 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22041 } 22042 } 22043 } 22044 } 22045 22046 /** 22047 * For system apps on non-FBE devices, this method migrates any existing 22048 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22049 * requested by the app. 22050 */ 22051 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22052 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22053 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22054 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22055 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22056 try { 22057 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22058 storageTarget); 22059 } catch (InstallerException e) { 22060 logCriticalInfo(Log.WARN, 22061 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22062 } 22063 return true; 22064 } else { 22065 return false; 22066 } 22067 } 22068 22069 public PackageFreezer freezePackage(String packageName, String killReason) { 22070 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22071 } 22072 22073 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22074 return new PackageFreezer(packageName, userId, killReason); 22075 } 22076 22077 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22078 String killReason) { 22079 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22080 } 22081 22082 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22083 String killReason) { 22084 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22085 return new PackageFreezer(); 22086 } else { 22087 return freezePackage(packageName, userId, killReason); 22088 } 22089 } 22090 22091 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22092 String killReason) { 22093 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22094 } 22095 22096 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22097 String killReason) { 22098 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22099 return new PackageFreezer(); 22100 } else { 22101 return freezePackage(packageName, userId, killReason); 22102 } 22103 } 22104 22105 /** 22106 * Class that freezes and kills the given package upon creation, and 22107 * unfreezes it upon closing. This is typically used when doing surgery on 22108 * app code/data to prevent the app from running while you're working. 22109 */ 22110 private class PackageFreezer implements AutoCloseable { 22111 private final String mPackageName; 22112 private final PackageFreezer[] mChildren; 22113 22114 private final boolean mWeFroze; 22115 22116 private final AtomicBoolean mClosed = new AtomicBoolean(); 22117 private final CloseGuard mCloseGuard = CloseGuard.get(); 22118 22119 /** 22120 * Create and return a stub freezer that doesn't actually do anything, 22121 * typically used when someone requested 22122 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22123 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22124 */ 22125 public PackageFreezer() { 22126 mPackageName = null; 22127 mChildren = null; 22128 mWeFroze = false; 22129 mCloseGuard.open("close"); 22130 } 22131 22132 public PackageFreezer(String packageName, int userId, String killReason) { 22133 synchronized (mPackages) { 22134 mPackageName = packageName; 22135 mWeFroze = mFrozenPackages.add(mPackageName); 22136 22137 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22138 if (ps != null) { 22139 killApplication(ps.name, ps.appId, userId, killReason); 22140 } 22141 22142 final PackageParser.Package p = mPackages.get(packageName); 22143 if (p != null && p.childPackages != null) { 22144 final int N = p.childPackages.size(); 22145 mChildren = new PackageFreezer[N]; 22146 for (int i = 0; i < N; i++) { 22147 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22148 userId, killReason); 22149 } 22150 } else { 22151 mChildren = null; 22152 } 22153 } 22154 mCloseGuard.open("close"); 22155 } 22156 22157 @Override 22158 protected void finalize() throws Throwable { 22159 try { 22160 mCloseGuard.warnIfOpen(); 22161 close(); 22162 } finally { 22163 super.finalize(); 22164 } 22165 } 22166 22167 @Override 22168 public void close() { 22169 mCloseGuard.close(); 22170 if (mClosed.compareAndSet(false, true)) { 22171 synchronized (mPackages) { 22172 if (mWeFroze) { 22173 mFrozenPackages.remove(mPackageName); 22174 } 22175 22176 if (mChildren != null) { 22177 for (PackageFreezer freezer : mChildren) { 22178 freezer.close(); 22179 } 22180 } 22181 } 22182 } 22183 } 22184 } 22185 22186 /** 22187 * Verify that given package is currently frozen. 22188 */ 22189 private void checkPackageFrozen(String packageName) { 22190 synchronized (mPackages) { 22191 if (!mFrozenPackages.contains(packageName)) { 22192 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22193 } 22194 } 22195 } 22196 22197 @Override 22198 public int movePackage(final String packageName, final String volumeUuid) { 22199 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22200 22201 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22202 final int moveId = mNextMoveId.getAndIncrement(); 22203 mHandler.post(new Runnable() { 22204 @Override 22205 public void run() { 22206 try { 22207 movePackageInternal(packageName, volumeUuid, moveId, user); 22208 } catch (PackageManagerException e) { 22209 Slog.w(TAG, "Failed to move " + packageName, e); 22210 mMoveCallbacks.notifyStatusChanged(moveId, 22211 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22212 } 22213 } 22214 }); 22215 return moveId; 22216 } 22217 22218 private void movePackageInternal(final String packageName, final String volumeUuid, 22219 final int moveId, UserHandle user) throws PackageManagerException { 22220 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22221 final PackageManager pm = mContext.getPackageManager(); 22222 22223 final boolean currentAsec; 22224 final String currentVolumeUuid; 22225 final File codeFile; 22226 final String installerPackageName; 22227 final String packageAbiOverride; 22228 final int appId; 22229 final String seinfo; 22230 final String label; 22231 final int targetSdkVersion; 22232 final PackageFreezer freezer; 22233 final int[] installedUserIds; 22234 22235 // reader 22236 synchronized (mPackages) { 22237 final PackageParser.Package pkg = mPackages.get(packageName); 22238 final PackageSetting ps = mSettings.mPackages.get(packageName); 22239 if (pkg == null || ps == null) { 22240 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22241 } 22242 22243 if (pkg.applicationInfo.isSystemApp()) { 22244 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22245 "Cannot move system application"); 22246 } 22247 22248 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22249 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22250 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22251 if (isInternalStorage && !allow3rdPartyOnInternal) { 22252 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22253 "3rd party apps are not allowed on internal storage"); 22254 } 22255 22256 if (pkg.applicationInfo.isExternalAsec()) { 22257 currentAsec = true; 22258 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22259 } else if (pkg.applicationInfo.isForwardLocked()) { 22260 currentAsec = true; 22261 currentVolumeUuid = "forward_locked"; 22262 } else { 22263 currentAsec = false; 22264 currentVolumeUuid = ps.volumeUuid; 22265 22266 final File probe = new File(pkg.codePath); 22267 final File probeOat = new File(probe, "oat"); 22268 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22269 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22270 "Move only supported for modern cluster style installs"); 22271 } 22272 } 22273 22274 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22275 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22276 "Package already moved to " + volumeUuid); 22277 } 22278 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22279 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22280 "Device admin cannot be moved"); 22281 } 22282 22283 if (mFrozenPackages.contains(packageName)) { 22284 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22285 "Failed to move already frozen package"); 22286 } 22287 22288 codeFile = new File(pkg.codePath); 22289 installerPackageName = ps.installerPackageName; 22290 packageAbiOverride = ps.cpuAbiOverrideString; 22291 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22292 seinfo = pkg.applicationInfo.seInfo; 22293 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22294 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22295 freezer = freezePackage(packageName, "movePackageInternal"); 22296 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22297 } 22298 22299 final Bundle extras = new Bundle(); 22300 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22301 extras.putString(Intent.EXTRA_TITLE, label); 22302 mMoveCallbacks.notifyCreated(moveId, extras); 22303 22304 int installFlags; 22305 final boolean moveCompleteApp; 22306 final File measurePath; 22307 22308 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22309 installFlags = INSTALL_INTERNAL; 22310 moveCompleteApp = !currentAsec; 22311 measurePath = Environment.getDataAppDirectory(volumeUuid); 22312 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22313 installFlags = INSTALL_EXTERNAL; 22314 moveCompleteApp = false; 22315 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22316 } else { 22317 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22318 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22319 || !volume.isMountedWritable()) { 22320 freezer.close(); 22321 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22322 "Move location not mounted private volume"); 22323 } 22324 22325 Preconditions.checkState(!currentAsec); 22326 22327 installFlags = INSTALL_INTERNAL; 22328 moveCompleteApp = true; 22329 measurePath = Environment.getDataAppDirectory(volumeUuid); 22330 } 22331 22332 final PackageStats stats = new PackageStats(null, -1); 22333 synchronized (mInstaller) { 22334 for (int userId : installedUserIds) { 22335 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22336 freezer.close(); 22337 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22338 "Failed to measure package size"); 22339 } 22340 } 22341 } 22342 22343 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22344 + stats.dataSize); 22345 22346 final long startFreeBytes = measurePath.getUsableSpace(); 22347 final long sizeBytes; 22348 if (moveCompleteApp) { 22349 sizeBytes = stats.codeSize + stats.dataSize; 22350 } else { 22351 sizeBytes = stats.codeSize; 22352 } 22353 22354 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22355 freezer.close(); 22356 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22357 "Not enough free space to move"); 22358 } 22359 22360 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22361 22362 final CountDownLatch installedLatch = new CountDownLatch(1); 22363 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22364 @Override 22365 public void onUserActionRequired(Intent intent) throws RemoteException { 22366 throw new IllegalStateException(); 22367 } 22368 22369 @Override 22370 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22371 Bundle extras) throws RemoteException { 22372 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22373 + PackageManager.installStatusToString(returnCode, msg)); 22374 22375 installedLatch.countDown(); 22376 freezer.close(); 22377 22378 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22379 switch (status) { 22380 case PackageInstaller.STATUS_SUCCESS: 22381 mMoveCallbacks.notifyStatusChanged(moveId, 22382 PackageManager.MOVE_SUCCEEDED); 22383 break; 22384 case PackageInstaller.STATUS_FAILURE_STORAGE: 22385 mMoveCallbacks.notifyStatusChanged(moveId, 22386 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22387 break; 22388 default: 22389 mMoveCallbacks.notifyStatusChanged(moveId, 22390 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22391 break; 22392 } 22393 } 22394 }; 22395 22396 final MoveInfo move; 22397 if (moveCompleteApp) { 22398 // Kick off a thread to report progress estimates 22399 new Thread() { 22400 @Override 22401 public void run() { 22402 while (true) { 22403 try { 22404 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22405 break; 22406 } 22407 } catch (InterruptedException ignored) { 22408 } 22409 22410 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22411 final int progress = 10 + (int) MathUtils.constrain( 22412 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22413 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22414 } 22415 } 22416 }.start(); 22417 22418 final String dataAppName = codeFile.getName(); 22419 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22420 dataAppName, appId, seinfo, targetSdkVersion); 22421 } else { 22422 move = null; 22423 } 22424 22425 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22426 22427 final Message msg = mHandler.obtainMessage(INIT_COPY); 22428 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22429 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22430 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22431 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22432 PackageManager.INSTALL_REASON_UNKNOWN); 22433 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22434 msg.obj = params; 22435 22436 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22437 System.identityHashCode(msg.obj)); 22438 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22439 System.identityHashCode(msg.obj)); 22440 22441 mHandler.sendMessage(msg); 22442 } 22443 22444 @Override 22445 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22446 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22447 22448 final int realMoveId = mNextMoveId.getAndIncrement(); 22449 final Bundle extras = new Bundle(); 22450 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22451 mMoveCallbacks.notifyCreated(realMoveId, extras); 22452 22453 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22454 @Override 22455 public void onCreated(int moveId, Bundle extras) { 22456 // Ignored 22457 } 22458 22459 @Override 22460 public void onStatusChanged(int moveId, int status, long estMillis) { 22461 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22462 } 22463 }; 22464 22465 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22466 storage.setPrimaryStorageUuid(volumeUuid, callback); 22467 return realMoveId; 22468 } 22469 22470 @Override 22471 public int getMoveStatus(int moveId) { 22472 mContext.enforceCallingOrSelfPermission( 22473 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22474 return mMoveCallbacks.mLastStatus.get(moveId); 22475 } 22476 22477 @Override 22478 public void registerMoveCallback(IPackageMoveObserver callback) { 22479 mContext.enforceCallingOrSelfPermission( 22480 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22481 mMoveCallbacks.register(callback); 22482 } 22483 22484 @Override 22485 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22486 mContext.enforceCallingOrSelfPermission( 22487 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22488 mMoveCallbacks.unregister(callback); 22489 } 22490 22491 @Override 22492 public boolean setInstallLocation(int loc) { 22493 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22494 null); 22495 if (getInstallLocation() == loc) { 22496 return true; 22497 } 22498 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22499 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22500 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22501 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22502 return true; 22503 } 22504 return false; 22505 } 22506 22507 @Override 22508 public int getInstallLocation() { 22509 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22510 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22511 PackageHelper.APP_INSTALL_AUTO); 22512 } 22513 22514 /** Called by UserManagerService */ 22515 void cleanUpUser(UserManagerService userManager, int userHandle) { 22516 synchronized (mPackages) { 22517 mDirtyUsers.remove(userHandle); 22518 mUserNeedsBadging.delete(userHandle); 22519 mSettings.removeUserLPw(userHandle); 22520 mPendingBroadcasts.remove(userHandle); 22521 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22522 removeUnusedPackagesLPw(userManager, userHandle); 22523 } 22524 } 22525 22526 /** 22527 * We're removing userHandle and would like to remove any downloaded packages 22528 * that are no longer in use by any other user. 22529 * @param userHandle the user being removed 22530 */ 22531 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22532 final boolean DEBUG_CLEAN_APKS = false; 22533 int [] users = userManager.getUserIds(); 22534 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22535 while (psit.hasNext()) { 22536 PackageSetting ps = psit.next(); 22537 if (ps.pkg == null) { 22538 continue; 22539 } 22540 final String packageName = ps.pkg.packageName; 22541 // Skip over if system app 22542 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22543 continue; 22544 } 22545 if (DEBUG_CLEAN_APKS) { 22546 Slog.i(TAG, "Checking package " + packageName); 22547 } 22548 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22549 if (keep) { 22550 if (DEBUG_CLEAN_APKS) { 22551 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22552 } 22553 } else { 22554 for (int i = 0; i < users.length; i++) { 22555 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22556 keep = true; 22557 if (DEBUG_CLEAN_APKS) { 22558 Slog.i(TAG, " Keeping package " + packageName + " for user " 22559 + users[i]); 22560 } 22561 break; 22562 } 22563 } 22564 } 22565 if (!keep) { 22566 if (DEBUG_CLEAN_APKS) { 22567 Slog.i(TAG, " Removing package " + packageName); 22568 } 22569 mHandler.post(new Runnable() { 22570 public void run() { 22571 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22572 userHandle, 0); 22573 } //end run 22574 }); 22575 } 22576 } 22577 } 22578 22579 /** Called by UserManagerService */ 22580 void createNewUser(int userId, String[] disallowedPackages) { 22581 synchronized (mInstallLock) { 22582 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22583 } 22584 synchronized (mPackages) { 22585 scheduleWritePackageRestrictionsLocked(userId); 22586 scheduleWritePackageListLocked(userId); 22587 applyFactoryDefaultBrowserLPw(userId); 22588 primeDomainVerificationsLPw(userId); 22589 } 22590 } 22591 22592 void onNewUserCreated(final int userId) { 22593 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22594 // If permission review for legacy apps is required, we represent 22595 // dagerous permissions for such apps as always granted runtime 22596 // permissions to keep per user flag state whether review is needed. 22597 // Hence, if a new user is added we have to propagate dangerous 22598 // permission grants for these legacy apps. 22599 if (mPermissionReviewRequired) { 22600 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22601 | UPDATE_PERMISSIONS_REPLACE_ALL); 22602 } 22603 } 22604 22605 @Override 22606 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22607 mContext.enforceCallingOrSelfPermission( 22608 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22609 "Only package verification agents can read the verifier device identity"); 22610 22611 synchronized (mPackages) { 22612 return mSettings.getVerifierDeviceIdentityLPw(); 22613 } 22614 } 22615 22616 @Override 22617 public void setPermissionEnforced(String permission, boolean enforced) { 22618 // TODO: Now that we no longer change GID for storage, this should to away. 22619 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22620 "setPermissionEnforced"); 22621 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22622 synchronized (mPackages) { 22623 if (mSettings.mReadExternalStorageEnforced == null 22624 || mSettings.mReadExternalStorageEnforced != enforced) { 22625 mSettings.mReadExternalStorageEnforced = enforced; 22626 mSettings.writeLPr(); 22627 } 22628 } 22629 // kill any non-foreground processes so we restart them and 22630 // grant/revoke the GID. 22631 final IActivityManager am = ActivityManager.getService(); 22632 if (am != null) { 22633 final long token = Binder.clearCallingIdentity(); 22634 try { 22635 am.killProcessesBelowForeground("setPermissionEnforcement"); 22636 } catch (RemoteException e) { 22637 } finally { 22638 Binder.restoreCallingIdentity(token); 22639 } 22640 } 22641 } else { 22642 throw new IllegalArgumentException("No selective enforcement for " + permission); 22643 } 22644 } 22645 22646 @Override 22647 @Deprecated 22648 public boolean isPermissionEnforced(String permission) { 22649 return true; 22650 } 22651 22652 @Override 22653 public boolean isStorageLow() { 22654 final long token = Binder.clearCallingIdentity(); 22655 try { 22656 final DeviceStorageMonitorInternal 22657 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22658 if (dsm != null) { 22659 return dsm.isMemoryLow(); 22660 } else { 22661 return false; 22662 } 22663 } finally { 22664 Binder.restoreCallingIdentity(token); 22665 } 22666 } 22667 22668 @Override 22669 public IPackageInstaller getPackageInstaller() { 22670 return mInstallerService; 22671 } 22672 22673 private boolean userNeedsBadging(int userId) { 22674 int index = mUserNeedsBadging.indexOfKey(userId); 22675 if (index < 0) { 22676 final UserInfo userInfo; 22677 final long token = Binder.clearCallingIdentity(); 22678 try { 22679 userInfo = sUserManager.getUserInfo(userId); 22680 } finally { 22681 Binder.restoreCallingIdentity(token); 22682 } 22683 final boolean b; 22684 if (userInfo != null && userInfo.isManagedProfile()) { 22685 b = true; 22686 } else { 22687 b = false; 22688 } 22689 mUserNeedsBadging.put(userId, b); 22690 return b; 22691 } 22692 return mUserNeedsBadging.valueAt(index); 22693 } 22694 22695 @Override 22696 public KeySet getKeySetByAlias(String packageName, String alias) { 22697 if (packageName == null || alias == null) { 22698 return null; 22699 } 22700 synchronized(mPackages) { 22701 final PackageParser.Package pkg = mPackages.get(packageName); 22702 if (pkg == null) { 22703 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22704 throw new IllegalArgumentException("Unknown package: " + packageName); 22705 } 22706 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22707 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22708 } 22709 } 22710 22711 @Override 22712 public KeySet getSigningKeySet(String packageName) { 22713 if (packageName == null) { 22714 return null; 22715 } 22716 synchronized(mPackages) { 22717 final PackageParser.Package pkg = mPackages.get(packageName); 22718 if (pkg == null) { 22719 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22720 throw new IllegalArgumentException("Unknown package: " + packageName); 22721 } 22722 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22723 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22724 throw new SecurityException("May not access signing KeySet of other apps."); 22725 } 22726 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22727 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22728 } 22729 } 22730 22731 @Override 22732 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22733 if (packageName == null || ks == null) { 22734 return false; 22735 } 22736 synchronized(mPackages) { 22737 final PackageParser.Package pkg = mPackages.get(packageName); 22738 if (pkg == null) { 22739 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22740 throw new IllegalArgumentException("Unknown package: " + packageName); 22741 } 22742 IBinder ksh = ks.getToken(); 22743 if (ksh instanceof KeySetHandle) { 22744 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22745 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22746 } 22747 return false; 22748 } 22749 } 22750 22751 @Override 22752 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22753 if (packageName == null || ks == null) { 22754 return false; 22755 } 22756 synchronized(mPackages) { 22757 final PackageParser.Package pkg = mPackages.get(packageName); 22758 if (pkg == null) { 22759 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22760 throw new IllegalArgumentException("Unknown package: " + packageName); 22761 } 22762 IBinder ksh = ks.getToken(); 22763 if (ksh instanceof KeySetHandle) { 22764 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22765 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22766 } 22767 return false; 22768 } 22769 } 22770 22771 private void deletePackageIfUnusedLPr(final String packageName) { 22772 PackageSetting ps = mSettings.mPackages.get(packageName); 22773 if (ps == null) { 22774 return; 22775 } 22776 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22777 // TODO Implement atomic delete if package is unused 22778 // It is currently possible that the package will be deleted even if it is installed 22779 // after this method returns. 22780 mHandler.post(new Runnable() { 22781 public void run() { 22782 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22783 0, PackageManager.DELETE_ALL_USERS); 22784 } 22785 }); 22786 } 22787 } 22788 22789 /** 22790 * Check and throw if the given before/after packages would be considered a 22791 * downgrade. 22792 */ 22793 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22794 throws PackageManagerException { 22795 if (after.versionCode < before.mVersionCode) { 22796 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22797 "Update version code " + after.versionCode + " is older than current " 22798 + before.mVersionCode); 22799 } else if (after.versionCode == before.mVersionCode) { 22800 if (after.baseRevisionCode < before.baseRevisionCode) { 22801 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22802 "Update base revision code " + after.baseRevisionCode 22803 + " is older than current " + before.baseRevisionCode); 22804 } 22805 22806 if (!ArrayUtils.isEmpty(after.splitNames)) { 22807 for (int i = 0; i < after.splitNames.length; i++) { 22808 final String splitName = after.splitNames[i]; 22809 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22810 if (j != -1) { 22811 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22812 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22813 "Update split " + splitName + " revision code " 22814 + after.splitRevisionCodes[i] + " is older than current " 22815 + before.splitRevisionCodes[j]); 22816 } 22817 } 22818 } 22819 } 22820 } 22821 } 22822 22823 private static class MoveCallbacks extends Handler { 22824 private static final int MSG_CREATED = 1; 22825 private static final int MSG_STATUS_CHANGED = 2; 22826 22827 private final RemoteCallbackList<IPackageMoveObserver> 22828 mCallbacks = new RemoteCallbackList<>(); 22829 22830 private final SparseIntArray mLastStatus = new SparseIntArray(); 22831 22832 public MoveCallbacks(Looper looper) { 22833 super(looper); 22834 } 22835 22836 public void register(IPackageMoveObserver callback) { 22837 mCallbacks.register(callback); 22838 } 22839 22840 public void unregister(IPackageMoveObserver callback) { 22841 mCallbacks.unregister(callback); 22842 } 22843 22844 @Override 22845 public void handleMessage(Message msg) { 22846 final SomeArgs args = (SomeArgs) msg.obj; 22847 final int n = mCallbacks.beginBroadcast(); 22848 for (int i = 0; i < n; i++) { 22849 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22850 try { 22851 invokeCallback(callback, msg.what, args); 22852 } catch (RemoteException ignored) { 22853 } 22854 } 22855 mCallbacks.finishBroadcast(); 22856 args.recycle(); 22857 } 22858 22859 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22860 throws RemoteException { 22861 switch (what) { 22862 case MSG_CREATED: { 22863 callback.onCreated(args.argi1, (Bundle) args.arg2); 22864 break; 22865 } 22866 case MSG_STATUS_CHANGED: { 22867 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22868 break; 22869 } 22870 } 22871 } 22872 22873 private void notifyCreated(int moveId, Bundle extras) { 22874 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22875 22876 final SomeArgs args = SomeArgs.obtain(); 22877 args.argi1 = moveId; 22878 args.arg2 = extras; 22879 obtainMessage(MSG_CREATED, args).sendToTarget(); 22880 } 22881 22882 private void notifyStatusChanged(int moveId, int status) { 22883 notifyStatusChanged(moveId, status, -1); 22884 } 22885 22886 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22887 Slog.v(TAG, "Move " + moveId + " status " + status); 22888 22889 final SomeArgs args = SomeArgs.obtain(); 22890 args.argi1 = moveId; 22891 args.argi2 = status; 22892 args.arg3 = estMillis; 22893 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22894 22895 synchronized (mLastStatus) { 22896 mLastStatus.put(moveId, status); 22897 } 22898 } 22899 } 22900 22901 private final static class OnPermissionChangeListeners extends Handler { 22902 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22903 22904 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22905 new RemoteCallbackList<>(); 22906 22907 public OnPermissionChangeListeners(Looper looper) { 22908 super(looper); 22909 } 22910 22911 @Override 22912 public void handleMessage(Message msg) { 22913 switch (msg.what) { 22914 case MSG_ON_PERMISSIONS_CHANGED: { 22915 final int uid = msg.arg1; 22916 handleOnPermissionsChanged(uid); 22917 } break; 22918 } 22919 } 22920 22921 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22922 mPermissionListeners.register(listener); 22923 22924 } 22925 22926 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22927 mPermissionListeners.unregister(listener); 22928 } 22929 22930 public void onPermissionsChanged(int uid) { 22931 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22932 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22933 } 22934 } 22935 22936 private void handleOnPermissionsChanged(int uid) { 22937 final int count = mPermissionListeners.beginBroadcast(); 22938 try { 22939 for (int i = 0; i < count; i++) { 22940 IOnPermissionsChangeListener callback = mPermissionListeners 22941 .getBroadcastItem(i); 22942 try { 22943 callback.onPermissionsChanged(uid); 22944 } catch (RemoteException e) { 22945 Log.e(TAG, "Permission listener is dead", e); 22946 } 22947 } 22948 } finally { 22949 mPermissionListeners.finishBroadcast(); 22950 } 22951 } 22952 } 22953 22954 private class PackageManagerInternalImpl extends PackageManagerInternal { 22955 @Override 22956 public void setLocationPackagesProvider(PackagesProvider provider) { 22957 synchronized (mPackages) { 22958 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22959 } 22960 } 22961 22962 @Override 22963 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22964 synchronized (mPackages) { 22965 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22966 } 22967 } 22968 22969 @Override 22970 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22971 synchronized (mPackages) { 22972 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22973 } 22974 } 22975 22976 @Override 22977 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22978 synchronized (mPackages) { 22979 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22980 } 22981 } 22982 22983 @Override 22984 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22985 synchronized (mPackages) { 22986 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22987 } 22988 } 22989 22990 @Override 22991 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22992 synchronized (mPackages) { 22993 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22994 } 22995 } 22996 22997 @Override 22998 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22999 synchronized (mPackages) { 23000 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23001 packageName, userId); 23002 } 23003 } 23004 23005 @Override 23006 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23007 synchronized (mPackages) { 23008 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23009 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23010 packageName, userId); 23011 } 23012 } 23013 23014 @Override 23015 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23016 synchronized (mPackages) { 23017 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23018 packageName, userId); 23019 } 23020 } 23021 23022 @Override 23023 public void setKeepUninstalledPackages(final List<String> packageList) { 23024 Preconditions.checkNotNull(packageList); 23025 List<String> removedFromList = null; 23026 synchronized (mPackages) { 23027 if (mKeepUninstalledPackages != null) { 23028 final int packagesCount = mKeepUninstalledPackages.size(); 23029 for (int i = 0; i < packagesCount; i++) { 23030 String oldPackage = mKeepUninstalledPackages.get(i); 23031 if (packageList != null && packageList.contains(oldPackage)) { 23032 continue; 23033 } 23034 if (removedFromList == null) { 23035 removedFromList = new ArrayList<>(); 23036 } 23037 removedFromList.add(oldPackage); 23038 } 23039 } 23040 mKeepUninstalledPackages = new ArrayList<>(packageList); 23041 if (removedFromList != null) { 23042 final int removedCount = removedFromList.size(); 23043 for (int i = 0; i < removedCount; i++) { 23044 deletePackageIfUnusedLPr(removedFromList.get(i)); 23045 } 23046 } 23047 } 23048 } 23049 23050 @Override 23051 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23052 synchronized (mPackages) { 23053 // If we do not support permission review, done. 23054 if (!mPermissionReviewRequired) { 23055 return false; 23056 } 23057 23058 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23059 if (packageSetting == null) { 23060 return false; 23061 } 23062 23063 // Permission review applies only to apps not supporting the new permission model. 23064 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23065 return false; 23066 } 23067 23068 // Legacy apps have the permission and get user consent on launch. 23069 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23070 return permissionsState.isPermissionReviewRequired(userId); 23071 } 23072 } 23073 23074 @Override 23075 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23076 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23077 } 23078 23079 @Override 23080 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23081 int userId) { 23082 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23083 } 23084 23085 @Override 23086 public void setDeviceAndProfileOwnerPackages( 23087 int deviceOwnerUserId, String deviceOwnerPackage, 23088 SparseArray<String> profileOwnerPackages) { 23089 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23090 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23091 } 23092 23093 @Override 23094 public boolean isPackageDataProtected(int userId, String packageName) { 23095 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23096 } 23097 23098 @Override 23099 public boolean isPackageEphemeral(int userId, String packageName) { 23100 synchronized (mPackages) { 23101 final PackageSetting ps = mSettings.mPackages.get(packageName); 23102 return ps != null ? ps.getInstantApp(userId) : false; 23103 } 23104 } 23105 23106 @Override 23107 public boolean wasPackageEverLaunched(String packageName, int userId) { 23108 synchronized (mPackages) { 23109 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23110 } 23111 } 23112 23113 @Override 23114 public void grantRuntimePermission(String packageName, String name, int userId, 23115 boolean overridePolicy) { 23116 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23117 overridePolicy); 23118 } 23119 23120 @Override 23121 public void revokeRuntimePermission(String packageName, String name, int userId, 23122 boolean overridePolicy) { 23123 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23124 overridePolicy); 23125 } 23126 23127 @Override 23128 public String getNameForUid(int uid) { 23129 return PackageManagerService.this.getNameForUid(uid); 23130 } 23131 23132 @Override 23133 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23134 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23135 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23136 responseObj, origIntent, resolvedType, callingPackage, userId); 23137 } 23138 23139 @Override 23140 public void grantEphemeralAccess(int userId, Intent intent, 23141 int targetAppId, int ephemeralAppId) { 23142 synchronized (mPackages) { 23143 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23144 targetAppId, ephemeralAppId); 23145 } 23146 } 23147 23148 @Override 23149 public boolean isInstantAppInstallerComponent(ComponentName component) { 23150 synchronized (mPackages) { 23151 return component != null && component.equals(mInstantAppInstallerComponent); 23152 } 23153 } 23154 23155 @Override 23156 public void pruneInstantApps() { 23157 synchronized (mPackages) { 23158 mInstantAppRegistry.pruneInstantAppsLPw(); 23159 } 23160 } 23161 23162 @Override 23163 public String getSetupWizardPackageName() { 23164 return mSetupWizardPackage; 23165 } 23166 23167 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23168 if (policy != null) { 23169 mExternalSourcesPolicy = policy; 23170 } 23171 } 23172 23173 @Override 23174 public boolean isPackagePersistent(String packageName) { 23175 synchronized (mPackages) { 23176 PackageParser.Package pkg = mPackages.get(packageName); 23177 return pkg != null 23178 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23179 | ApplicationInfo.FLAG_PERSISTENT)) == 23180 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23181 : false; 23182 } 23183 } 23184 23185 @Override 23186 public List<PackageInfo> getOverlayPackages(int userId) { 23187 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23188 synchronized (mPackages) { 23189 for (PackageParser.Package p : mPackages.values()) { 23190 if (p.mOverlayTarget != null) { 23191 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23192 if (pkg != null) { 23193 overlayPackages.add(pkg); 23194 } 23195 } 23196 } 23197 } 23198 return overlayPackages; 23199 } 23200 23201 @Override 23202 public List<String> getTargetPackageNames(int userId) { 23203 List<String> targetPackages = new ArrayList<>(); 23204 synchronized (mPackages) { 23205 for (PackageParser.Package p : mPackages.values()) { 23206 if (p.mOverlayTarget == null) { 23207 targetPackages.add(p.packageName); 23208 } 23209 } 23210 } 23211 return targetPackages; 23212 } 23213 23214 @Override 23215 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23216 @Nullable List<String> overlayPackageNames) { 23217 synchronized (mPackages) { 23218 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23219 Slog.e(TAG, "failed to find package " + targetPackageName); 23220 return false; 23221 } 23222 23223 ArrayList<String> paths = null; 23224 if (overlayPackageNames != null) { 23225 final int N = overlayPackageNames.size(); 23226 paths = new ArrayList<>(N); 23227 for (int i = 0; i < N; i++) { 23228 final String packageName = overlayPackageNames.get(i); 23229 final PackageParser.Package pkg = mPackages.get(packageName); 23230 if (pkg == null) { 23231 Slog.e(TAG, "failed to find package " + packageName); 23232 return false; 23233 } 23234 paths.add(pkg.baseCodePath); 23235 } 23236 } 23237 23238 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23239 mEnabledOverlayPaths.get(userId); 23240 if (userSpecificOverlays == null) { 23241 userSpecificOverlays = new ArrayMap<>(); 23242 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23243 } 23244 23245 if (paths != null && paths.size() > 0) { 23246 userSpecificOverlays.put(targetPackageName, paths); 23247 } else { 23248 userSpecificOverlays.remove(targetPackageName); 23249 } 23250 return true; 23251 } 23252 } 23253 23254 @Override 23255 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23256 int flags, int userId) { 23257 return resolveIntentInternal( 23258 intent, resolvedType, flags, userId, true /*includeInstantApps*/); 23259 } 23260 23261 @Override 23262 public ResolveInfo resolveService(Intent intent, String resolvedType, 23263 int flags, int userId, int callingUid) { 23264 return resolveServiceInternal( 23265 intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/); 23266 } 23267 23268 23269 @Override 23270 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23271 synchronized (mPackages) { 23272 mIsolatedOwners.put(isolatedUid, ownerUid); 23273 } 23274 } 23275 23276 @Override 23277 public void removeIsolatedUid(int isolatedUid) { 23278 synchronized (mPackages) { 23279 mIsolatedOwners.delete(isolatedUid); 23280 } 23281 } 23282 } 23283 23284 @Override 23285 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23286 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23287 synchronized (mPackages) { 23288 final long identity = Binder.clearCallingIdentity(); 23289 try { 23290 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23291 packageNames, userId); 23292 } finally { 23293 Binder.restoreCallingIdentity(identity); 23294 } 23295 } 23296 } 23297 23298 @Override 23299 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23300 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23301 synchronized (mPackages) { 23302 final long identity = Binder.clearCallingIdentity(); 23303 try { 23304 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23305 packageNames, userId); 23306 } finally { 23307 Binder.restoreCallingIdentity(identity); 23308 } 23309 } 23310 } 23311 23312 private static void enforceSystemOrPhoneCaller(String tag) { 23313 int callingUid = Binder.getCallingUid(); 23314 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23315 throw new SecurityException( 23316 "Cannot call " + tag + " from UID " + callingUid); 23317 } 23318 } 23319 23320 boolean isHistoricalPackageUsageAvailable() { 23321 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23322 } 23323 23324 /** 23325 * Return a <b>copy</b> of the collection of packages known to the package manager. 23326 * @return A copy of the values of mPackages. 23327 */ 23328 Collection<PackageParser.Package> getPackages() { 23329 synchronized (mPackages) { 23330 return new ArrayList<>(mPackages.values()); 23331 } 23332 } 23333 23334 /** 23335 * Logs process start information (including base APK hash) to the security log. 23336 * @hide 23337 */ 23338 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23339 String apkFile, int pid) { 23340 if (!SecurityLog.isLoggingEnabled()) { 23341 return; 23342 } 23343 Bundle data = new Bundle(); 23344 data.putLong("startTimestamp", System.currentTimeMillis()); 23345 data.putString("processName", processName); 23346 data.putInt("uid", uid); 23347 data.putString("seinfo", seinfo); 23348 data.putString("apkFile", apkFile); 23349 data.putInt("pid", pid); 23350 Message msg = mProcessLoggingHandler.obtainMessage( 23351 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23352 msg.setData(data); 23353 mProcessLoggingHandler.sendMessage(msg); 23354 } 23355 23356 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23357 return mCompilerStats.getPackageStats(pkgName); 23358 } 23359 23360 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23361 return getOrCreateCompilerPackageStats(pkg.packageName); 23362 } 23363 23364 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23365 return mCompilerStats.getOrCreatePackageStats(pkgName); 23366 } 23367 23368 public void deleteCompilerPackageStats(String pkgName) { 23369 mCompilerStats.deletePackageStats(pkgName); 23370 } 23371 23372 @Override 23373 public int getInstallReason(String packageName, int userId) { 23374 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23375 true /* requireFullPermission */, false /* checkShell */, 23376 "get install reason"); 23377 synchronized (mPackages) { 23378 final PackageSetting ps = mSettings.mPackages.get(packageName); 23379 if (ps != null) { 23380 return ps.getInstallReason(userId); 23381 } 23382 } 23383 return PackageManager.INSTALL_REASON_UNKNOWN; 23384 } 23385 23386 @Override 23387 public boolean canRequestPackageInstalls(String packageName, int userId) { 23388 int callingUid = Binder.getCallingUid(); 23389 int uid = getPackageUid(packageName, 0, userId); 23390 if (callingUid != uid && callingUid != Process.ROOT_UID 23391 && callingUid != Process.SYSTEM_UID) { 23392 throw new SecurityException( 23393 "Caller uid " + callingUid + " does not own package " + packageName); 23394 } 23395 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23396 if (info == null) { 23397 return false; 23398 } 23399 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23400 throw new UnsupportedOperationException( 23401 "Operation only supported on apps targeting Android O or higher"); 23402 } 23403 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23404 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23405 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23406 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23407 } 23408 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23409 return false; 23410 } 23411 if (mExternalSourcesPolicy != null) { 23412 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23413 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23414 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23415 } 23416 } 23417 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23418 } 23419 23420 @Override 23421 public ComponentName getInstantAppResolverSettingsComponent() { 23422 return mInstantAppResolverSettingsComponent; 23423 } 23424} 23425